%This example shows how to load a signal from matlab workspace into the AFG
%memory. The signal is sent via Binary Block and saved in the ARBB buffer
%of the AFG, then you can select ARBB as carrier or as modulating law
%
%On the channel 1 there is the function from Matlab, on the channel 2 a
%predefined function (Sinc).
%You can change amplitude, offset and frequency of both channels.
%For the channel 1 you can redefine the function and change the number of
%points up to 16384.

%%

%Instrument address
Instrument_Addr = 'TCPIP0::192.168.0.21::inst0::INSTR';

%Waveform Parameters
CH1_Amplitude = 2.5;
CH1_Offset = 0;
CH1_Frequency = 5e6;

CH2_Amplitude = 1.5;
CH2_Offset = 1;
CH2_Frequency = 10e6;

%CH1 Function (create the vector of samples for the channel 1)
NPoints = 16384;

%Define a time vector of NPoints step
t = (-NPoints / 2):1:(NPoints / 2 - 1);

%Define a parabolic function (as example)
%"Waveform" is sent to instrument
Waveform = t.^2;

%%

% Find a VISA-TCPIP object.
obj = instrfind('Type', 'visa-tcpip', 'RsrcName', Instrument_Addr);

% Create the VISA-TCPIP object if it does not exist
% otherwise use the object that was found.
if isempty(obj)
    obj = visa('NI', Instrument_Addr);
else
    fclose(obj);
    obj = obj(1);
end

%Set the buffers size at 40 kbytes (before open)
obj.OutputBufferSize=40e3;

%Set the timeout at 10 s (before open)
obj.Timeout=10;

%Connect to instrument object, obj1.
fopen(obj);

%Reset the instrument
fprintf(obj, '*RST');

%Send the signal
Send_Wfm_Binary_Block(obj,1,Waveform);

%Select the waveforms
fprintf(obj, 'SOURCE1:FUNC:SHAPE ARBB');
fprintf(obj, 'SOURCE2:FUNC:SHAPE SINC');

%Set the frequencies
fprintf(obj, 'SOURCE1:FREQ %f',CH1_Frequency);
fprintf(obj, 'SOURCE2:FREQ %f',CH2_Frequency);

%Set the amplitudes
fprintf(obj, 'SOURCE1:VOLT:AMPL %f',CH1_Amplitude);
fprintf(obj, 'SOURCE2:VOLT:AMPL %f',CH2_Amplitude);

%Set the offsets
fprintf(obj, 'SOURCE1:VOLT:OFFSet %f',CH1_Offset);
fprintf(obj, 'SOURCE2:VOLT:OFFSet %f',CH2_Offset);

%Enable the outputs
fprintf(obj, 'OUTPUT1:STATE 1');
fprintf(obj, 'OUTPUT2:STATE 1');

%Start the generation
fprintf(obj, 'AFGC:START');

err_no = 1;
i=1;
%Loop until it receive error number = 0
while err_no~=0
    
    %send the query
    fprintf(obj, 'SYST:ERR?');
    
    %read the response
    Response=fscanf(obj);
    
    %save error number and message     
    [err_no,~,~,next_index]=sscanf(Response,'%d,');
    fprintf('%s\n',Response);
end
