Fs = 100e3;
f0 = 10e3;
duration = 1;
samples = Fs*duration;
t = (0:samples-1)*1/Fs;
signal = 0.5*(square(2*pi*f0*t)+1);
NFFT = 10000;
Overlap = 0.75;
w = hanning(NFFT);
[freq,fft_spectrum] = myfft_peak(signal, Fs, NFFT, Overlap);
sensor_spectrum_dB = 20*log10(fft_spectrum);
figure(1),plot(freq,sensor_spectrum_dB,'b');grid
title(['Averaged FFT Spectrum / Fs = ' num2str(Fs) ' Hz / Delta f = ' num2str(freq(2)-freq(1)) ' Hz ']);
xlabel('Frequency (Hz)');ylabel(' dB')
text(locs+.02,pks,num2str(freq(locs)))
function [freq_vector,fft_spectrum] = myfft_peak(signal, Fs, nfft, Overlap)
signal = signal(:);
samples = length(signal);
if samples<nfft
s_tmp = zeros(nfft,1);
s_tmp((1:samples)) = signal;
signal = s_tmp;
samples = nfft;
end
window = hanning(nfft);
window = window(:);
offset = fix((1-Overlap)*nfft);
spectnum = 1+ fix((samples-nfft)/offset);
fft_spectrum = 0;
for i=1:spectnum
start = (i-1)*offset;
sw = signal((1+start):(start+nfft)).*window;
fft_spectrum = fft_spectrum + (abs(fft(sw))*4/nfft);
end
fft_spectrum = fft_spectrum/spectnum;
if rem(nfft,2)
select = (1:(nfft+1)/2)';
else
select = (1:nfft/2+1)';
end
fft_spectrum = fft_spectrum(select);
freq_vector = (select - 1)*Fs/nfft;
end
Best Answer