%main program to communicate with the Newport power meter



clear all;
close all;

filename=input('Input filename for the data (with single quotes around it and .xls extension)')
% filename='FP8pads_s2_n3_25C.xls';

instrreset;

%enter number for device ID
deviceid = 'Me';
% all files for the device start with this number, and the type of
% measurement is in the remainder of the file.

%GPIB addresses
gpib_newport = 5;
gpib_keithley_1 = 24;

nwpt = gpib('ni',0,gpib_newport);
keithley_1 = gpib('ni',0,gpib_keithley_1);

%setup scan Keithley1 - Gain section
I_start = 1;
I_stop = 200;
I_step = 2;
I = I_start:I_step:I_stop;

%config keithley 1
fopen(keithley_1);
fprintf(keithley_1,':*RST');
fprintf(keithley_1,':SOUR:FUNC:MODE CURR');
fprintf(keithley_1,':SOUR:CURR 0');
fprintf(keithley_1,':SENS:VOLT:RANGE 3');
fprintf(keithley_1,':SENS:VOLT:PROT:LEV 5');%

%config Newport
fopen(nwpt);
fprintf(nwpt,'*RST');
fprintf(nwpt,'*CLS');
fprintf(nwpt,'DSCLR');
fprintf(nwpt,'DSE 0');
fprintf(nwpt,'LAMBDA 1550');
fprintf(nwpt,'DSCLR');
fprintf(nwpt,'SPREC 4096');
fprintf(nwpt,'UNITS W');
fprintf(nwpt,'MODE DCCONT');
fclose(nwpt);

voltage = zeros(size(I));
data = zeros(size(I),3);
v_temp = 0;

figure(1)
hold on;
for k = 1:size(I,2);
    v_1 = func_keithley_set_current(keithley_1,I(k));
    power(k) = Newport(nwpt);
    voltage_1(k) = v_1;
    Rs(k) = (v_1-v_temp)/I_step*1000;
    if Rs >= 50;
        Rs(k) = 50;
    else
    end
    subplot(3,1,1)
    plot(I(1:k),power*1000,'b-');
    title('Current-Power');
    subplot(3,1,2)
    plot(voltage_1,I(1:k),'r-');
    title('Current-Voltage');
    subplot(3,1,3)
    plot(I(1:k),Rs(1:k),'g-');
    title('Current-Resistance');
    data(k,1) = I(k);
    data(k,2) = power(k)*1000;
    data(k,3) = voltage_1(k);
    v_temp = v_1;
end

hold off;

delete(nwpt);
clear nwpt;

fprintf(keithley_1,'*RST');
fprintf(keithley_1,':*CLS ');
fclose(keithley_1);
delete(keithley_1);
clear keithley_1;

Rs = diff(voltage_1)./I_step.*1000;
Rs_ave = mean(Rs(length(Rs)-10:length(Rs)))

figure(2)
plot(I(1:k),power*1000,'b-');
title('Current-Power');

figure(3)
plot(I(1:size(I,2)-1),Rs);
axis([0 max(I) 0 50]);

M=[I', power', voltage_1'];
xlswrite(filename, M);