
clear; clf; figure(1);

sample_rate = 10000;
plot_window = 1;     %% how often is the plot refreshed; 
duration = 40;         %% how long does the experiment run

d = daq.getDevices;  d =d(1);  %%% Get the devices you have plugged in, assume only one device

s = daq.createSession('ni');                       %%% start the session
s.addAnalogInputChannel(d.ID, 'ai0', 'Voltage');   %%% Add channel ai0 
s.addAnalogInputChannel(d.ID, 'ai1', 'Voltage');   %%% Add channel ai1
s.Channels(1).Range = [-2.5 2.5];                      %%% set input range for ai0
s.Channels(2).Range = [-2.5 2.5];                      %%% set input range for ai1


s.Rate = sample_rate;               %% set the sample rate
s.DurationInSeconds = duration;     %% set the duration of the experiment
N_channels = length(s.Channels); 


s    %% print session information to confirm properties 


%%% open a log file to save the data and plot and regular intervals
%%% These examples were taken from the MATLAB help examples 
fid1 = fopen('DAQlog.bin','w');
lh_log = s.addlistener('DataAvailable',@(src, event)logData(src, event, fid1));
lh_plot = s.addlistener('DataAvailable', @(src,event) plot(event.TimeStamps, event.Data));
s.NotifyWhenDataAvailableExceeds = sample_rate*plot_window;

%%% start the acquisitions
s.startBackground();   %% run in the background so we can see data while it is coming
s.wait();              %% wait until it is done

%%% clear the handles and close the log file. 
delete(lh_log);  delete(lh_plot);  fclose(fid1);


%%% load the data from the file to the workspace
fid2 = fopen('DAQlog.bin','r');
[data,count]= fread(fid2,[N_channels+1,inf],'double'); fclose(fid2);


%%% Plot the data
time = data(1,:);  data = data(2:N_channels+1,:);
plot(time,data);


