%{
AsciiArb is a sample program that demonstrates how to download an arbitrary waveform
	into instrument volatile memory and play back the same with the configuration below:
	This arb generates a 8192 point pulse waveform, of which the first 400 points define a
	positive pulse from 0 volts to the maximum defined voltage amplitude.

Wave Shape: Arb
Amplitude:	2 Volt Peak to Peak
Offset:		0 Volt
Output Impedance:	50 Ohm
Output: Enabled

This example will work with the Agilent 33210A, 33220A, and 33250A
%}


% clears all variables, closes all open files

clear all; close all; clc;

%opens and creates a visa session for communication with function generator

fgen = visa('AGILENT','GPIB0::10::INSTR');
set (fgen,'OutputBufferSize',1000000);
set (fgen,'timeout', 100);
fopen(fgen);

%Query Idendity string and report
fprintf (fgen, '*IDN?');
idn = fscanf (fgen);
fprintf (idn)
fprintf ('\n\n')

%Clear and reset instrument
fprintf (fgen, '*RST');
fprintf (fgen, '*CLS');


	% Create arb waveform with 8192 points of 0-1 data
	fprintf('Generating Waveform...\n\n')
	

i=1;
b=3e6; % Chirp rate 4 MHz/ 1ms
f_0=2e6; % starting f=1 MHz
B=0;
Arb_FDPA=[];   
for t=0:1/65536/1:1-1/65536/1; %1 ms duration
    f=(f_0+b*t)/1e6; % frequency in MHz
    HiLevel=(0.6061*f.^4+1.414*f.^3-46.21*f.^2+192.7*f+1180);
    LoLevel=-2.028*f.^4+25.92*f.^3-118.1*f.^2+126.2*f+513.6;
    B=(HiLevel-LoLevel).*(1+sin(2*pi*f*1e6.*t*1e-3))/2+LoLevel;
    y = num2str(B);
    s1 = sprintf(', %s', y);
    Arb_FDPA = [Arb_FDPA s1];
end
%     
    
   
    % combine string of data with scpi command
	arbstring =sprintf('DATA VOLATILE %s', Arb_FDPA);

    
	%Send Command to set the desired configuration
	fprintf('Downloading Waveform...\n\n')
	fprintf(fgen, arbstring);
    %make instrument wait for data to download before moving on to next
    %command set
	fprintf(fgen, '*WAI');
	fprintf('Download Complete\n\n')

	%Set desired configuration.
%     fprintf(fgen,'VOLT 2'); % set max waveform amplitude to 2 Vpp
%     fprintf(fgen,'VOLT:OFFSET 0'); % set offset to 0 V
     fprintf(fgen,'OUTPUT:LOAD 50'); % set output load to 50 ohms
     fprintf(fgen,'FREQ 100'); %set frequency to 1KHz
     fprintf(fgen,'FUNC:USER VOLATILE');
     fprintf(fgen,'FUNC:SHAP USER');
 

    %Enable Output
    fprintf(fgen,'OUTPUT ON'); % turn on channel 1 output


% Read Error
fprintf(fgen, 'SYST:ERR?');
errorstr = fscanf (fgen);

% error checking
if strncmp (errorstr, '+0,"No error"',13)
   errorcheck = 'Arbitrary waveform generated without any error \n';
   fprintf (errorcheck)
else
   errorcheck = ['Error reported: ', errorstr];
   fprintf (errorcheck)
end

%closes the visa session with the function generator
fclose(fgen);