1. Today’s topic
We examine:
timer clock
prescaler and auto-reload
Input Capture
Output Compare
PWM
One-Pulse mode
counter overflow
hardware ADC triggering
timer synchronization
period and pulse-duration measurementThe central idea: when edge timing or pulse duration matters, a hardware timer should capture or generate the event. A FreeRTOS task should process an already recorded timestamp.
2. Why this matters
Traffic-light phases
Input Capture records the edge time in hardware:
input edge
→ CNT copied into CCR
→ ISR receives the saved timestamp
→ input_task analyzes intervalsCapture latches the counter independently of ISR-entry latency, provided a later capture has not overwritten it. Account for timer quantization, input synchronization/filtering, CCxOF overcapture flags and queue losses.
HDR illumination and sync
Poor approach:
gpio_set_level(IR_GPIO, 1);
vTaskDelay(pdMS_TO_TICKS(duration_ms));
gpio_set_level(IR_GPIO, 0);Correct approach:
camera sync edge
→ Input Capture / timer trigger
→ One-Pulse or Output Compare
→ hardware illumination pulseADC + DMA
TIM update/TRGO
→ ADC conversion
→ DMA bufferThis keeps the sample period uniform and independent of the scheduler.
3. Theory
Main registers
timer clock
↓
Prescaler PSC
↓
Counter CNT
├── comparison with ARR → update/overflow
└── comparison with CCRx → Output Compare/PWMFor ordinary upcounting with overflow updates and no additional repetition-counter division:
f_counter = f_timer / (PSC + 1)
T_tick = 1 / f_counter
f_update = f_timer / ((PSC + 1) × (ARR + 1))A 1 microsecond tick
If f_counter = 1 MHz, then 1 tick = 1 us. This is convenient for measuring 50/100 Hz periods and illumination pulses. But for a 16-bit timer:
65536 us ≈ 65.5 msBeyond that, overflow handling or a 32-bit timer is required.
Input Capture
At an edge:
CCRx = CNTFor the period between rising edges:
uint32_t delta_ticks = current_capture - previous_capture;With uint32_t values and a counter modulo 2^32, unsigned subtraction gives the interval only when the true elapsed ticks are less than 2^32. One complete revolution is indistinguishable from zero elapsed ticks. A 16-bit counter or different ARR needs its own modulus or a coherently extended overflow count.
Duty cycle
rising1 → falling → rising2
period = rising2 - rising1
high_time = falling - rising1
duty = high_time / periodWithout float:
static bool pulse_duty_permille(uint32_t high_ticks,
uint32_t period_ticks,
uint32_t *out)
{
if (out == NULL || period_ticks == 0 || high_ticks > period_ticks) {
return false;
}
*out = (uint32_t)(((uint64_t)high_ticks * 1000ULL) / period_ticks);
return true;
}Input filter
The timer’s digital filter helps against glitches, but adds delay and limits the maximum frequency. It complements circuit design rather than replacing it.
Output Compare
Output Compare generates a hardware event when:
CNT == CCRxCompare can change an output, raise an interrupt or request DMA. Schedule periodic compares from the previous deadline, but handle late servicing explicitly: a CCR already passed may not match until a full counter revolution. Define how missed deadlines are skipped or recovered.
PWM
frequency = f_counter / (ARR + 1)
duty ≈ CCR / (ARR + 1)PWM is generated in hardware without scheduler jitter.
One-Pulse mode
trigger
→ programmable delay
→ output active
→ programmable duration
→ output inactive
→ timer stopsSuitable for an IR flash, reset pulse, camera trigger, or strobe.
Preload
With preload enabled, staged CCR/ARR values become active at the configured update event. This avoids applying one value mid-cycle, but related changes must be staged before the same event. An update between two writes can activate an inconsistent pair for one cycle; use supported update control or DMA-burst under the timer reference manual.
4. Common mistakes
- Measuring an edge with a timestamp inside ISR rather than the Capture Register.
- Not checking the timer clock.
- Forgetting PSC + 1 and ARR + 1.
- Not accounting for overflow.
- Using software PWM through vTaskDelay().
- Switching capture polarity too slowly.
- Logging or doing heavy mathematics in a capture callback.
- Treating the digital filter as a substitute for circuit design.
- Changing CCR mid-PWM without preload.
- Scheduling compare from the current CNT and accumulating drift.
5. Practical assignment
Generate PWM and measure it with hardware capture on a low-voltage board. Expected values below are calculated, not measured; check logic-level compatibility and the ground connection.
- Configure PWM:
frequency = 1 kHz
duty = 30 %- Connect PWM output → capture input.
- Configure the capture timer:
counter frequency ≈ 1 MHz
time step ≈ 1 us
capture rising and falling edges- Expected values:
period ≈ 1000 us
high time ≈ 300 us
duty ≈ 30 %
frequency ≈ 1000 Hz- The ISR passes only:
typedef struct {
uint32_t capture;
uint8_t edge;
} timer_capture_event_t;The task calculates period/duty/frequency.
- Add a capture CLI:
capture:
counter_hz=1000000
time_step_us=1
edges=120340
measurements=60170
period=999..1001 us
frequency=1000000 mHz
duty=300 permille
invalid=0
timeouts=06. What to try next
- Add a missing-signal timeout.
- Test 100 Hz, 1 kHz, 10 kHz, and different duty values.
- Inject a glitch and inspect the counter.
- Create HIL: Raspberry Pi/a second MCU generates the signal, ESP32/STM32 measures it.
- Extract the calculation into pulse_meter_core and cover it with host unit tests.
Final checklist for lessons 21-30
Reliability
□ Faults have a source, class, action and counter. □ Degraded operation is visible. □ Recoverable faults do not cause unconditional reset. □ Fatal faults do not wait for ordinary retries. □ Retain diagnostic history proactively; do not assume a last-moment snapshot is always possible.
Configuration and OTA
□ Config has magic/version/size/CRC/generation. □ Defaults and validation exist. □ Old versions can be migrated. □ A/B config exists. □ OTA is confirmed only after self-test. □ LTE/MQTT unavailability does not automatically roll back healthy firmware.
CI/HIL
□ Builds use pinned container and toolchain versions. □ ELF, MAP, sdkconfig, manifest and SHA-256 are retained. □ OTA slot size is checked. □ Firmware signing is separate from pull-request validation. □ HIL tests normal operation, power cuts, rollback, watchdogs and fault handling.
Testability
□ Core modules do not depend on ESP-IDF/STM32 HAL. □ Time is passed as an argument. □ Infinite tasks use a testable step() function. □ The AT parser is tested for fragmentation invariance. □ Fuzzing crashes become regression tests.
RTOS and interrupts
□ A peripheral has a single owner task. □ ISR does not wait for a mutex. □ ISR calls only ...FromISR() API. □ NVIC priorities agree with configMAX_SYSCALL_INTERRUPT_PRIORITY. □ ESP32 interrupts have deliberate core affinity. □ Long processing moves from ISR into a task.
DMA, buffers, and timers
□ A continuous stream has an owner, overrun detection, and CLI stats. □ DMA buffers have explicit ownership. □ STM32H7/F7 cache clean/invalidate are accounted for. □ Timer clock is checked against the clock tree. □ Precise edges are measured through Input Capture. □ PWM/One-Pulse are generated in hardware, not through vTaskDelay().
Exercise
Explain why an ISR-entry timestamp is not equivalent to an Input Capture register value. Describe a test that exposes the difference under interrupt load.
Self-check criteria: Separate edge time from handling time and use a known signal/reference; do not claim accuracy from scheduler timing alone.
Show the supplied answer
The capture register latches the hardware edge time, while an ISR timestamp includes interrupt latency. Apply a known signal and additional interrupt load, compare recorded capture intervals with ISR-entry timing, and inspect variation without heavy logging inside ISR.
Exercise
For 1 kHz PWM with a 30% duty cycle, calculate the period and HIGH time. How does preload help, and what is required to update several related registers coherently?
Self-check criteria: Obtain 1000 µs and 300 µs, and explain the shared activation boundary. These are expected calculations, not hardware measurements.
Show the supplied answer
The expected period is about 1000 µs and the HIGH time about 300 µs. Preload defers activation until the update event. Stage all related CCR/ARR values before the same boundary; otherwise one cycle can use an inconsistent pair. Inspect the output around the change, not merely whether it toggles.