% Copyright (c) 2023 SpinCore Technologies, Inc.
% http://www.spincore.com
% 
% This software is provided 'as-is', without any express or implied warranty. 
% In no event will the authors be held liable for any damages arising from the 
% use of this software.
% 
% Permission is granted to anyone to use this software for any purpose, 
% including commercial applications, and to alter it and redistribute it
% freely, subject to the following restrictions:
% 
% 1. The origin of this software must not be misrepresented; you must not
% claim that you wrote the original software. If you use this software in a
% product, an acknowledgment in the product documentation would be appreciated
% but is not required.
% 2. Altered source versions must be plainly marked as such, and must not be
% misrepresented as being the original software.
% 3. This notice may not be removed or altered from any source distribution.
%

%
% \file pbesr_pro_example1.m adapted from pbesr_pro_example1.c
% \brief Example program for PulseBlasterESR-PRO boards
%  
% This demonstrates a simple pulse loop and also the short pulse feature.
%  
% All four BNC connectors are high for three clock periods (making use
% of the short-pulse feature), then low for the duration of instruction 1,
% or 20 ns. The BNC connectors are then held high for 40ns.  
% All four BNC connectors are then low for 40ns and the program repeats.
% 
% The largest value for the delay field of the pb_inst is 850ns.
% For longer delays, use the LONG_DELAY instruction.  The maximum value
% for the data field of the LONG_DELAY is 1048576.  Even longer delays can
% be achieved using the LONG_DELAY instruction inside of a loop.
% 
% \ingroup ESRPRO
%   
clc; clear;

global SPINAPI_DLL_NAME

SPINAPI_DLL_NAME = 'spinapi64';

addpath('../MATLAB_SpinAPI'); % MATLAB_SpinAPI Folder path address

SpinAPI_Drive = 'C:'; % Modify to the hard drive letter that contains SpinAPI

% Loads spinapi64 library and headers
% All files are located in SpinAPI folder
if ~libisloaded('spinapi64')  % Needs the MinGW-w64 add-on
    loadlibrary([SpinAPI_Drive,'\SpinCore\SpinAPI\lib\spinapi64.dll'], ...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\spinapi.h'], 'addheader',...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\pulseblaster.h'], 'addheader',...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\radioprocessor.h'], 'addheader',...
                 [SpinAPI_Drive,'\SpinCore\SpinAPI\include\dds.h']);
end

% Load constants to the workspace as variables
load('CONST.mat');

clock_freq = 500;

% Uncommenting the line below will generate a debug log in your current
% directory that can help debug any problems that you may be experiencing   
% pb_set_debug(1);

fprintf('Copyright (c) 2023 SpinCore Technologies, Inc.\n\n');

fprintf('Using SpinAPI library version %s \n', pb_get_version());


numBoards = detect_boards(); % If there is more than one board in the system, have the user specify.
if numBoards > 1             % Request the board number to use from the user
    select_boards(numBoards)
end

if pb_init() ~= 0
  error('Error initializing board: %s\n', pb_get_error());
end

% User input clock
clock_freq = input_clock();

fprintf('Clock frequency: %.2f MHz\n\n', clock_freq);
fprintf(['BNC outputs 1-3 will output a pulse with a period of 20ns, the ',...
	       'high time of which will be 3 clock cycles (%f ns).  They will ',...
		   'then be held high for 40ns and then low for 40ns and the program ',...
		   'will repeat. BNC output 0 will provide a signal to use for a ',...
		   'sampling trigger, with only one rising and falling edge per ',...
		   'period.\n\n'], 3000 / clock_freq);

% Tell driver what clock frequency the board uses
pb_core_clock(clock_freq);

% Prepare the board to receive pulse program instructions
pb_start_programming(PULSE_PROGRAM);

% Instruction 0 - Continue to instruction 1 in 20ns
% The lower 4 bits (all BNC connectors) will be driving high
% For PBESR-PRO boards, or-ing THREE_PERIOD with the flags
% causes a 3 period short pulse to be used. 
start = pb_inst_pbonly(bitor(hex2dec(THREE_PERIOD), hex2dec('F')), CONTINUE, 0, 20.0 * ns);

% Instruction 1 - Continue to instruction 2 in 40ns
% The BNC1-3 will be driving high the entire 40ns.
pb_inst_pbonly(bitor(hex2dec(ON), hex2dec('E')), CONTINUE, 0, 40.0 * ns);

% Instruction 2 - Branch to 'start' (Instruction 0) in 40ns
% Outputs are off
pb_inst_pbonly(0, BRANCH, start, 40.0 * ns);

pb_stop_programming();	% Finished sending instructions

pb_reset();
pb_start();			% Trigger the pulse program

% End communication with the PulseBlasterESR-PRO board. The pulse program
% will continue to run even after this is called.
pb_close();

fprintf('Press enter to continue...\n')
pause;

% Unload library and free memory
unloadlibrary('spinapi64');


function numBoards = detect_boards()
    numBoards = pb_count_boards();
    if numBoards < 1
        error(['No Boards were detected in your system. Verify that the board is', ...
            ' firmly secured in the PCI slot.']);
    end
end

function select_boards(numBoards)
    while true
        fprintf('Found %d boards in your system. ', numBoards);
        fprintf('Which board should be used? (0-%d): ', (numBoards-1));
        choice = input('');
        if choice < 0 || choice > numBoards-1
            fprintf('Invalid Board Number (%d).\n', choice);
        else 
            pb_select_board(choice);
            fprintf('Board %d selected.\n',choice);
            break
        end 
    end 
end 

function clock = input_clock()
    clock = input('\nPlease enter internal clock frequency (MHz): ');
end