What is PWM in Embedded C: Explanation and Example
Embedded C, PWM (Pulse Width Modulation) is a technique to create a digital signal that simulates an analog output by switching a pin ON and OFF rapidly with varying ON time. It controls devices like motors and LEDs by adjusting the signal's duty cycle, which is the percentage of time the signal stays ON in each cycle.How It Works
Think of PWM like turning a light switch ON and OFF very fast. Instead of just ON or OFF, you control how long the switch stays ON compared to OFF in each cycle. This ratio is called the duty cycle.
For example, if the switch is ON half the time and OFF half the time, the duty cycle is 50%. This makes the light appear dimmer than if it was ON all the time. In embedded systems, PWM uses this idea to control power to devices without needing a real analog output.
The microcontroller sets a timer to create these ON/OFF pulses on a pin. By changing the ON time (pulse width), you can control speed, brightness, or position in devices like motors, LEDs, or speakers.
Example
This example shows how to generate a simple PWM signal on a microcontroller pin using Embedded C. It sets a 50% duty cycle, meaning the signal is ON half the time and OFF half the time.
#include <avr/io.h> #include <util/delay.h> int main(void) { DDRB |= (1 << PB1); // Set PB1 as output (OC1A pin on AVR) // Configure Timer1 for Fast PWM mode, non-inverting TCCR1A = (1 << COM1A1) | (1 << WGM11); TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); // No prescaling ICR1 = 39999; // Set TOP for 20ms period (50Hz) OCR1A = 19999; // 50% duty cycle (pulse width 10ms) while (1) { // PWM runs automatically by hardware } return 0; }
When to Use
Use PWM in embedded systems when you need to control devices that require varying power levels but only have digital outputs. Common uses include:
- Controlling motor speed by adjusting voltage indirectly
- Dimming LEDs smoothly without changing hardware
- Generating audio tones or signals
- Controlling servo motor positions
PWM is efficient because it uses digital signals and hardware timers, saving power and CPU time compared to analog methods.
Key Points
- PWM creates analog-like control using digital signals by changing ON/OFF time.
- Duty cycle controls how much power a device receives.
- Hardware timers in microcontrollers generate PWM signals automatically.
- Commonly used for motors, LEDs, and servos in embedded systems.