clear;


instrreset;

%voltage meter
HP_DMM = gpib('ni',0,16);
fopen(HP_DMM);


K_DMM = gpib('ni',0,22);
K2_DMM = gpib('ni',0,21);
K_driver = gpib('ni',0,23);



fopen(K_driver);
%fopen(New_power);
fopen(K_DMM);
fopen(K2_DMM);

detectorvoltage= -5;
Ip = 0.000:.001:.1; %units of Amps

cmd1=sprintf('sour:volt:lev %1.2f',detectorvoltage);
fprintf(K_DMM,cmd1);fprintf(K2_DMM,cmd1);




temp_ind = 0;
go_flag = 1;
while go_flag==1
   temp_ind = temp_ind+1;
   temp(temp_ind) = input('Enter temperature:');
   
   %pause(10)
   for k = 1:length(Ip)
       cmd = sprintf('sour:curr:lev %1.3f',Ip(k))
       fprintf(K_driver,cmd);
       pause(0.2)
       fprintf(HP_DMM,'READ?')
       voltage(k,temp_ind) = str2num(fscanf(HP_DMM));
       
       %cmd = sprintf(':WAV:SOUR CHAN1;FORM ASCII;XINC?;XOR?;YOR?;YINC?;DATA?')
       %fprintf(HP_scope,cmd);
       % pause(1);
       % ss = fscanf(HP_scope);
       % xinc = str2num((ss(1:12)));
       % xor = str2num((ss(14:25)));
       % yor = str2num((ss(27:38)));
       % yinc = str2num((ss(40:51)));
       % data = str2num(ss(52:end));
       % volt = data*yinc+(yor-(16384*yinc));
       % figure(1)
       % plot(volt)       
       % voltage(k,temp_ind) = -mean(volt(170:240));
           
       fprintf(K_DMM,'READ?');
       %fprintf(New_power,'R_B?');
       pause(0.01);
       %power(k,temp_ind) = str2num(fscanf(New_power));
       response=[str2num(fscanf(K_DMM))];
       detectorcurrent(k,temp_ind) = -response(2);

       fprintf(K2_DMM,'READ?');
       %fprintf(New_power,'R_B?');
       pause(0.1);
       %power(k,temp_ind) = str2num(fscanf(New_power));
       response2=[str2num(fscanf(K2_DMM))];
       detector2current(k,temp_ind) = -response2(2);

       detectorsum(k,temp_ind) = detectorcurrent(k,temp_ind)+detector2current(k,temp_ind)
       
       figure(2)
       subplot(6,1,1); 
       plot(Ip(1:k),voltage(1:k,temp_ind)); title('I-V')
       subplot(6,1,2); plot(Ip(1:k),detectorcurrent(1:k,:),Ip(1:k),detectorcurrent(1:k,temp_ind),'-o'); title('I-I, left')
       subplot(6,1,3); plot(Ip(1:k),detector2current(1:k,:),Ip(1:k),detector2current(1:k,temp_ind),'-o'); title('I-I, right')
       subplot(6,1,4:6); plot(Ip(1:k),detectorsum(1:k,:),Ip(1:k),detectorsum(1:k,temp_ind),'-o'); title('I-I, both')
       
       
   end
   offvalue=0;
   fprintf(K_driver,'sour:curr:lev %1.2f',offvalue'); cmd1=sprintf('sour:volt:lev %1.2f',detectorvoltage);fprintf(K_DMM,cmd1);%fprintf(New_power,'AUTO_B 1');
   go_flag = input('Ready for another measurement? (1: Yes, 0: Stop)');
end

fclose(HP_DMM);
fclose(K_DMM);

fclose(K2_DMM);
%fclose(New_power);
fclose(K_driver);
%fclose(HP_scope);

save_str = input('Save file name:');
M=[I',voltage', detectorcurrent', detector2current',detectorsum'];

if ~isempty(save_str)
%     eval(['save ',save_str]);  
xlswrite(save_str, M);
end


 
