% Tune Loop with NanoVNA
% Andrew Fletcher August 2020

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

% the serial port that the nanoVNA is connected to
nanoVNAport = '/dev/tty.usbmodem4001';
tuneSpan = 0.2; % sweep span in MHz

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

hCom = nanoOpen(nanoVNAport);

% ask for loop to be connected
input('press RETURN when loop is connected to ch0');

% set traces
% note: these commands are not specified in the nanoVNA console commands
% but seem to work as expected
nanoCommand(hCom, 'trace 0 on');
nanoCommand(hCom, 'trace 1 off');
nanoCommand(hCom, 'trace 2 off');
nanoCommand(hCom, 'trace 3 off');

% set sweep
tuneFreq = input('Frequency to tune to (MHz) ? ');

sweepStart = tuneFreq - (tuneSpan / 2);
command = sprintf('sweep start %.0f', sweepStart * 1000000);
nanoCommand(hCom, command);

sweepEnd = tuneFreq + (tuneSpan /2);
command = sprintf('sweep stop %.0f', sweepEnd * 1000000);
nanoCommand(hCom, command);

% set markers
marker = 1;
index = 50; % half way through span
command = sprintf("marker %d %d", marker, index);
nanoCommand(hCom, command);

marker = 2;
command = sprintf("marker %d off", marker);
nanoCommand(hCom, command);

marker = 3;
command = sprintf("marker %d off", marker);
nanoCommand(hCom, command);

marker = 3;
command = sprintf("marker %d off", marker);
nanoCommand(hCom, command);

nanoCommand(hCom, 'resume'); % start sweeping

input('tune loop for dip at the marker, press RETURN when tuned ok');

nanoCommand(hCom, 'pause'); % stop sweeping

% close port
nanoClose(hCom);