MTBuilder AcademyLearn it. Test it. Build it.
Code & microcontrollersLesson 28 of 48
Practice60 minutes2 project connections

Timers, deadlines, and PWM

Use hardware timebases and PWM duty cycle to schedule work and choose a switching rate that controls average power without confusing frequency with resolution.

After this lesson, you can
  • Calculate timer periods and PWM duty cycles, implement rollover-safe periodic work, and explain what a PWM output does and does not control.
ReadPracticedBench demonstrated
Related study — optional context
01

Understand

The working idea

A timer counts clock ticks so firmware can act at useful intervals without staring at a wall clock. The same idea coordinates a screen refresh, a sensor sample, or a motor-control pulse. If a counter advances at f_tick ticks per second, one tick lasts T_tick = 1/f_tick, and N ticks span N/f_tick seconds. Hardware compare units can change a pin or request service when the count reaches a chosen value.

Pulse-width modulation switches an output repeatedly. Duty cycle D = t_on/T is the fraction of each period that is on, while PWM frequency f = 1/T says how often periods repeat. For an ideal 12 V source at 25% duty, the time-average switched voltage is 3 V, but the instantaneous motor-terminal waveform still alternates between approximately 0 V and 12 V. Motor inductance and inertia smooth current and speed; an LED averages brightness to the eye. This is not an adjustable DC supply for every load.

Timer resolution and frequency trade off when a fixed clock supplies the counter. With a 1 MHz timer and 100-count period, PWM is 10 kHz with 101 possible compare positions if endpoints are included. A larger period permits finer duty steps but lowers frequency. Choosing 20 kHz for a small motor can move switching above much of human hearing, yet driver losses and MCU limits must be checked. That frequency choice is a build decision, not folklore.

Common errors include confusing 50% duty with half speed, assuming duty directly sets torque under every load, and writing delay-based schedules that drift. For periodic work, advance the deadline by the intended period rather than setting it to “now plus period” after variable work. Counter rollover is normal; use the platform’s documented difference arithmetic rather than comparisons that fail once the counter wraps. The associated simulation is a bounded scheduling model, not a reproduction of a particular timer peripheral.

02

Follow the reasoning

Worked example

An 8 MHz timer uses a prescaler of 8 and counts 0 through 199 for PWM. Find frequency and the compare value nearest 30% duty.

  1. 1

    Timer tick frequency = 8 MHz / 8 = 1 MHz, so each tick is 1 µs.

  2. 2

    The inclusive 0…199 period has 200 ticks, so T = 200 µs and f = 1/200 µs = 5 kHz.

  3. 3

    Thirty percent of 200 ticks is 60 on-ticks, so configure the platform’s compare semantics for 60 high ticks.

Result

The PWM frequency is 5 kHz and 60 of 200 ticks produces 30% duty under the stated edge convention.

Sanity check5,000 periods/s × 200 ticks/period = 1,000,000 ticks/s, matching the prescaled timer clock.

03

Try it yourself

Independent check

A periodic task should run every 10 ms. Its work sometimes takes 3 ms. Which update best avoids accumulating phase drift?
04

Move to the bench

Measure PWM timing and compare non-blocking periodic scheduling with a drifting completion-based schedule.

Gather
  • Microcontroller with PWM
  • LED and 330 Ω resistor
  • logic analyzer or oscilloscope if available
  • serial console

Experiment

  1. Configure an LED PWM output near 1 kHz and command 25%, 50%, and 75% duty; log requested values.
  2. If an instrument is available, measure high time and period at one setting; otherwise use a slow 2 Hz test waveform and timestamp edges in software.
  3. Schedule a status print every 100 ms by advancing the stored deadline from its prior value.
  4. Introduce a deliberate fault by scheduling from task completion and adding 20 ms of simulated work; compare timestamp drift, then restore deadline-based scheduling.
  5. Document timer frequency, resolution, and whether the output polarity inverts the numeric duty.

Observe

  • Expected: nominal high time at 1 kHz and 25% duty is 0.25 ms; actual measured period and high time must be recorded separately.
  • Expected: deadline-based timestamps remain near multiples of 100 ms, while completion-based scheduling accumulates the added work time.
  • Record actual jitter and instrument resolution rather than interpreting requested duty as measured duty.
Transfer it

Choose a PWM frequency and initial duty limit for a transistor-driven miniature fan, stating what motor/driver documentation you would verify before testing.

Limits and cautions
  • Drive only the resistor-limited LED directly; a fan or motor requires a suitable driver and separate current-path analysis.
05

Keep evidence

Bench note

Record what you expected, what you actually measured or observed, and one difference worth investigating. This is self-reported evidence, not a certification.

0 / 5,000A bench demonstration needs a concrete note of at least 20 characters.
Terms in this lessonBrowse the advanced glossary

Sources and further reading

  1. MicroPython RP2 quick reference
  2. Arduino Blink Without Delay