%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% PWM_Ex1.m - K. A. Connor - 29 Nov 15
% Description: Demo of PWM Signal Driving LED
% Usage: 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Circuit Connections:
% GND connected to 1k resistor
% 1+ connected to LED
% 1- connected to AGND
% W1 connected to LED
% LED connected in series to 1k resistor
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% move to command window
commandwindow;

% clean up
clear all;
close all;

% set up DAQ
s = daq.createSession('digilent');                % create DAQ session
ch_out = addAnalogOutputChannel(s,'AD1', 1, 'Voltage');       % add input voltage channel to measure voltage
ch_in = addAnalogInputChannel(s,'AD1', 1, 'Voltage');      % add output voltage channel to control LED brightness


% indicates the DAQ has been configured and the  process begun
fprintf('Process started...\n');                 % indicates that the process has started
% fprintf('Disconnect pin 1+ to terminate\n');        % instructs how to terminate process

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% begin process

%Set session and channel properties
% Set the generation rate (300kHz).
rate = 150e3;
s.Rate = rate;

% Define the output waveform
% Generate a 10 Hz sine-wave for 1 second.
f = 30;
duration = 1;
t = (1:(duration*rate))/rate;
output = 2 + 2*square(2*pi*f*t,25)';

% Generate / Acquire continuous data
% Generate queued data and acquire timestamped data in the foreground. 
% For any given session, generation and acquisition run at the same rate.
queueOutputData(s,output);
[data, timestamps, triggerTime] = s.startForeground;

% Display the results
plot(timestamps, data);grid;
xlabel('Time (seconds)'); ylabel('Voltage (Volts)');
title(['Clocked Data Triggered on: ' datestr(triggerTime)])

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% turn off LED
s.outputSingleScan(0);
