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

%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/50); % 
set(ai, 'TriggerRepeat', 1);
set(ai, 'TriggerType', 'manual');
chIn = addchannel(ai, [0 1]);
%configure gain
ai.Channel.InputRange = [-1 1];

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

%NOTE -- the analog output voltage will be inverted electronically!
    Vrest = 0.1;
Vsteps = [0.08  0.07   0.06  0.05   0.02  ];
colors = gray(length(Vsteps));
styles = {'k', 'k', 'k-.',  'k:', 'k--'};
[b,a] = butter(2,.2);

for i=1:length(Vsteps)
    
    putsample(ao,Vrest) %set the membrane to resting potential
    pause(0.2) %let system settle
    Vstep = Vsteps(i);

    %trigger the input
    start(ai);
    trigger(ai);
    
    %wait to  step voltage
   % pause(.001-toc)
    putsample(ao,Vstep)
    %get the data and plot it
    %ch1 is clamp cmd v(:,2) -- ch0 is current+cmd v(:,2)
    [v,time] = getdata(ai);
    %set the membrane back to rest level
    putsample(ao,Vrest)
    stop(ai);
    if i==1
        continue
    end
    subplot(2,1,1)
    %plot(time,v(:,2));
    
    plot(time,v(:,1), styles{i} ,'linewidth',2) %'color',colors(i,:)
    hold on
    set(gca,'ylim',[-0.1 0])
    title('V vs T')
    ylabel('command voltage (volts)')
    %legend('actual Vmemb','command V')

    %subtract command and actual membrane voltage to get current estimate
    subplot(2,1,2)
    Current = filter(b,a,(v(:,2)-v(:,1))/10000 );
    %Current = (v(:,2)-v(:,1))/10000 ;
    plot(time,Current, styles{i}, 'linewidth',2);
    hold on
    %set(gca,'ylim',[-.001 0.001])
    title('(Current vs T')
    ylabel('current (amps)')
    
end

%trash the analog objects
delete(ai);
delete(ao);




