%pulse width modulation and demodulation
close all; clear; clc;

fc = 1000;        % Carrier frequency
fs = 10000;       % Sampling frequency
f1 = 200;         % Message frequency

t = 0:1/fs:((2/f1)-(1/fs));
x1 = 0.4 * cos(2*pi*f1*t) + 0.5;

% Modulation
y1 = modulate(x1, fc, fs, 'pwm');

subplot(3,1,1);
plot(x1);
axis([0 50 0 1]);
title('Original Signal (f1 = 200Hz, fs = 10000Hz)');
xlabel('Time (s)');
ylabel('Amplitude');

subplot(3,1,2);
plot(y1);
axis([0 50 -0.2 1.2]);
title('PWM Modulated Signal');
xlabel('Time (s)');
ylabel('Amplitude');

% Demodulation
x1_recover = demod(y1, fc, fs, 'pwm');
subplot(3,1,3);
plot(x1_recover);
axis([0 50 0 1]);
title('Recovered Signal (PWM Demodulated)');
xlabel('Time (s)');
ylabel('Amplitude');
sgtitle('Sujal Singh (04119051723)') 
