Lessons and the learning game

Timers, PWM and capture on four chips

Set up timers by hand on an Uno, an ESP32-C3, a Pico and an STM32: prescalers, PWM, input capture, and one PWM driver with the same calls on all four.

The bench

Each lesson opens one board with a lamp on its PWM pin and a frequency counter (0.1 s gate) clipped on the same pin, plus a second counter where a second output matters. Every frequency a step checks is read by a counter, so a step passes on what the pin really does. The project opens all four boards at once, each with a lamp and a counter on its tone pin.

Take the course at Timers, PWM and capture on four chips on /learn.

What each sketch does

  • tmrbasics (Uno): Timer1 in CTC mode toggles pin 9 once a second and interrupts on every match.
  • tmravr (Uno): Timer1 fast PWM mode 14 at 1000 Hz and 25 percent on pin 9, beside analogWrite()'s 490 Hz on pin 3.
  • tmrledc (ESP32-C3): LEDC at 5 kHz and 10 bits on GPIO 4, a 440 Hz tone on GPIO 5, and a frequency and resolution the hardware refuses.
  • tmrpico (Pico): PWM slice 1 by register, GP2 and GP3 sharing a frequency, and the 8.4 fixed-point divider.
  • tmrstm (Black Pill): TIM3 channels 1 and 2 on PA6 and PA7, and center-aligned counting.
  • tmrcapture (Uno): Timer1 input capture on pin 8 with an overflow count, as a reciprocal counter, measuring a tone from pin 3.
  • tmrdrvuno, tmrdrvc3, tmrdrvpico, tmrdrvstm: the project, the same pwmBegin, pwmDuty and pwmTone calls on each chip's own timers.

Honest limits of the simulator

  • A function generator's square wave reaches an MCU pin here on a grid of about a millisecond, so input capture of a funcgen signal reads wrong in the simulator. The capture lesson measures a digital signal from the Uno's own pin 3 instead, which is exact, and keeps the frequency counter as the reference.
  • The Uno's Timer1 external clock input (T1, pin 5) is not modeled, so no lesson counts edges with it.
  • The RP2040's phase-correct mode and edge-counting mode are not modeled; the Pico lesson uses the fractional divider instead.
  • The frequency counter reads edges exactly, with no noise and no time base error.

Bare-metal STM32 builds TIM3 one register at a time, and Scheduling and RTOS uses timers to schedule tasks.