clear all; close all; clc
Fs = 68e3;                    % Sampling frequency
T = 1/Fs;                     % Sample time
L = 1e3;                      % Length of signal
t = 0:T:L*T-T;                % Time vector
y = ( (2^11-10)/2*sin(2*pi*5000*t));     % Sinusoidal waveform
figure(1)
hold on
plot(1000*t,y)
title('Sinusoidal waveform 5kHz')
xlabel('t [ms]')

NFFT = 2^nextpow2(L);
Y1 = fft(y,NFFT)/L;
Y1_n = 20*log10(2*abs(Y1(1:NFFT/2+1)));
Y1_n = Y1_n - max(Y1_n);
f = Fs/2*linspace(0,1,NFFT/2+1);

% Plot single-sided amplitude spectrum.
figure(2)
plot(f,Y1_n,'LineWidth',2) 
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')
grid on


Fs2=Fs*2^11;
LPWM=L*2^11;
outPWM = zeros(1,LPWM);

for i=1:L*2^11
    if ((2^11-10)/2*sin(2*pi*5000*i*(1/Fs2))) > (2^11)/2*sawtooth(2*pi*68e3*i*(1/Fs2))
        outPWM(i) = 1;
    else
        outPWM(i) = -1;
    end 
end
figure(3)
tpwm=0:(1/Fs2):i*(1/Fs2)-1/Fs2;
plot(tpwm,outPWM)

NFFT = 2^nextpow2( LPWM );
Y2 = fft(outPWM,NFFT)/L;
Y2_n = 20*log10(2*abs(Y2(1:NFFT/2+1)));
Y2_n = Y2_n - max(Y2_n);
f = Fs2/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
figure(4)
plot(f*1e-3,Y2_n,'LineWidth',2) 
title('Jednostranné amplitudové spektrum PWM signálu, Fs = 140MHz')
xlabel('Frekvence (kHz)')
ylabel('20log|Y(f)| - 20log|Y_m_a_x(f)| [dB]')
grid on
axis([0 204 -80 2])