Square Wave FFT
clc; clear;
fs = 128; % sampling rate
N = 1024; % samples
fi = 5; % 5 Hz
t = 0 : 1/fs : 1; % time vector
x = square(2*pi*fi*t); % square wave
subplot(2,1,1);
plot(t,x); % plot square wave
ylim([-1,1.5]);
xlabel('time');
ylabel('amplitude');
title('square wave');
y = fft(x,N); % fft
Y = abs(y(1:N/2+1)); % make single-sided
f = fs/2*linspace(0,1,N/2+1); % freq vector
YdB = mag2db(Y); % in dB
YdB = YdB - max(YdB); % scale to 0dB
subplot(2,1,2);
plot(f,YdB); % plot FFT
xlabel('freq');
ylabel('magnitude');
title('FFT');
grid on;