Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Last updated: Friday 13 November 2026 @ 17:29:40
Programming for Engineers

Pulse-Width Modulation

In this practical you will configure hardware-generated PWM on an ATmega328P, moving from Arduino's analogWrite() abstraction to the registers that control the output waveform. You will build and upload pwm.c, vary the LED brightness and investigate PWM frequency.

ATmega328PTimer0Fast PWMDuty cycleEmbedded C
Practical Checklist
Chapter checklist 0 / 8 completed

1. Understanding PWM

Pulse-width modulation (PWM) varies the proportion of time a digital output stays high within each repeated cycle. This proportion is the duty cycle. The output remains digital; an LED’s perceived brightness changes because its average current changes rapidly.

Duty cycleApproximate behaviour
25%High for approximately one quarter of each period
50%High for approximately half of each period
75%High for approximately three quarters of each period

2. Timer0 and its registers

The ATmega328P contains three timer/counter peripherals:

TimerCounter widthRelevant control registers
Timer08-bitTCCR0A, TCCR0B
Timer116-bitTCCR1A, TCCR1B
Timer28-bitTCCR2A, TCCR2B

This practical uses Timer0, with an 8-bit counter TCNT0 and output compare register OCR0A.

2.1 TCCR0A — output and waveform mode

Bit 7Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
COM0A1COM0A0COM0B1COM0B0——WGM01WGM00

For Fast PWM, non-inverting output on OC0A:

TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
  • COM0A1=1, COM0A0=0 selects non-inverting PWM on OC0A.
  • WGM01=1, WGM00=1 together with WGM02=0 selects Fast PWM with TOP=0xFF.
  • OCR0A determines the compare threshold, and therefore the approximate duty cycle.

2.2 TCCR0B — clock source and prescaler

Bit 7Bit 6Bit 5Bit 4Bit 3Bit 2Bit 1Bit 0
FOC0AFOC0B——WGM02CS02CS01CS00

For Timer0, the clock selection bits provide:

CS02CS01CS00Timer clock selection
000Stopped
001Clock / 1
010Clock / 8
011Clock / 64
100Clock / 256
101Clock / 1024
110External clock on T0, falling edge
111External clock on T0, rising edge
TCCR0B = (1 << CS01);
TCCR0B = (1 << CS01) | (1 << CS00);
TCCR0B = (1 << CS02);
TCCR0B = (1 << CS02) | (1 << CS00);

2.3 Calculate the output frequency

For Timer0 Fast PWM with TOP=255, the frequency is:

\[ f_{PWM} = \frac{f_{CPU}}{N \times 256} \]

where \(N\) is the prescaler. With a 16 MHz CPU clock and \(N=64\):

\[ f_{PWM} = \frac{16,000,000}{64\times256} = 976.5625\ \text{Hz} \]

PrescalerPWM frequency at 16 MHz
87,812.5 Hz
64976.56 Hz
256244.14 Hz
102461.04 Hz

3. From analogWrite() to pwm.c

const int pwmPin = 6;

void setup() {
    pinMode(pwmPin, OUTPUT);
    analogWrite(pwmPin, 127);
}

void loop() {
    // Hardware PWM continues without repeated writes.
}
#include <avr/io.h>

static void PWM_Init(void) {
    DDRD |= (1 << DDD6);  // PD6 / OC0A is an output
    TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
    TCCR0B = (1 << CS01) | (1 << CS00);  // /64
    OCR0A = 127; // Approximately 50% duty cycle
}

int main(void) {
    PWM_Init();
    while (1) {
        // Hardware PWM continues without repeated writes.
    }
}
  1. From Git Bash, create and enter the project directory:

    mkdir -p ~/embeddedC/pwm
    cd ~/embeddedC/pwm
  2. Create the source file:

    touch pwm.c
    code pwm.c
  3. Enter the full programme below and save it.

    #include <avr/io.h>
    
    static void PWM_Init(void)
    {
        // Arduino digital pin 6 = ATmega328P PD6 = OC0A.
        DDRD |= (1 << DDD6);
    
        // Fast PWM, TOP = 0xFF, non-inverting OC0A.
        TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
    
        // Timer0 clock = 16 MHz / 64.
        TCCR0B = (1 << CS01) | (1 << CS00);
    
        // Approximately 50% duty cycle.
        OCR0A = 127;
    }
    
    int main(void)
    {
        PWM_Init();
    
        while (1) {
            // Hardware Timer0 drives the pin independently.
        }
    }

4. Build, upload and observe

  1. Copy the Makefile from your earlier Blink project:

    cp ../blink/Makefile .
    vim Makefile
  2. Press Esc, then run the following Vim substitution to replace the whole word blink with pwm:

    :%s/\<blink\>/pwm/g

    Replacing blink targets in the Makefile

  3. Check the correct serial port before uploading. Change the PORT variable in the Makefile if necessary.

    Get-CimInstance Win32_SerialPort | Select-Object Name, DeviceID, Description

    PowerShell list of serial ports

    wmic path Win32_SerialPort get caption,name,deviceid

    The wmic command may not be installed on recent Windows systems. Use PowerShell or Device Manager instead.

    Windows serial port listing

    ls /dev/ttyACM* /dev/ttyUSB* 2>/dev/null

    Device names and permissions depend on the USB interface and your distribution.

    PORT = COM6
  4. Compile and upload:

    make clean
    make
    make upload
    What happens during the build?

    The Makefile first compiles pwm.c into pwm.o, links it into pwm.elf, converts the flash image to pwm.hex, and then uses avrdude to upload the firmware.

  5. With the board disconnected from power, connect the external LED and resistor in series:

    • digital pin 6 → 220–330 Ω resistor → LED anode (+); LED cathode (−) → GND.

    Reconnect the board and check that the LED lights at partial brightness.

5. Independent exercises

Exercise 1 - Change the duty cycle

  1. Set OCR0A = 64;, run make and make upload, and record your observation.

  2. Repeat for OCR0A = 127; and OCR0A = 192;.

  3. Explain why the LED's brightness changes although the PWM frequency remains fixed.

    Hint

    The timer still completes 256 counts per cycle. Only the point at which the output changes state moves.

Exercise 2 - Create a breathing LED

  1. Add #define F_CPU 16000000UL before including <util/delay.h> and update the main loop.

  2. Use loops with a type that can reach the termination condition without wrapping around.

  3. Compile, upload, and observe the LED. Try reducing or increasing the inter-step delay.

    A uint8_t ranges from 0 to 255. The expression i <= 255 is always true for a uint8_t, so an incrementing loop can wrap from 255 back to 0 and never terminate. Use a wider integer type for the loop counter.

    #define F_CPU 16000000UL
    #include <avr/io.h>
    #include <util/delay.h>
    #include <stdint.h>
    
    static void PWM_Init(void)
    {
        DDRD |= (1 << DDD6);
        TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
        TCCR0B = (1 << CS01) | (1 << CS00);
        OCR0A = 0;
    }
    
    int main(void)
    {
        PWM_Init();
        while (1) {
            for (uint16_t level = 0; level <= 255; ++level) {
                OCR0A = (uint8_t)level;
                _delay_ms(10);
            }
            for (int16_t level = 255; level >= 0; --level) {
                OCR0A = (uint8_t)level;
                _delay_ms(10);
            }
        }
    }

Exercise 3 - Change the PWM frequency

  1. Set a fixed intermediate compare value, for example OCR0A = 127;.

  2. Try prescalers 8, 64 and 256, compiling and uploading between changes.

    The CS02:CS00 bits determine the clock divisor used by Timer0. Change only the prescaler selection, keeping OCR0A = 127 and Fast PWM mode unchanged.

    PrescalerCS02CS01CS00Fast PWM frequency (16 MHz)
    80107,812.5 Hz
    64011976.56 Hz
    256100244.14 Hz

    Use the relationship:

    \[f_{\mathrm{PWM}} = \frac{f_{\mathrm{CPU}}}{N\times256}\]

    where \(N\) is the prescaler. Try implementing the selection with #if / #elif / #else /#endif to avoid editing the register expression repeatedly.

    #include <avr/io.h>
    
    // Change to 8, 64 or 256; recompile and upload each time.
    #define PWM_PRESCALER 64
    
    static void PWM_Init(void)
    {
        DDRD |= (1 << DDD6);  // OC0A / Arduino digital pin 6
    
        // Timer0 Fast PWM, non-inverting output on OC0A.
        TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
        OCR0A = 127;         // Keep duty cycle approximately 50%.
    
        #if PWM_PRESCALER == 8
            TCCR0B = (1 << CS01);
        #elif PWM_PRESCALER == 64
            TCCR0B = (1 << CS01) | (1 << CS00);
        #elif PWM_PRESCALER == 256
            TCCR0B = (1 << CS02);
        #else
            #error "PWM_PRESCALER must be 8, 64 or 256"
        #endif
    }
    
    int main(void)
    {
       PWM_Init();
       while (1) {
           // PWM continues automatically in timer hardware.
       }
    }

    Rebuild and upload the firmware after each change to PWM_PRESCALER. Observe the output using an oscilloscope or logic analyser, if available.

  3. Explain whether a visible change in LED brightness is a reliable way to measure PWM frequency.

    Expected interpretation

    At a fixed compare value, the approximate duty cycle is unchanged. The PWM frequency changes from about 7.81 kHz (prescaler 8), to 976.56 Hz (64), to 244.14 Hz (256). Human visual perception is not a reliable frequency meter in this range; use an oscilloscope or logic analyser for quantitative measurement.