0
0
Embedded Cprogramming~5 mins

PWM generation using timers in Embedded C

Choose your learning style9 modes available
Introduction

PWM (Pulse Width Modulation) lets us control devices like motors or LEDs by turning a signal on and off very fast. Using timers helps create this signal automatically and precisely.

To control the brightness of an LED by changing how long it stays on.
To adjust the speed of a motor smoothly.
To generate audio tones by varying the signal.
To control servo motors in robotics.
To create precise timing signals for communication.
Syntax
Embedded C
1. Configure the timer's mode to PWM.
2. Set the timer's period (frequency).
3. Set the duty cycle (how long signal stays high).
4. Start the timer to begin PWM output.

The exact code depends on your microcontroller and its timer registers.

Duty cycle is usually set by changing the compare register value.

Examples
This sets a PWM with 50% duty cycle on an 8-bit timer.
Embedded C
// Example for a generic 8-bit timer
TIMER_MODE = PWM_MODE;
TIMER_PERIOD = 255; // max count
TIMER_COMPARE = 128; // 50% duty cycle
TIMER_START();
Using STM32 HAL, this starts PWM on channel 1 with 50% duty cycle.
Embedded C
// Example for STM32 HAL library
TIM_HandleTypeDef htim;
htim.Init.Prescaler = 0;
htim.Init.Period = 999;
HAL_TIM_PWM_Start(&htim, TIM_CHANNEL_1);
__HAL_TIM_SET_COMPARE(&htim, TIM_CHANNEL_1, 500); // 50% duty
Sample Program

This program sets up Timer0 on an AVR microcontroller to generate a 50% duty cycle PWM signal on pin PD6.

Embedded C
#include <avr/io.h>

int main(void) {
    // Set PD6 (OC0A) as output
    DDRD |= (1 << PD6);

    // Set Timer0 to Fast PWM mode
    TCCR0A |= (1 << WGM01) | (1 << WGM00);
    TCCR0B |= (1 << CS00); // No prescaling

    // Set non-inverting mode on OC0A
    TCCR0A |= (1 << COM0A1);

    // Set duty cycle to 50%
    OCR0A = 128;

    while(1) {
        // PWM runs automatically
    }

    return 0;
}
OutputSuccess
Important Notes

Make sure the output pin is set as output in the data direction register.

Changing the OCR (Output Compare Register) value changes the duty cycle.

Timer prescaler affects PWM frequency; choose it based on your needs.

Summary

PWM uses timers to create signals that switch on and off quickly.

Duty cycle controls how long the signal stays on in each cycle.

Setting timer mode, period, and compare value generates PWM automatically.