Tuesday, January 31, 2012

Matlab Function for Creating Arbitrary Waveform Files

This post features a Matlab function called convertToArb( ) that converts a vector / array of data into a waveform format that can be loaded onto Agilent's 3352xA function / arbitrary waveform generators (33521A one channel and 33522A two channel). This function converts a row or column vector into a 3352xA format .arb file (a waveform file that can be loaded onto the 33522A or 33521A). The vector data should contain voltage values ranging from 10 V to - 10 V. The convertToArb( ) function will generate a .arb file in the current Matlab open directory. The file can then be imported to the 33521A or 33522A via a USB memory stick. You can copy the code for the function below or you can download the function from Matlab Central (link at the end).

function convertToArb(data,samplerate,fName)

%check if data is row vector, if so convert to column
if isrow(data)
    data = data';
numberofpoints = length(data);

%Get max and min values from waveform data

%range has to be the maximum absolute value between data_min and data_max
%Data Conversion from V to DAC levels

fName = [fName '.arb']; %add file extension to file name

%File creation and formatting
fid = fopen(fName, 'w');
fprintf(fid,'%s\r\n','File Format:1.10');
fprintf(fid,'%s\r\n','Channel Count:1');
fprintf(fid,'%s\r\n','Column Char:TAB');
fprintf(fid,'%s%d\r\n','Sample Rate:',samplerate);
fprintf(fid,'%s%6.4f\r\n','High Level:',data_max(1));
fprintf(fid,'%s%6.4f\r\n','Low Level:',data_min(1));
fprintf(fid,'%s\r\n','Data Type:"Short"');
fprintf(fid,'%s%d\r\n','Data Points:',numberofpoints);
%Write data to file and close it

The input arguments for the convertToArb( ) function are as follows:
  • 'data' is the vector containing the waveform points that you want to convert to a .arb file
  • 'samplerate' is the sample rate setting for the 33521A or 33522A. The total time of your waveform is equal to: samplerate * number of points in the file.
  • 'fName' is the name you want to assign to the .arb file that is created, for instance "myArb" will create a "myArb.arb" file.
The following example Matlab script uses the convertToArb( ) function to create a waveform that consists of three different sine waves summed together.

%example script to demonstrate function convertToArb(data,samplerate,fName) 
xAxis = 0:.001:1; %create x axis for plot
count = length(xAxis); %get size of waveform
yAxis = zeros(1,count); %allocate array

for i = 1:count
    %build waveform that consists of three sinewaves summed together
   yAxis(i) = sin((2*pi)*xAxis(i)) + (.5*sin((2*pi)*xAxis(i)*3)) + (.3*sin(pi*xAxis(i)));

%call function to convert it to .arb file named myArb.arb

Below is the resulting waveform generated with the example script captured on a scope.