Pulse Width Modulation (PWM)
Pulse Width Modulation(PWM) is something that is often used in embedded systems. Commonly you’ll see this used for controlling the average amplitude or power of a signal.
Let’s define some terms :
Period : Time taken for some cycle to repeat(in this case, a voltage rectangular waveform).
Duty Cycle(“On time”) : The length that the signal is on within an individual cycle.
Frequency : How often a cycle occurs within some unit of time
F = 1/T, where T is in seconds(s), and F is in Hertz(Hz).
Operation:
PWM works by controlling the duty cycle of this rectangular waveform at some fixed frequency.
Here are some examples where this is used and some calculations:
A DC Fan in a computer is typically 12V rated, and realistically the motor stops working at approximately 7V. Let’s say we want to control Fan RPM, the most logical approach is to change the voltage. But what if we want to go at a very low fan speed that requires us to be under 7V? Let’s say we don’t have adjustable voltage control, just 12V. How could I make the fan run slower? Now imagine turning the fan on and off at an extremely fast rate, the average speed of the fan would be slower. This is exactly how PWM works. When you see a “PWM Fan”, it refers to it having a PWM signal pin where we control the duty cycle to do what we described.
In a voltage regulator, we have a “switch”(usually a transistor) that turns on and off. The duty cycle will affect the output voltage, and the regulator has a feedback pin that senses the output voltage and adjusts duty cycle to maintain constant voltage
Vout = Vin * (Duty Cycle) where Duty Cycle is between 0 and 1(0% to 100%)
ton = (Duty_Cycle) * Period
toff = (1-Duty_Cycle) * Period
Things to Consider:
Let’s go back to the fan example. Turning a fan on and off very slowly evidently shows us the average fan speed is going to fluctuate around, so if we graphed this it would be very “jittery”. This tells us our PWM frequency being too low will lead to “stutters” and unpleasant results. However, too high frequencies can cause excessive transistor switching losses(Gate capacitance and non ideal properties of a switching component).
Firmware Implementation:
In our firmware we use output compare registers to toggle the state of the timer pin. In a bare-metal application, the timer continuously compares the counter value with the output compare register. When a match occurs, a hardware interrupt occurs and it automatically toggles the GPIO pin. The hardware manages this operation without the need for coded ISRs. To learn more about timers here are resources:
Introduction to STM32 Timer Basics and Library
Getting Started with STM32 - Timers and Timer Interrupts