Welcome to ESP32 Core Board repository
4. TIMER_IT
TIMER_IT
TIMER_IT1. Timer Overview2. Core Concepts2.1 MicroPython Timer Types2.2 Timer Modes2.3 ISR Design Principle — Only Count, No Work2.4 Critical Section Protection — disable_irq / enable_irq2.5 time.ticks_ms() — Millisecond Timestamp2.6 Core API3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Details5.1 Imports and Global Variables5.2 Timer ISR — Minimal Callback5.3 Starting the Timer5.4 Main Loop — Cumulative Printing + Critical Section6. Operation Procedure6.1 Flashing and Running6.2 Normal Phenomenon6.3 Verification Methods7. Common Problems
1. Timer Overview
The timer is one of the most commonly used peripherals of an MCU — set a time interval, and the callback function is triggered automatically when the time is up. This experiment uses machine.Timer to configure a 10ms periodic timer. The ISR only records the timestamp and the trigger count (it does not toggle the LED or print). The main loop prints the elapsed running time via serial once every 100 triggers (≈1s).
Typical application scenarios:
| Application Type | Example |
|---|---|
| Periodic tasks | LED blinking, timed sensor sampling |
| Timeout judgment | Communication timeout, long-press button detection |
| PWM generation | Breathing light, motor speed control |
| Precise timing | Pulse measurement, frequency counting |
2. Core Concepts
2.1 MicroPython Timer Types
The ESP32-S3 has 4 hardware timers (Timer 0~3):
| Timer ID | Description |
|---|---|
Timer(0) | Hardware timer 0 |
Timer(1) | Hardware timer 1 |
Timer(2) | Hardware timer 2 |
Timer(3) | Hardware timer 3 |
Do not confuse these with FreeRTOS software timers —
machine.Timerdirectly uses the hardware timers.
2.2 Timer Modes
| Mode | Timer Constant | Description |
|---|---|---|
| One-shot | Timer.ONE_SHOT | Triggers once when the time expires, then stops |
| Periodic | Timer.PERIODIC | Repeats every period milliseconds |
2.3 ISR Design Principle — Only Count, No Work
This experiment demonstrates a core practice: the ISR only does the lightest operations — recording the timestamp and accumulating the count. Time-consuming operations such as printing and LED toggling are all placed in the main loop.
| ISR does | ISR does not do |
|---|---|
time.ticks_ms() reads the timestamp | print() |
isr_trigger_count += 1 accumulates an integer | LED toggle / GPIO operations |
| — | time.sleep() |
2.4 Critical Section Protection — disable_irq / enable_irq
When the ISR and the main loop share variables (isr_capture_time, isr_trigger_count), there is a race condition risk: the main loop is interrupted by the ISR halfway through a read, and the variable is modified, causing inconsistent data.
irq_state = disable_irq() # disable IRQs, save the current interrupt statetrigger = isr_trigger_count # atomic readnow = isr_capture_timeenable_irq(irq_state) # restore the interrupt stateReading/writing a 32-bit integer is atomic on the ESP32-S3, but not across two variables — disabling interrupts guarantees that this small section is "indivisible".
2.5 time.ticks_ms() — Millisecond Timestamp
xxxxxxxxxximport timet = time.ticks_ms() # returns milliseconds since startup (wraparound-safe)elapsed = time.ticks_diff(now, start) # safely compute the difference, handles wraparound automatically
ticks_diff()has built-in wraparound handling, so it still computes the difference correctly even whenticks_ms()wraps back to 0.
2.6 Core API
xfrom machine import Timer
tim = Timer(0) # use timer 0tim.init(period=10, mode=Timer.PERIODIC, callback=fn) # 10ms periodtim.deinit() # stop the timer| Parameter | Description |
|---|---|
period | Timer period, in milliseconds |
mode | Timer.PERIODIC or Timer.ONE_SHOT |
callback | Timer callback function, receives one argument tim (the timer object) |
3. Hardware Dependencies
This experiment is a pure system-function demonstration and does not involve GPIO peripherals. Serial printing is used to observe the timer timing.
4. Project Architecture and Flow
xxxxxxxxxxScript execution (single-file .py)│├─ isr_capture_time = 0 // timestamp captured by the ISR├─ isr_trigger_count = 0 // total number of ISR triggers├─ def timer_callback(tim): // timer ISR (triggers every 10ms)│ ├─ isr_capture_time = time.ticks_ms() // record the current timestamp│ └─ isr_trigger_count += 1 // increment trigger count├─ tim = Timer(0) // create the timer├─ tim.init(period=10, PERIODIC, callback) // start: 10ms period│└─ while True: // main loop├─ trigger = isr_trigger_count // read ISR trigger count├─ if trigger - last_print >= 100: // print every 100 times (≈1s)│ ├─ disable_irq() // critical section start│ ├─ trigger = isr_trigger_count; now = isr_capture_time // atomic read│ ├─ enable_irq(irq_state) // critical section end│ ├─ elapsed = ticks_diff(now, start) // compute elapsed time│ └─ print("elapsed:", elapsed, "ms") // serial output└─ last_print_trigger = trigger // update print threshold
5. Source Code Details
Full source code: 5.Source Code → MicroPython → 1.Basic Peripherals → 4.TIMER_IT → 4.TIMER_IT.py
5.1 Imports and Global Variables
xxxxxxxxxxfrom machine import Timer, disable_irq, enable_irq # Timer + IRQ controlimport time # ticks_ms / ticks_diff
isr_capture_time = 0 # timestamp captured by the ISR (ms)isr_trigger_count = 0 # total ISR trigger countdisable_irq and enable_irq are the key new APIs in this experiment — they are used to briefly disable interrupts when reading the ISR-shared variables.
5.2 Timer ISR — Minimal Callback
xxxxxxxxxxdef timer_callback(tim): # timer ISR callback global isr_capture_time, isr_trigger_count
isr_capture_time = time.ticks_ms() # capture trigger time isr_trigger_count += 1 # increment countThe ISR only uses two lines of variable assignment, taking < 1μs. It does not touch GPIO, print, or delay — this is the experiment goal of "don't make the ISR do work".
5.3 Starting the Timer
xxxxxxxxxxtim = Timer(0) # hardware timer 0tim.init(period=10, mode=Timer.PERIODIC, callback=timer_callback) # 10ms periodic
print("Timer started (period 10 ms)") # timer started5.4 Main Loop — Cumulative Printing + Critical Section
xxxxxxxxxxstart = time.ticks_ms() # record the start time (ms)last_print_trigger = 0 # trigger count at the last print
while True: trigger = isr_trigger_count # quick read (non-critical, only for threshold check)
if trigger - last_print_trigger >= 100: # every 100 triggers (~1s) # critical section: atomic read of trigger and capture_time irq_state = disable_irq() trigger = isr_trigger_count now = isr_capture_time enable_irq(irq_state)
elapsed = time.ticks_diff(now, start) # calculate elapsed time last_print_trigger = trigger
print("[%d] elapsed: %d ms" % (trigger, elapsed)) # printExecution timing:
xxxxxxxxxxISR (every 10ms): ─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─ ...└┴┴┴┴┴┴┴┴┴┴┴┴┴─ ...trigger_count accumulates: 1, 2, 3, ...Main loop:read trigger, find >= 100 → disable IRQ → read trigger+time → enable IRQ → printread trigger, find >= 200 → disable IRQ → read trigger+time → enable IRQ → print...
The
trigger = isr_trigger_countoutside the critical section is used to quickly determine "whether it should print now"; once the threshold is reached, the code enters the critical section for an accurate read. This "coarse check first, then precise read" pattern is very efficient in high-frequency ISR scenarios.
6. Operation Procedure
6.1 Flashing and Running
Thonny IDE steps: See the 1. Before Development → 3.Thonny IDE chapter.
6.2 Normal Phenomenon
The Thonny Shell prints one line per second:
xxxxxxxxxxTimer started (period 10 ms)[100] elapsed: 999 ms[200] elapsed: 1999 ms[300] elapsed: 2999 ms[400] elapsed: 3999 ms[500] elapsed: 4999 ms[600] elapsed: 5999 ms[700] elapsed: 6999 ms[800] elapsed: 7999 ms

Due to slight jitter in ISR execution and main-loop scheduling,
elapsedmay not be exactly a whole multiple of 1000ms; ±1ms is perfectly normal.
6.3 Verification Methods
| Operation | Expected Result |
|---|---|
| Power up | Shell prints one line per second |
Change period=10 to period=50 | Prints once every 5s (100 × 50ms) |
Change the threshold 100 to 50 | Prints twice per second (every 500ms) |
Remove disable_irq / enable_irq | Still works (atomic 32-bit read/write), but not logically rigorous |
Add print("ISR") in the ISR | 100 prints per second → Shell freezes |
7. Common Problems
| Symptom | Cause | Solution |
|---|---|---|
| Timer does not trigger | period is in milliseconds; wrote 10000 | Confirm the unit: 10ms = period=10 |
| Shell print interval is unstable | ISR and main loop run in time-sharing; the main loop is preempted by other tasks | Normal phenomenon; use ESP-IDF for high real-time requirements |
No error after removing disable_irq | 32-bit integer reads/writes are atomic on the ESP32-S3 | But not across two variables — keeping the critical section is correct |
elapsed jumps > 1s during printing | Main loop overloaded or GC reclaiming causes the if to be missed | Change the threshold 100 to 50 to reduce the single interval |
Timer.init() reports an error | The timer is already occupied | tim.deinit() before init, or use another Timer ID |