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.
Practical Checklist
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 cycle | Approximate 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:
| Timer | Counter width | Relevant control registers |
|---|---|---|
| Timer0 | 8-bit | TCCR0A, TCCR0B |
| Timer1 | 16-bit | TCCR1A, TCCR1B |
| Timer2 | 8-bit | TCCR2A, TCCR2B |
This practical uses Timer0, with an 8-bit counter TCNT0 and output compare register OCR0A.
2.1 TCCR0A — output and waveform mode
| Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|
| COM0A1 | COM0A0 | COM0B1 | COM0B0 | — | — | WGM01 | WGM00 |
For Fast PWM, non-inverting output on OC0A:
TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00);
COM0A1=1,COM0A0=0selects non-inverting PWM on OC0A.WGM01=1,WGM00=1together withWGM02=0selects Fast PWM withTOP=0xFF.OCR0Adetermines the compare threshold, and therefore the approximate duty cycle.
2.2 TCCR0B — clock source and prescaler
| Bit 7 | Bit 6 | Bit 5 | Bit 4 | Bit 3 | Bit 2 | Bit 1 | Bit 0 |
|---|---|---|---|---|---|---|---|
| FOC0A | FOC0B | — | — | WGM02 | CS02 | CS01 | CS00 |
For Timer0, the clock selection bits provide:
| CS02 | CS01 | CS00 | Timer clock selection |
|---|---|---|---|
| 0 | 0 | 0 | Stopped |
| 0 | 0 | 1 | Clock / 1 |
| 0 | 1 | 0 | Clock / 8 |
| 0 | 1 | 1 | Clock / 64 |
| 1 | 0 | 0 | Clock / 256 |
| 1 | 0 | 1 | Clock / 1024 |
| 1 | 1 | 0 | External clock on T0, falling edge |
| 1 | 1 | 1 | External 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} \]
| Prescaler | PWM frequency at 16 MHz |
|---|---|
| 8 | 7,812.5 Hz |
| 64 | 976.56 Hz |
| 256 | 244.14 Hz |
| 1024 | 61.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.
}
}
-
From Git Bash, create and enter the project directory:
mkdir -p ~/embeddedC/pwm cd ~/embeddedC/pwm -
Create the source file:
touch pwm.c code pwm.c -
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
-
Copy the Makefile from your earlier Blink project:
cp ../blink/Makefile . vim Makefile -
Press Esc, then run the following Vim substitution to replace the whole word
blinkwithpwm::%s/\<blink\>/pwm/g
-
Check the correct serial port before uploading. Change the
PORTvariable in the Makefile if necessary.Get-CimInstance Win32_SerialPort | Select-Object Name, DeviceID, Description
wmic path Win32_SerialPort get caption,name,deviceidThe
wmiccommand may not be installed on recent Windows systems. Use PowerShell or Device Manager instead.
ls /dev/ttyACM* /dev/ttyUSB* 2>/dev/nullDevice names and permissions depend on the USB interface and your distribution.
PORT = COM6 -
Compile and upload:
make clean make make uploadWhat happens during the build?
The Makefile first compiles
pwm.cintopwm.o, links it intopwm.elf, converts the flash image topwm.hex, and then usesavrdudeto upload the firmware. -
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
-
Set
OCR0A = 64;, runmakeandmake upload, and record your observation. -
Repeat for
OCR0A = 127;andOCR0A = 192;. -
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
-
Add
#define F_CPU 16000000ULbefore including<util/delay.h>and update the main loop. -
Use loops with a type that can reach the termination condition without wrapping around.
-
Compile, upload, and observe the LED. Try reducing or increasing the inter-step delay.
A
uint8_tranges from 0 to 255. The expressioni <= 255is always true for auint8_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
-
Set a fixed intermediate compare value, for example
OCR0A = 127;. -
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, keepingOCR0A = 127and Fast PWM mode unchanged.Prescaler CS02 CS01 CS00 Fast PWM frequency (16 MHz) 8 0 1 0 7,812.5 Hz 64 0 1 1 976.56 Hz 256 1 0 0 244.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 /#endifto 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.
-
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.