5.5.3 · D3Embedded Systems & Real-Time Software

Worked examples — Timers — PWM generation, input capture, output compare

2,485 words11 min readBack to topic

The scenario matrix

Every timer problem is one (or a blend) of these cells. Each worked example below is tagged with the cell(s) it covers.

# Cell (case class) What makes it tricky Example
A Forward design, PWM % — pick PSC/ARR/CCR for a target frequency + duty choosing PSC to keep ticks tidy Ex 1
B Forward design, pulse-width (servo/ESC) — set CCR in µs, not % duty is irrelevant; width matters Ex 2
C Degenerate duty — 0%, 100%, and the off-by-one at the top vs Ex 3
D Toggle mode — square wave, divide-by-2 subtlety two toggles = one period Ex 4
E Input capture, no wrap — measure a frequency plain subtraction Ex 5
F Input capture, WITH wrap — the negative-difference trap modulo arithmetic Ex 6
G Limiting / resolution — smallest & largest frequency a 16-bit timer can hit ARR range limits Ex 7
H Real-world word problem — dim an LED to a perceived brightness mapping physical want → registers Ex 8
I Exam twist — given a scope reading, reverse-engineer the registers invert every formula Ex 9
Figure — Timers — PWM generation, input capture, output compare

Example 1 — Cell A: forward PWM design


Example 2 — Cell B: pulse-width design (servo)


Example 3 — Cell C: the degenerate duties (0 %, 100 %)


Example 4 — Cell D: toggle mode square wave

Figure — Timers — PWM generation, input capture, output compare

Example 5 — Cell E: input capture, no overflow


Example 6 — Cell F: input capture ACROSS an overflow

Figure — Timers — PWM generation, input capture, output compare

Example 7 — Cell G: limiting frequencies of a 16-bit timer


Example 8 — Cell H: real-world word problem (LED dimming)


Example 9 — Cell I: exam twist (reverse-engineer from a scope)


Which cell is which — decision flow

want a pin waveform

want to measure a signal

target is a percent

target is a pulse width

just a square wave

c2 greater than c1

c2 less than c1

Start: what is given?

Design mode Time to Pin

Capture mode Pin to Time

Solve ARR then CCR equals duty times ARR plus 1

Set CCR equals width in ticks

Toggle mode divide match rate by 2

Delta equals c2 minus c1

Delta equals difference mod ARR plus 1

Check degenerate 0 and 100 percent


Active recall


Connections

  • Parent topic (Hinglish) — the machinery these examples exercise.
  • Clock Tree and Prescalers — where and the tidy-tick choices come from.
  • GPIO and Alternate Functions — the pin every PWM/toggle example drives.
  • Interrupts and NVIC — overflow-counting for the Cell F wrap case.
  • Servo and ESC Control — Example 2's pulse-width interpretation.
  • Motor Control and H-Bridges — Example 1 & 8 style duty control at speed.
  • Encoder Mode — a capture cousin for the curious.