% Calibrate NanoVNA
% Andrew Fletcher 2020

% Configuration Section  -------------------------------------------------

% the serial port that the nanoVNA is connected to
nanoVNAport = '/dev/tty.usbmodem4001';

% End  of Configuration
% Do not edit below here -------------------------------------------------

hCom = nanoOpen(nanoVNAport);

% prompt for sweep
sweepStart = input('Sweep start (MHz)? ');
command = sprintf('sweep start %d', sweepStart * 1000000);
nanoCommand(hCom, command);

sweepEnd = input('Sweep stop (MHz)? ');
command = sprintf('sweep stop %d', sweepEnd * 1000000);
nanoCommand(hCom, command);

% reset calibration
display('Calibrating...')
nanoCommand(hCom, 'cal reset');

% calibrate open
input('press RETURN when S11 is open');
nanoCommand(hCom, 'cal open');

% calibrate short
input('press RETURN when S11 is shorted');
nanoCommand(hCom, 'cal short');

% calibrate 50?
input('press RETURN when S11 has 50 ohm load');
nanoCommand(hCom, 'cal load');

continueAns = input('Calibrate S21 (Y/n)', 's');
if isempty(continueAns)
    continueAns = 'Y';
end
if strcmpi(continueAns, 'Y')
    % calibrate open
    input('press RETURN when S21 has 50 ohm load and S11 is open or has 50 ohm load');
    nanoCommand(hCom, 'cal isoln');

    % calibrate short
    input('press RETURN when S11 is connected to S21 with standard cable');
    nanoCommand(hCom, 'cal thru');
end

% save to memory
saveLocation = input('Save [0-4]? ');
command = sprintf('save %d', saveLocation);
nanoCommand(hCom, command);

% close port
nanoClose(hCom);