Electronics · Optional embedded electronics and a sensor logger
Use a timer, an interrupt and PWM
A timer can keep counting while the processor does something else. To use it well, identify what the hardware counts, when it generates an event, and when software actually responds. Then check what the output waveform means for the circuit it drives.
Lesson preparation and course links
Use the optional first-program concepts and the GPIO/timing introduction. Clock division, inclusive counts, interrupt latency, RMS/mean and modular subtraction are developed here. All tasks can use the declared model on paper; no device, simulator or programming run is required.
Back to the Electronics chapterAfter reading, you can
Derive timer rate and PWM duty from a declared peripheral contract. Separate hardware events from polling or interrupt response, check initialization and lost events, and calculate elapsed ticks under an explicit wraparound bound.
Declare the timer rather than guessing from the CPU clock
Use a mathematical STM32-style timer contract based on AN4013: a 48 MHz timer input, a prescaler setting PSC=47, edge-aligned up-counting from CNT=0 through ARR=999 inclusive, and a periodic wrap/update. No repetition division is active (RCR=0 where present). For pulse width modulation (PWM), the selected PWM1 output is active high while CNT<CCR, with CCR=250.
These are declared fixture values. They are not a runnable register configuration for an unspecified STM32, and PSC/ARR semantics must not be transferred to the previous Pico program. Clock trees, available modes, register widths, pin mappings and buffered-update behaviour require the exact device documentation before implementation.
The timer input is the frequency actually reaching this peripheral. It need not equal the processor clock or an assumed bus clock. The exercise begins after initialization in a defined periodic mode; startup transitions and pin propagation are outside its ideal waveform.
| Item | Assumption |
|---|---|
| Timer input | 48,000,000 Hz |
| PSC | 47 means divide by 48 |
| ARR | 999 means count 0…999: 1000 ticks |
| Mode | Edge-aligned up-counter; periodic wrap/update; no repetition division |
| PWM output | Active high in PWM1 while CNT<CCR |
| CCR | 250 active counts per 1000-count period |
Count the zero value and both divider offsets
The prescaler divides by PSC+1=48, so the counter rate is 48 MHz/48=1 MHz. One counter tick lasts 1 µs. An ARR value of 999 gives 1000 ticks per period because zero is a count too.
The periodic update rate is fUPDATE=fTIM/[(PSC+1)(ARR+1)]=48,000,000/(48×1000)=1000 Hz. Its period is T=1/fUPDATE=1 ms. These equations apply to the declared up-counter/no-repetition contract; another mode can change their meaning.
As a supplied configuration fault, writing ARR=1000 instead makes 1001 ticks: T=1.001 ms and fUPDATE≈999.001 Hz. Writing PSC=48 instead divides by 49, giving 1.020833… ms with ARR still 999. If both mistakes occur, the period is 49×1001/48,000,000 s≈1.021854 ms.
An off-by-one setting is a count/configuration error. It should not be explained away as oscillator calibration. First identify the actual programmed fields and mode, then compare the resulting nominal count with any observed timing.
| PSC | ARR | Counts/division | Period ms |
|---|---|---|---|
| 47 | 999 | 48×1000 input cycles | 1.000000 |
| 47 | 1000 | 48×1001 input cycles | 1.001000 |
| 48 | 999 | 49×1000 input cycles | 1.020833… |
| 48 | 1000 | 49×1001 input cycles | 1.021854… |
Derive the waveform before calling it an average voltage
With CNT<250 active, counts 0…249 are high: 250 of 1000 ticks. Duty D=250/1000=0.25, so each nominal 1 ms period has 250 µs high and 750 µs low. A hardware compare output creates those transitions without waiting for an interrupt handler.
For an explicitly ideal 0 V/3.3 V waveform, the instantaneous value is one of those two levels. Its period mean is D×3.3=0.825 V. It is not a constant 0.825 V source. Filtering, loading, ripple, output resistance and pin limits would need a separate physical design.
Root mean square (RMS) voltage, which relates to heating in a resistor, is 3.3√D=1.65 V. For a separate ideal 1 kΩ load model, average power is D×3.3²/1000=0.0027225 W=2.7225 mW. Using the mean voltage squared would incorrectly give 0.680625 mW. This calculation is not approval to drive an arbitrary load from a GPIO.
The chart separates an ideal PWM trace from a later software-response window. Its waveform and latency band are declared model data, not a measured pin trace or firmware simulation.
Separate the event from the polling or interrupt endpoint
A hardware update can set a status flag and request an interrupt. The processor responds later. In a declared example, suppose the chosen software action follows each update by 3–8 µs, including the path to that action, with no missed service or other delay. That action window is an assumption to test in an implementation, not a universal MCU specification.
For an update at 1000 µs, the assumed action lies between 1003 and 1008 µs. Latency spans 5 µs. Consecutive action intervals equal 1000 µs plus the difference between successive latencies, so they can range from 995 to 1005 µs under this bound. Distinguish the 5 µs latency range from the 10 µs full range of possible action intervals.
Polling the event every 200 µs instead adds up to one polling interval of waiting under the stated regular-poll assumption, plus detection/processing time. A stalled or irregular polling task has no such 200 µs bound. Hardware PWM compare transitions do not wait for either method, though real pin delays and clock errors still exist.
A MicroPython timer callback is another software endpoint, with its documented runtime scheduling behaviour. It must not be treated as the same edge guarantee as the declared hardware PWM output. Use the exact runtime/peripheral documentation for the implementation you choose.
A pending flag is not a queue of all updates
A single sticky update flag remembers that at least one event occurred while it was pending. If two or more updates occur before software services and clears it, one bit cannot tell how many happened. Counting handler calls is not automatically counting every hardware update.
To construct a nominal 100 ms interval from 100 updates, start from a known phase/reference event and count 100 subsequent 1 ms intervals without losses or extra initialization events. A suitable hardware counting/capture arrangement is another option. Merely seeing a flag 100 times does not establish that exactly 100 updates elapsed.
For an illustrative absolute-clock budget, suppose the actual 48 MHz timer input is within ±100 parts per million (ppm) of nominal. Over a nominal 100 ms interval that is approximately ±10 µs of clock error before software latency. The exact interval scales inversely with frequency: 100 ms/(1+100×10⁻⁶) to 100 ms/(1−100×10⁻⁶), about 99.990001 to 100.010001 ms.
That clock bound is supplied, not a measured board specification. Clock tolerance, scheduling latency, missed events and initialization phase are different contributions. Record them separately instead of assigning every discrepancy to “jitter.”
Define when the first valid period begins
Prescaler, reload and compare values may be buffered. A software update used to transfer those values can also set event/status flags, depending on the selected timer and configuration. Initialization can therefore create an event that should not be confused with one completed periodic interval.
A device-specific implementation must establish the intended clock/mode and output defaults, load the chosen values through the documented update/preload mechanism, handle its flags and pending interrupt state correctly, and enable the output/interrupt/counter in the documented order. Define the reference for the first accepted period.
This lesson supplies the count/latency contract and a checklist, rather than invented register writes for an unnamed part. The exact reference manual, errata and measured implementation evidence remain necessary before claiming the physical configuration works.
Use a wraparound calculation only within its stated interval
For a separate free-running 16-bit mode, set ARR=65535 and keep the 1 MHz counter rate. This is not the ARR=999 PWM mode. Suppose a first reading is 65530 and a later reading is 20. If strictly less than one full wrap period elapsed, modular subtraction gives (20−65530) mod 65536=26 ticks, or 26 µs.
The counter passes through 65531…65535, wraps to 0, then reaches 20. Simple signed subtraction without the modulo would give −65510, which does not represent the declared short elapsed interval. More than one possible wrap makes the two readings alone ambiguous.
A software time API can have different rules. MicroPython ticks_diff uses its documented wrap-safe domain and requires the separation to be less than half the tick period. Do not assume its counter width or replace that contract with the separate 16-bit one-wrap hardware exercise.
| Example | Modulus/period contract | Allowed elapsed interval | Result here |
|---|---|---|---|
| Declared free counter | 65536 ticks at 1 MHz; ARR 65535 | Less than one full wrap | 65530→20 gives 26 µs |
| MicroPython ticks_diff | Runtime-specific tick period | Less than half that period | Use the documented API and valid inputs |
Choose the next observation from the discrepancy
If a supplied output period is 1.001 ms, first compare it with the ARR=1000 count prediction. That is a candidate explanation under this exact clock/mode, not a unique diagnosis of an arbitrary board. A second observation of actual settings and clock separates a reload mistake from a changed clock.
If hardware period is correct but software actions vary within the declared 3–8 µs window, the two endpoints describe different paths. Check action timestamps and service conditions before changing the PWM divider.
If the task waiting for 100 subsequent counted update events fires later than its intended 100 ms reference, lost or collapsed updates are a candidate: software needs more real periods to accumulate its count. If it fires early by a period, an extra initialization event counted as a completed interval is a candidate. These are hypotheses under the declared count contract; clock, mode and service evidence are still required. A count that under-reports a fixed external elapsed interval is a different observation and can also indicate lost counts. For a two-reading elapsed calculation, check mode, wrap interval and timebase assumptions.
From 48 MHz to a bounded software schedule
For PSC 47 and ARR 999, divide 48 MHz by 48 to get a 1 MHz count. The inclusive 0…999 cycle takes 1000 µs and updates at 1000 Hz. CCR 250 in the stated PWM1 mode gives 25% active-high duty and 250 µs high.
Treat the hardware update and software action as different timestamps. An update at 1000 µs permits a software action at 1003…1008 µs under the supplied latency assumption. Consecutive action intervals can vary 995…1005 µs even when the update interval remains 1000 µs.
To schedule a nominal 100 ms task from 100 subsequent updates, first establish the phase and exclude initialization events, then guarantee/count all 100 intervals. Retain the supplied approximately ±10 µs clock budget separately from service latency and loss. Nothing in the paper arithmetic establishes that a real handler met those conditions.
Try the reasoning
Find counter rate, update period and update frequency for the declared 48 MHz, PSC 47, ARR 999 contract.
Show the answer and reasoning
PSC+1=48, so counter rate=1 MHz and each tick is 1 µs. ARR+1=1000 ticks gives 1 ms per update and 1000 updates/s. This uses the stated edge-aligned up-counter with no repetition division.
What duty and high time follow CCR 250 in the selected PWM1 mode?
Show the answer and reasoning
CNT 0…249 is active: 250 of 1000 ticks, so duty=25% and high time=250 µs per 1 ms period. The actual mode/polarity must match this contract.
What if ARR 1000 is used, and what if PSC 48 is also used?
Show the answer and reasoning
ARR 1000 gives 1001 ticks and 1.001 ms with PSC 47. If PSC 48 is also used, divide by 49: 49×1001/48 MHz≈1.021854 ms. These are setting/count changes, not automatically clock calibration errors.
For an update at 1000 µs and assumed action latency 3–8 µs, what action window and consecutive-action interval range follow?
Show the answer and reasoning
The action lies 1003…1008 µs after the time origin. Consecutive action intervals equal 1000 µs plus the latency difference, so the range is 995…1005 µs. Latency varies across 5 µs; possible intervals span 10 µs. All statements depend on the declared bound/no-loss assumptions.
Does polling every 200 µs or enabling an interrupt guarantee immediate action?
Show the answer and reasoning
No. Regular polling adds up to one poll interval of waiting plus processing; a stall breaks that bound. Interrupt response also has latency. Hardware PWM edges follow the compare mechanism independently of the handler, with their own physical timing conditions.
Can a sticky update flag establish that every update was counted?
Show the answer and reasoning
No. Multiple updates while the same bit is pending can collapse into one visible pending state. Counting 100 valid subsequent intervals requires a no-loss/phase contract or a suitable hardware counting scheme; handler count alone is insufficient.
Calculate the ideal mean, RMS and 1 kΩ heating power for 25% duty at 0/3.3 V.
Show the answer and reasoning
Mean=0.25×3.3=0.825 V; RMS=3.3√0.25=1.65 V; average resistor power=1.65²/1000=2.7225 mW. The instantaneous waveform is 0 or 3.3 V, not a constant mean-voltage source.
Find elapsed time for 65530→20 in the separate 1 MHz, ARR 65535 mode.
Show the answer and reasoning
If less than one full 65536-tick wrap elapsed, modular difference is 26 ticks=26 µs. Longer unknown separations are ambiguous from those two readings. This mode differs from ARR 999 PWM, and MicroPython ticks_diff has a separate half-period rule.
What is the approximate 100 ms error from the supplied ±100 ppm timer-clock bound, and what must happen during initialization?
Show the answer and reasoning
Approximately ±10 µs before software latency; exact times scale inversely with frequency. Initialization must follow the actual device preload/update/flag/pending-interrupt/output order and define the first valid period. A generated update flag is not automatically a completed periodic interval.
What to carry forward
Count the hardware intervals with the declared divider and mode, then identify the software response endpoint. PWM duty, mean voltage, event flags, elapsed counters and measured timing describe different things; each needs its own assumptions and checks.
References
Sources supporting this lesson’s explanations and examples.
- AN4013: Introduction to timers for STM32 MCUsSTMicroelectronicsTechnical documentation · PDF
MicroPython project, runtime maintainer2 sources