Pulse Width Modulation (PWM)
MATLAB Script
clc;
clear all;
close all;
fs=5; %frequency of the sawtooth signal
fm=5; %frequency of the message signal
sampling_frequency = 10e3;
a=0.5; % amplitide
t=0:(1/sampling_frequency):1; %sampling rate of 10kHz
sawtooth=1.01*a.*sawtooth(2*pi*fs*t); %generating a sawtooth wave
subplot(4,1,1);
plot(t,sawtooth); % plotting the sawtooth wave
title('Comparator Wave');
msg=a.*sin(2*pi*fm*t); %generating message wave
subplot(4,1,2);
plot(t,msg); %plotting the sine message wave
title('Message Signal');
for i=1:length(sawtooth)
if (msg(i)>=sawtooth(i))
pwm(i)=1; %is message signal amplitude at i th sample is greater than
%sawtooth wave amplitude at i th sample
else
pwm(i)=0;
end
end
subplot(4,1,3);
plot(t,pwm,'r');
title('PWM');
axis([0 1 0 1.1]); %to keep the pwm visible during plotting.
%% Demodulation
% Demodulation: Measure the pulse width to reconstruct the signal
demodulated_signal = zeros(size(msg));
for i = 1:length(pwm)-1
if pwm(i) == 1
% Measure the time until the next falling edge
j = i + 1;
while pwm(j) == 1 && j < length(pwm)
j = j + 1;
end
% Reconstruct the analog value based on pulse width
demodulated_signal(i) = mean(msg(i:j-1));
end
end
% Plot the demodulated signal for comparison
subplot(4,1,4);
plot(t, demodulated_signal);
title('Demodulated Signal');
xlabel('Time');
ylabel('Amplitude');
grid on;
clear all;
close all;
fs=5; %frequency of the sawtooth signal
fm=5; %frequency of the message signal
sampling_frequency = 10e3;
a=0.5; % amplitide
t=0:(1/sampling_frequency):1; %sampling rate of 10kHz
sawtooth=1.01*a.*sawtooth(2*pi*fs*t); %generating a sawtooth wave
subplot(4,1,1);
plot(t,sawtooth); % plotting the sawtooth wave
title('Comparator Wave');
msg=a.*sin(2*pi*fm*t); %generating message wave
subplot(4,1,2);
plot(t,msg); %plotting the sine message wave
title('Message Signal');
for i=1:length(sawtooth)
if (msg(i)>=sawtooth(i))
pwm(i)=1; %is message signal amplitude at i th sample is greater than
%sawtooth wave amplitude at i th sample
else
pwm(i)=0;
end
end
subplot(4,1,3);
plot(t,pwm,'r');
title('PWM');
axis([0 1 0 1.1]); %to keep the pwm visible during plotting.
%% Demodulation
% Demodulation: Measure the pulse width to reconstruct the signal
demodulated_signal = zeros(size(msg));
for i = 1:length(pwm)-1
if pwm(i) == 1
% Measure the time until the next falling edge
j = i + 1;
while pwm(j) == 1 && j < length(pwm)
j = j + 1;
end
% Reconstruct the analog value based on pulse width
demodulated_signal(i) = mean(msg(i:j-1));
end
end
% Plot the demodulated signal for comparison
subplot(4,1,4);
plot(t, demodulated_signal);
title('Demodulated Signal');
xlabel('Time');
ylabel('Amplitude');
grid on;