Skip to main content

1. PWM (Pulse Width Modulation)

PWM is a technique used to simulate analog output using a digital signal. Instead of producing a true analog voltage, the microcontroller rapidly switches a pin between HIGH and LOW.

Term Meaning
Period Total time of one cycle
Duty Cycle Percentage of time signal is HIGH

Changing the duty cycle changes the average voltage seen by external devices.

AVR microcontrollers provide hardware timers that can automatically generate PWM signals in the background. It basically switches on and off on certain positions of the counter. To generate more finely controlled PWM output (such as those for servos), Timer1 is usually used as it is 16 bits thus allowing more precise features.

Phase Correct PWM

Phase correct PWM uses dual slop that goes up and down, switching between those operations. This mode performs more accurately in exchange for half the available frequency.

Fast PWM

Fast PWM provides PWM with higher frequency but lower resolution because it uses a single-slope operation, where the counter immediately returns to 0 after reaching its maximum value. Fast PWM is commonly used for devices that require high-frequency signals.

TCCRnA and TCCRnB — Timer/Counter Control Registers

TCR1A

TCR1B

COM

COM1x1 COM1x0 Description
0 0 Normal port operation (PWM disconnected)
0 1 Toggle OC1X on Compare Match (special case)
1 0 Clear on Compare Match, Set at BOTTOM (Non-inverting PWM)
1 1 Set on Compare Match, Clear at BOTTOM (Inverting PWM)

WGM

Certain modes in the Timer that affects PWM behavior

Mode WGM13 WGM12 WGM11 WGM10 Mode Name TOP
1 0 0 0 1 PWM Phase Correct 8-bit 0x00FF
2 0 0 1 0 PWM Phase Correct 9-bit 0x01FF
3 0 0 1 1 PWM Phase Correct 10-bit 0x03FF
5 0 1 0 1 Fast PWM 8-bit 0x00FF
6 0 1 1 0 Fast PWM 9-bit 0x01FF
7 0 1 1 1 Fast PWM 10-bit 0x03FF
8 1 0 0 0 PWM Phase & Frequency Correct (ICR1) ICR1
9 1 0 0 1 PWM Phase & Frequency Correct (OCR1A) OCR1A
10 1 0 1 0 PWM Phase Correct (ICR1) ICR1
11 1 0 1 1 PWM Phase Correct (OCR1A) OCR1A
14 1 1 1 0 Fast PWM (ICR1 TOP) ICR1
15 1 1 1 1 Fast PWM (OCR1A TOP) OCR1A

OCRn — Output Compare Register

The Output Compare Register stores a value that the timer constantly compares against the counter. When the counter hits that value, it triggers compare match that does different things aaccording to COM to the set output pin.

  • Setting a pin HIGH
  • Clearing a pin LOW
  • Triggering an interrupt

ICRn — Input Capture Register

The Input Capture Register is used in certain PWM modes as the TOP value of the timer. This means the timer counts from 0 up to the value stored in ICRn before restarting the counting cycle.

When used as TOP, ICRn determines the PWM period (frequency).

In PWM modes that use ICRn as TOP (such as mode 8 & 15), the timer behavior becomes:

Counter: 0 → ICRn → reset

Changing ICRn changes the PWM frequency, while OCRn still controls the duty cycle.