I am trying to write a basic program that samples a 4 kHz sinewave at a sampling rate of 8 kHz and takes the FFT of the signal and plots it.
From everything I have read, as long as the signal you are sampling has frequency content that is less than or equal to Fs/2 no aliasing will occur and the results will be accurate. However writing a simple example seems to be more complicated than I thought.
Using Python I wrote up a basic example:
import matplotlib.pyplot as plt import numpy as np Fs = 8000.0 Ts = 1/Fs N = 8 t = np.arange(0, N*Ts, Ts) # 4 kHz sinewave y = np.sin(2*np.pi*4000*t) # Bandwidth of the signal (Hz) BW = Fs/2 # Spectral Lines (number of frequency samples) SL = round(N/2 + 1) # Frequency scale f = np.linspace(0, BW, SL) Y = np.fft.fft(y)*2/N Y = Y[:SL] fig, ax = plt.subplots(2, 1) ax.stem(t, y, use_line_collection=True) ax.set_xlabel('Time') ax.set_ylabel('Amplitude') ax.stem(f, abs(Y), use_line_collection=True) ax.set_xlabel('Freq (Hz)') ax.set_ylabel('|Y(freq)|') plt.show()
Looking at the output you can see that this does not properly capture the frequency content at 4 kHz in the FFT plot.
But if I simply add a phase shift to the signal by changing this line
y = np.sin(2*np.pi*4000*t)
y = np.sin(2*np.pi*4000*t + np.pi/2)
I end up with much better results...
My question is, how come this doesn't work without a phase shift? It makes me wonder how anyone can be confident in the result of an FFT when the signal being sampled has some frequency content that is at the frequency Fs/2. How do you ensure that the signal you are analyzing is at a phase alignment that will not cause issues?