%Clear data, reset and initialize plot
clear; figure(1); clf; daqreset;

sampleRate = 5000;  %% samples per second
expDuration = 20;   %% duration of experiment in seconds
plotDuration = 3;   %% plot window duration in seconds

%%% intializa and setup the analog input device
NID = daqhwinfo('nidaq'); NID = NID.InstalledBoardIds{1}; %%Find the device ID
AI = analoginput('nidaq',NID);
set(AI,'SampleRate',sampleRate);
set(AI,'SamplesPerTrigger',inf);

%%% Set up channels, 
addchannel(AI,[0]);
set(AI.Channel(1),'InputRange',[-2.5 2.5]);
set(AI.Channel(1),'InputRange',[-10 10]);


allData = []; allTime = []; %% Initialize variables for storing all the data
start(AI);                  %% start the device 
tic;                        %% Start timer
while toc <= expDuration
    
    while AI.SamplesAvailable == 0
        pause(1/sampleRate); %wait for average time required to get 1 sample
    end
    
    [newData newTime] = getdata(AI,AI.SamplesAvailable); %get new data since last read

    %%% add new data - Note if experiment is very long, should pre-allocate
    allData = [allData;newData]; allTime = [allTime;newTime];
    
    %%% Create the plot
    if (length(allTime)> sampleRate*plotDuration)
        Np = sampleRate*plotDuration;
        plot(allTime(end-Np:end),allData(end-Np:end,:));
        axis([min(allTime(end-Np:end)) max(allTime(end-Np:end)) min(allData(:,1)) max(allData(:,1))])
    else
        plot(allTime(:,1),allData(:,1));
        axis([min(allTime) max(allTime) -inf inf])
    end
     xlabel('t (sec)'); ylabel('V');
     
     drawnow;
end

stop(AI); 
