clear; figure(1); clf; daqreset;

%%% parameters for the experiment
sample_rate = 1000;  
plot_duration = 1;   %% how frequent to plot
exp_duration = 60;   %% how long to collect data for

%%% Set up the parameters to acquire the data
AI = analoginput('nidaq','Brian');    
chan = addchannel(AI,[0]);
set(AI,'SampleRate',sample_rate);
set(AI,'SamplesPerTrigger',inf);
set(AI.Channel(1),'InputRange',[-2 2]);

start(AI);

all_Emf = []; all_time = []; all_T = [];  %% for storing all the data
for i =1:ceil(exp_duration/plot_duration)
    
    while AI.SamplesAvailable < sample_rate*plot_duration   %% wait until enough data
    end 
    [data time] = getdata(AI,(sample_rate*plot_duration));  %% get the dataa

    %%% convert voltage to temperature
    a = [    0.000000E+00   1.978425E+01 -2.001204E-01  1.036969E-02 ...   
        -2.549687E-04   3.585153E-06  -5.344285E-08  5.099890E-10  0.000000E+00 ]; %%type J 
    E = data(:,1)/50*1000;  %% thermocouple EMF voltage in mV (50 is gain of circuit)

    %%% Polynomial fit for the V-Temperature curve
    T = zeros(size(data));
    for n = 0:length(a)-1
        T = T + a(n+1)*E.^n;
    end
    
    %%% save all the data, 
    all_Emf = [all_Emf;E];   
    all_time = [all_time;time];
    all_T = [all_T;T];
    
    %%% plot the current and all data to show two different time scales. 
     subplot(2,1,2);
     plot(all_time,all_Emf);        
     xlabel('t (sec)'); ylabel('mV');
     
     subplot(2,1,1)
     plot(all_time,all_T);             
     xlabel('t (sec)'); ylabel('T (C)');

     drawnow;
end

delete(AI);
clear AI;