close all; clear global; clc

%initialization
tclabFall2018;

disp('This experiment turns on Heater 1, and reports temperature 1 and 2')
disp('LED brightness indicates temperature 1')

figure(1)
t1s = [];
t2s = [];
h1s = [];
h2s = [];
% initial heater values
ht1 = 0;
ht2 = 0;
h1(ht1);
h2(ht2);

for i = 1:800
    tic;
    if i==2
        disp('Turn on heater 1')
        ht1 = 75;
        h1(ht1);
    end
    if i==600
        disp('Turn off heater 1')
        ht1 = 0;
        h1(ht1);
    end
    % read temperatures
    t1 = T1C();
    t2 = T2C();

    % LED brightness
    brightness1 = (t1 - 30)/50.0;  % <30degC off, >80degC full brightness
    brightness = max(0,min(1,brightness1)); % limit 0-1
    led(brightness);
    
    % plot heater and temperature data
    h1s = [h1s,ht1];
    h2s = [h2s,ht2];
    t1s = [t1s,t1];
    t2s = [t2s,t2];
    n = length(t1s);
    time = linspace(0,n+1,n);
    clf
    subplot(2,1,1)
    plot(time,t1s,'r.','MarkerSize',10);
    hold on
    plot(time,t2s,'b.','MarkerSize',10);
    ylabel('Temperature (degC)')
    legend('Temperature 1','Temperature 2','Location','NorthWest')
    subplot(2,1,2)
    plot(time,h1s,'r-','LineWidth',2);
    hold on
    ylabel('Heater (0-5.5 V)')
    xlabel('Time (sec)')
    legend('Heater 1','Location','NorthWest')
    drawnow;
    t = toc;
    pause(max(0.01,1.0-t));
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=[time;t1s;t2s;h1s;h2s];
  fprintf(fileID,'%12s %12s %12s %12s %12s\n','time','t1s','t2s','h1s','h2s');
  fprintf(fileID,'%d %d %d %d %d\n',results);
  fclose(fileID);
end
