%Simple voltage clamp dirver
clear all
%trash any existing analog i/o objects
delete(daqfind);

%define the input
adaptor = 'nidaq';
adaptorData = daqhwinfo(adaptor);
%get the adaptor id, 
%but note that the brackets are curly {}
%because the struct is an cellarray
id = adaptorData.InstalledBoardIds{1} ;

% Create an analog input object with two channels.
Fs = 5000;
ai = analoginput(adaptor, id);
set(ai, 'SampleRate', Fs);
% Configure the analog input object to trigger manually.
set(ai, 'SamplesPerTrigger', Fs/5); % 1/5 second
set(ai, 'TriggerRepeat', 1);
set(ai, 'TriggerType', 'manual');
chIn = addchannel(ai, [0 1]);

%Create an analog output object with one channel
%then zero the output
ao = analogoutput(adaptor, id);
chOut = addchannel(ao, [0]);

%NOTE -- the analog output voltage will be inverted electronically!
Vrest = 2.5;
putsample(ao,Vrest) %set the membrane to resting potential
pause(1.0) %let system settle
Vstep = 2.0;

%trigger the input
start(ai);
trigger(ai);
%wait 0.05 then step voltage
pause(.05)
putsample(ao,Vstep)
%get the data and plot it
%ch0 is clamp output v(:,1) -- ch1 is memb v v(:,2)
[v,time] = getdata(ai);
%set the membrane back to rest level
putsample(ao,Vrest) 

figure(2); clf;
subplot(2,1,1)
plot(time,v(:,2));
hold on
plot(time,v(:,1),'r')
set(gca,'ylim',[-3 0])
title('V vs T')
ylabel('voltage (volts)')
legend('actual Vmemb','command V')

%subtract command and actual membrane voltage to get current estimate
subplot(2,1,2)
plot(time,(v(:,1)-v(:,2))/75);
%set(gca,'ylim',[-.15 0.05])
title('(Vin-Vmemb)/Rclamp vs T')
ylabel('current (amps)')
%trash the analog objects
stop(ai);
delete(ai);
delete(ao);




