PWM Frequency and Duty Cycle in Embedded C Explained
PWM frequency is how often the pulse repeats per second, and duty cycle is the percentage of time the pulse stays high in one cycle. Together, they control the power delivered to devices like motors or LEDs by switching the signal on and off rapidly.How It Works
PWM stands for Pulse Width Modulation. Imagine turning a light switch on and off very fast. The frequency is how many times you flip the switch on and off every second. For example, a frequency of 1 kHz means the switch flips 1000 times per second.
The duty cycle is like how long the switch stays on during each flip. If the switch is on half the time and off half the time, the duty cycle is 50%. If it stays on longer, say 75% of the time, the device gets more power.
In embedded C, you set these values to control devices smoothly. For example, a motor can run slower or faster depending on the duty cycle, even though the power supply is constant.
Example
This example shows how to configure PWM frequency and duty cycle on a microcontroller using embedded C. It sets a frequency of 1 kHz and a duty cycle of 50%.
#include <stdint.h> #include <stdio.h> // Assume a microcontroller with a timer clock of 1 MHz #define TIMER_CLOCK 1000000 // Function to calculate timer counts for frequency uint16_t calculate_period(uint32_t frequency) { return (uint16_t)(TIMER_CLOCK / frequency); } // Function to calculate compare value for duty cycle uint16_t calculate_duty(uint16_t period, float duty_cycle_percent) { return (uint16_t)(period * (duty_cycle_percent / 100.0f)); } int main() { uint32_t pwm_frequency = 1000; // 1 kHz float duty_cycle = 50.0f; // 50% uint16_t period = calculate_period(pwm_frequency); uint16_t duty = calculate_duty(period, duty_cycle); printf("PWM Frequency: %u Hz\n", pwm_frequency); printf("Timer Period Counts: %u\n", period); printf("Duty Cycle: %.1f%%\n", duty_cycle); printf("Compare Value (ON time counts): %u\n", duty); // Here you would load 'period' and 'duty' into timer registers return 0; }
When to Use
Use PWM frequency and duty cycle control when you want to adjust power to devices without changing voltage. This is common in:
- Controlling motor speed smoothly
- Dimming LEDs without flicker
- Generating audio tones
- Power regulation in embedded systems
Choosing the right frequency avoids noise or flicker, and adjusting duty cycle changes how much power the device receives.
Key Points
- Frequency is how often the PWM signal repeats per second.
- Duty cycle is the percentage of time the signal is ON in each cycle.
- Changing duty cycle controls power delivered without changing voltage.
- Embedded C uses timers to set frequency and duty cycle values.
- Proper frequency selection prevents flicker and noise in devices.