close all; clear all; clc

% include tclab.m for initialization
tclabFall2018;

disp('This experiment powers Heater 1 in a pulse train fashion according to ATV tuning, and reports temperature 1')

figure(1)
t1s = [];
h1s = [];
t_axis =[];
% initial heater values
ht1 = 0;
ht2 = 0;
h1(ht1);
h2(ht2);
baseline=50;
h = 10; % heater of ATV input
t1 = T1C();
tbase=0;
tic;

for i = 1:2200
    tdelay=toc;
    t1 = T1C();
    if t1-tbase>=1; ht1=baseline-h; end
    if t1-tbase<-1; ht1=baseline+h; end
    if i<700; ht1=baseline-h; end
    if i<600; ht1= baseline; end
    h1(ht1);
    if i==599; tbase = T1C(); end
  
    % plot heater and temperature data
    h1s = [h1s,ht1];
    t1s = [t1s,t1];
    t_axis = [t_axis,toc];
    clf
    subplot(2,1,1)
    plot(t_axis,t1s,'r.','MarkerSize',10);
    hold on
    ylabel('Temperature (degC)')
    legend('Temperature 1','Location','NorthWest')
    subplot(2,1,2)
    plot(t_axis,h1s,'r-','LineWidth',2);
    hold on
    ylabel('Heater1 (0-5.5 V)')
    xlabel('Time (sec)')
    legend('Heater 1','Location','NorthWest')
    drawnow;
    pause(max(0,1-(toc-tdelay)));
end

h1(0);
h2(0);

disp('experiment complete')
fprintf('\n','\n');

%save data to disk
decision=input('Save data (y/n)?','s');
if decision=='y' || decision =='Y'
  savefile=input('filename:','s');    
  fileID=fopen(savefile,'w');
  results=[t_axis;t1s;h1s];
  fprintf(fileID,'%12s %12s %12s \n','time','t1s','h1s');
  fprintf(fileID,'%d %d %d \n',results);
  fclose(fileID);
end
