%% Acquiring Data with MatLab using the National Instruments DAQ
%   Written by Justin Zepp, February 2010
%   Edited by John M. Cimbala

% This program records a signal from the National Instruments DAQ and saves
% the data so that they can be plotted and manipulated.

% Configure property values
% Set the sampling frequency in Hertz and the duration of the recording in seconds.

duration = 1;            % Duration in seconds (1 second is typical)
Fs = 500;                % Sampling rate in Hertz (500 Hertz is typical)

%%%%%%%%%%%%%%%% Do not change anything below this line %%%%%%%%%%%%%%%%%%%

% Label what device will be acquiring the data and save it as a variable
% Note: National Instruments DAQ is abbreviated as nidaq in MatLab and the
%       ID of the device installed is Dev1. Our lab uses a DAQPad 6015.
AI = analoginput('nidaq','Dev1');

% Add the channel in which your input BNC cable is connected to the device
% labeled above. 
chan = addchannel(AI,0);

% Define the sampling rate and number of samples 
% [Note that here, "sample" means a data point, not a set of data points]
set(AI,'SampleRate',Fs)
set(AI,'SamplesPerTrigger',duration*Fs)
set(AI,'TriggerType','Manual')
blocksize = get(AI,'SamplesPerTrigger');

% Acquire data
start(AI)
trigger(AI)
wait(AI,duration + 1)
    %The wait function pauses MATLAB until either the acquisition completes
    %or the time-out elapses (whichever comes first). If the time-out 
    %elapses, an error occurs. Adding 1 second to the duration allows some 
    %margin for the time-out.
[data,time] = getdata(AI);

% Clean up
stop(AI);
delete(AI);

% Compute FFT 
% [f,mag] = daqdocfft(data,Fs,blocksize);
xfft = abs(fft(data,blocksize))*2/blocksize;
mag = (xfft);
mag = mag(1:floor(blocksize/2));
mag(1)=mag(1)/2;
f = (0:length(mag)-1)*Fs/blocksize;

% Plot Results
subplot(2,1,1)
plot(time,data)
zoom on
title('Time Trace');
xlabel('Time (s)');
ylabel('Voltage (volt)');
% NOTE: To change the axes limits, add this line: axis([xmin, xmax, ymin, ymax])
%       where you specify the values of xmin, xmax, ymin, and ymax.

subplot(2,1,2)
plot(f,mag)
grid on 
ylabel('Amplitude (volt)')
xlabel('Frequency (Hz)')
title('Frequency Spectrum')


