%get and plot IV curve;
%Last step sets voltage to 0.
clear all
compliance = 10e-3; %A
Vstart = 0;         %V
Vstop = -7;        %V
Vstep = -0.01;       %V
pse = 0.01;         %How long to pause in between points (sec)
Vvec_up = Vstart:Vstep:Vstop;
Vvec_down = Vstop:-Vstep:Vstart;
meterGPIB = 10;

%initialize source meter
address = strcat('GPIB0::', num2str(meterGPIB), '::INSTR');
%source = visa('ni', address);
source=gpib('ni', 0, meterGPIB);
fopen(source)
voltage = Vvec_up(1);
fprintf(source, ':SENS:CURR:PROT %e', compliance);
fprintf(source, ':SOUR:VOLT:LEV %e', voltage);
fprintf(source, ':OUTP ON');
fprintf(source, ':READ?')
current_holder = str2num(fscanf(source));
current = current_holder(2);

%step through voltages: go up:
for i = 1:length(Vvec_up)
    voltage = Vvec_up(i);
    fprintf(source, ':SOUR:VOLT:LEV %e; *WAI', voltage);
    pause(pse);
    fprintf(source, ':READ?; *WAI')
    current_holder = str2num(fscanf(source));
    current_up(i) = current_holder(2);
end

plot(Vvec_up, current_up)

%step through voltages: go down:
for i = 1:length(Vvec_down)
    voltage = Vvec_down(i);
    fprintf(source, ':SOUR:VOLT:LEV %e; *WAI', voltage);
    fprintf(source, ':READ?; *WAI')
    current_holder = str2num(fscanf(source));
    current_down(i) = current_holder(2);
    pause(pse);
end

fprintf(source, ':SOUR:VOLT:LEV 0');
fclose(source)
clear source

plot(Vvec_up, current_up*1e3, Vvec_down, current_down*1e3)
ylabel('Current (mA)')
xlabel('Voltage (V)')

figure(1)
uisave()


