%Acquire one channel of data from a USB-1608G data acquisition system
%User provides the sampling rate, number of samples and input range
%This code also creates an amplitude spectrum for the data collected from
%channel 0

%Voltages from channel 0 are stored in the variable "chan0"
%The time of each sample is stored in the variable "time"

%Based on PMD1208_sample by HJSIII
%Last edit MDR 08/15/13
clear all
close all 
clc

%Set sampling rate (samples per second). 
%Maximum sampling rate for two channels = 125000 
samplingRate = 2000; 
numberOfSamples = 800; %Set number of samples to acquire
inputRange = [-10 10]; %Set input range in volts ([-1 1],[-2 2],[-5,5], or [-10 10])
excelFileName = 'sampleData';%Name of excel file in which to save data

%% The code below samples data and takes care of the details of data 
%acquisition 
ai = analoginput( 'mcc', 0 );
addchannel( ai, 0 );
set(ai, 'InputType', 'Differential');
set( ai, 'SampleRate', samplingRate )
set( ai, 'SamplesPerTrigger', numberOfSamples )
ai.Channel.InputRange = inputRange;
% activate USB-1608G
start( ai )

% sample data
[ data, time, abstime, events ] = getdata( ai );

% break data into channels 0 and 1
chan0 = data(:,1);

% Deactivate data acquisition board
stop(ai); 
delete(ai)
clear ai

%% Place your code below. The variable chan0 contains the data for channel 0,
%chan1 contains the data for channel 1 and time contains the time for both
%channels

%Example: plot channel 0, save the plot as an image, print the standard deviation of 
%channel 0 to the MATLAB command window, and save the time, channel 0 data and
%channel 1 data to an Excel file.

%Plot data
Fs=samplingRate;
L=numberOfSamples;
y = chan0;
t = time;

NFFT = 2^nextpow2(L); % Next power of 2 from length of y
Y = fft(y,NFFT)/L;
Y(1)=Y(1)/2;
f = Fs/2*linspace(0,1,NFFT/2+1);

subplot(2,1,1);
% Plot voltage signal
plot(time,chan0,'b.');
title('Channel 0 data');%Add title
xlabel('Time (s)');%Add x label
ylabel('Voltage (V)');%Add y label
subplot(2,1,2);
% Plot single-sided amplitude spectrum.
plot(f,2*abs(Y(1:NFFT/2+1))) 
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')

%Save figure as a .jpg image. You can change 'figureName.jpg' to another
%name, but you need to include .jpg at the end
saveas(gcf,'figureName.jpg');



