Friday, November 30, 2018

PWM of a signal

Pulse Width Modulation can be used to convert an analog signal to digital or mimic an analog signal with digital (e.g. Arduino's analogWrite()). PWM basically converts the signal sample values into pulse width values (amplitude of pulses is constant). Below is a Matlab script that demonstrates PWM of a sine wave.


%Matlab script to demonstrate PWM of sine signal
clc; clear all; close all;
nSample = 36;
dAngle_rad = deg2rad(20);
sinp1 = zeros(nSample,1);
dutyCyle = zeros(nSample,1);
angle_rad = zeros(nSample,1);
pwmX = zeros(nSample,1);
for i = 1:nSample
angle_rad(i) = dAngle_rad * (i-1);
sinp1(i) = 1 + sin(angle_rad(i)); %signal is between [0, 2]
dutyCyle(i) = sinp1(i) / 2; %PWM duty cycle
pwmX(i) = (dutyCyle(i)*dAngle_rad);
end
subplot(2,1,1);
plot(angle_rad, sinp1, 'o-')
title('PWM of sine'); grid on; set(gca, 'xgrid', 'off');
ylim([-0.1, 2.1]); xlim([min(angle_rad), max(angle_rad)+0.2])
for i=1:nSample
line(angle_rad(i)*[1, 1], [0 sinp1(i)], 'color', 'k');
end
subplot(2,1,2);
plot(angle_rad, sinp1, 'o-');
grid on; hold on; set(gca, 'xgrid', 'off'); ylim([-0.1, 2.1]);
xlim([min(angle_rad), max(angle_rad)+0.2]); xlabel('angle [rad]')
pwmMag = max(sinp1);
for i=1:nSample-1
%ON
line([angle_rad(i), angle_rad(i)+pwmX(i)], [pwmMag pwmMag], 'color', 'r');
line(angle_rad(i)*[1 1], [0 pwmMag], 'color', 'r');
line(angle_rad(i)+pwmX(i)*[1 1], [0 pwmMag], 'color', 'r');
%OFF
line([angle_rad(i)+pwmX(i), angle_rad(i)+pwmX(i) + dAngle_rad-pwmX(i)], [0 0], 'color', 'r');
end
view raw sinePWM.m hosted with ❤ by GitHub

No comments: