%Acquire two channels of data from a USB-1608G data acquisition system
%User provides the sampling rate, number of samples and input range
%This demo also exports the captured data to an Excel file 

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

%NOTE: REMEMBER TO CHANGE THE NAME OF THE EXCEL FILE AND THE FIGURE IMAGE
%OTHERWISE PREVIOUS DATA WILL BE OVERWRITTEN

%Based on PMD1208_sample by HJSIII
%Last edit JMC 11/14/2013
clear all
close all 
clc
%Set sampling rate (samples per second). 
%Maximum sampling rate for two channels = 125000 
samplingRate = 2000; 
numberOfSamples = 100; %Set number of samples to acquire
inputRange = [-10 10]; %Set input range in volts ([-1 1],[-2 2],[-5,5], or [-10 10])

% %Recommended 2nd Order settings 
% samplingRate = 10000; 
% numberOfSamples = 50000; %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 );
%The line below adds channels to sample. If you wanted to sample more than
%0 and 1, you would need to add the numbers to the vector [0,1]. The new
%data would show up as additional columns in the variable "data"
addchannel( ai, [0,1] ); 
set(ai, 'InputType', 'Differential');
set( ai, 'SampleRate', samplingRate )
set( ai, 'SamplesPerTrigger', numberOfSamples )
ai.Channel.InputRange = inputRange;
% activate USB-1608G
fprintf('Wait 2 seconds, then turn your circuit on.')
start( ai )
% sample data
[ data, time, abstime, events ] = getdata( ai );

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

% 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
plot(time,chan0,'b.');
title('Channel 0 data');%Add title
xlabel('Time (s)');%Add x label
ylabel('Voltage (V)');%Add y label

%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,'aliased signal.jpg');

%Find standard deviation
standardDeviation = std(chan0)

%Write to Excel file
%Check to see if file already exists
if(exist (strcat(excelFileName,'.xls')))
    delete(strcat(excelFileName,'.xls'))%Delete existing file
end
xlswrite(excelFileName,{'Time (s)','Channel 0 (V)','Channel 1 (V)'})%Write column names
%Write data starting below column names
xlswrite(excelFileName,[time,chan0,chan1],'Sheet1','A2')



