% FFT Example - for Engr325 Lab #4
% Revision 3.0 Curt Nelson  2/3/2020

% Creates functions of time and explores the fft implementation

clear all;

% Create time vector for x-axis
start_time = 0;
end_time = .01;		% 10 milli-seconds
delta_time = 1e-6;	% 10 micro-seconds
number_time_samples = (end_time - start_time)/delta_time;

% create time vector (in this case, 1000 data points)
time_vec = start_time:delta_time:end_time;

% The effective sampling rate is 1/delta_time or 100,000 samples/second
sampling_rate = 1/delta_time;

% Now create the time domain function with a frequency of 200Hz, resulting
% in a period of 1/frequency or 5 milli-seconds.
freq = 200;
period = 1/freq;
time_function = sin(2*pi*freq*time_vec);

% Since we are sampling from 0 to 10ms, we should see 2 cycles
plot(time_vec,time_function);		% Plot the function
title('Time Function with 1000 Data Points');
ylabel('volts');
xlabel('time - seconds');
grid on;

% Now do an FFT on this time domain function
% fft_results contains a complex number pair for each sample 
fft_results = fft(time_function);

% Create the x axis for frequencies
% Start at DC value (0 Hz)
dc_value = 0;

% We only need to plot the first half of the frequencies because the fft returns
% the same data folded over on itself at maxfreq/2
% Frequency spacing is the sampling rate / by the number of samples
freq_spacing =  sampling_rate/number_time_samples;

% Maximum frequency for the fft is (sampling rate/2) – delta_freq
freq_max = (sampling_rate/2) - freq_spacing;

% Now create the x-axis points
freq_plot_xaxis = dc_value:freq_spacing:freq_max;

% This results in (number of time samples/2) or 500 frequencies
number_freq_samples = number_time_samples/2;

% The magnitude of the fft must be computed from the fft_results
magnitude = abs(fft_results);

% Magnitude must be normalized by dividing by the number of frequency samples
nor_magnitude = magnitude/number_freq_samples;

% Plot the first 30 frequencies using red circles
plot(freq_plot_xaxis(1:30),nor_magnitude(1:30),'ro');
