NI myDAQ Matlab

Here I provide some example code that demonstrates how to use the NI myDAC with Matlab. This example assumes that you have installed NI ELVISmx 14.0 which contains the myDAQ drivers and that you have the Matlab Data Acquisition Toolbox.

This example implements a simple vector network analyser that outputs a swept sinusoidal signal   as the input to the DUT and measures both the input signal and the output signal from the DUT. It then measures the frequency dependent gain and phase of the DUT.


% Example code to output and capture analogue waveforms
% Note the myDAQ has a maximum sample rate of 200kHz

% Author: Benn Thomsen September 2014

Fs = 200e3; % Sample rate (Hz)
N = 100000; % Number of samples

time = (0:N-1)'./Fs;
freq = (-N/2:N/2-1)'*(Fs/N);
Amplitude = 2; % Amplitude
Fstart = 10; % Start Frequency (Hz)
Fstop = 100e3; % End frequency (Hz) Fmax = 100kHz.
Fpoints = 10; % Points per decade
start = log10(Fstart);
stop =log10(Fstop);
f = logspace(start,stop,Fpoints*(stop-start));

s = daq.createSession('ni');
s.Rate = Fs;
s.addAnalogInputChannel('myDAQ1',0:1, 'Voltage'); % Add Input Channels
s.Channels(1).Range = [-2 2]
s.Channels(2).Range = [-2 2]
s.addAnalogOutputChannel('myDAQ1',0,'Voltage'); % Add Output Channel

Nf = length(f);
Gain = zeros(Nf,1);
Phase = zeros(Nf,1);

for n=1:Nf,
TestSig = Amplitude*exp(1j*2*pi*f(n)*time); % Create complex sinusoidal signal

s.queueOutputData(real(TestSig)); % Send real part to myDAQ
signal = s.startForeground(); % Start data playback and capture
SigDownConInput = signal(:,1).*TestSig; % Down convert sinusoidal input signal
SigDownConOutput = signal(:,2).*TestSig; % Down convert sinusoidal output signal
InputPower = sum(abs(SigDownConInput).^2)./N; % Measure average power of input signal
OutputPower = sum(abs(SigDownConOutput).^2)./N % Measure average power of output signal
Gain(n)=10*log10(OutputPower./InputPower); % Calculate gain
Phase(n) = angle(sum(SigDownConInput).*conj(sum(SigDownConOutput))); % Measure phase difference

figure(2), subplot(211),semilogx(f(1:n),Gain(1:n),'-o')
xlim([Fstart,Fstop])
ylim([-15 0])
ylabel('Gain (dB)')
subplot(212),semilogx(f(1:n),unwrap(Phase(1:n)),'-o')
xlim([Fstart,Fstop])
ylabel('Phase (rad)')
xlabel('Frequency (Hz)')
end

s.release()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s