
% 1) Establish connection to laser
o = serialport("COM9",9600); %per USB angeschlossen
configureTerminator(o,"CR")
writeline(o,"*IDN?");
wait(1)
if o.NumBytesAvailable ~= 0
    disp(['Laser Mainframe: ',readline(o)]);
else
    error('Keine Verbindung zum Mainframe mglich?')
    clear o

end

% 2) connect to device
v = visa('keysight', 'TCPIP0::134.245.243.248::inst0::INSTR');
fopen(v);
fprintf(v, '*IDN?;');
disp(['Powermeter: ' fscanf(v)]);

% Define channels
laser_channel = 7;
powermeter_slot = 1;
l = 1300:0.1:1320;

% turn on the laser
writeline(o,['CH',num2str(laser_channel),':ENABLE']);
wait(0.2)
current_wavelen = readline(o);

clear power
clear lambda

for n = 1:length(l)

    % 2 change wavelength in laser slot
    command = string(['CH',num2str(laser_channel),':L=',num2str(l(n))]);
    writeline(o,command);
    wait(0.5);
    readline(o);

    % query and check wavelength
    writeline(o,['CH',num2str(laser_channel),':L?']);
    wait(0.2)
    current_wavelen = readline(o);
    current_wavelen = str2double(strrep(regexp(current_wavelen,'([CH7:L=])+([\d]*)+([.])+([\d]*)','match'),'CH7:L=',''));

    if l(n) ~= current_wavelen
        clear o
        fclose(v);
        delete(v);
        clear v
        error('Wellenlnge wurde nicht bernommen');
    end

    wait(0.75);

    % get current power in slot
    slot = 1;
    fprintf(v, [':READ' num2str(slot) ':POW?']);
    power(n) = sscanf(fscanf(v),'%f');
    lambda(n) = current_wavelen;

    if mod(n,10)==1
        disp(['Measured ',num2str(power(n)),' dBm at ',num2str(lambda(n)),' nm'])
    end
end

figure(2)
hold on
plot(lambda,power,'Marker','*');
xlabel('Wavelngth in nm')
ylabel('Power in dBm')
grid minor

figure(211)
hold on
plot(lambda,10.^(power/10),'Marker','*');
xlabel('Wavelngth in nm')
ylabel('Power in mW')
grid minor

%close the serial connection

clear o
fclose(v);
delete(v);
clear v
