yahboom
HomeTutorialsProduct
Solution
Blog
Online Store
About Us
EN/中文
Store
ESP32 Core Board📖
1. ESP32 Introduction
  • 1. ESP32S3 Overview
  • 2. Environment Setup Introduction
  • 3. Dev Board Introduction
2. ESP-IDF Development Tutorial
1. Before Development
  • 1. Environment Setup (Windows)
  • 2. Environment Setup (Linux)
  • 3. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. DMA
  • 8. ADC
  • 9. PWM Breathing LED
  • 10. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. PSRAM External Memory Experiment
  • 5. Flash Read and Write Experiment
  • 6. USB Emulated Mass Storage Experiment
4. FreeRTOS operating system
  • 1.FreeRTOS Core Concepts Theory
  • 2.Task Creation and Management
  • 3.Queue
  • 4.Binary Semaphore
  • 5.Mutex
  • 6.Event Groups
  • 7.Software Timer
  • 8.Task Scheduler
  • 9.Low Power Mode
  • 10.Deadlock
  • 11.Priority Inversion
5. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. Socket Programming Basics
  • 9. HTTP Client Experiment
  • 10. HTTP Server Experiment
  • 11. MQTT IoT Communication Protocol
  • 12. WIFI OTA Upgrade
  • 13. Bluetooth Fundamentals
  • 14. Bluetooth Slave Mode
  • 15. Bluetooth Master Mode
6. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
7. Xiaozhi AI Voice
  • 1. Burn Xiaozhi Firmware
  • 2. Network and Configuration
  • 3. AI Agent Settings
  • 4. Program Analysis
  • 5. Free Chat
3. Arduino Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. ESP_TIMER
  • 5. GPTIMER
  • 6. Watchdog Timer
  • 7. ADC
  • 8. PWM Breathing LED
  • 9. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication
  • 2. I2C OLED Display
  • 3. SPI Bus Communication
  • 4. Flash Read and Write
  • 5. USB Emulated Mass Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Server Experiment
  • 5. UDP Client Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT IoT Communication Protocol
  • 11. WIFI OTA Upgrade
  • 12. Bluetooth Fundamentals
  • 13. Bluetooth Slave Mode
  • 14. Bluetooth Master Mode
5. Audio Applications
  • 1.I2S Microphone Recording and U-Disk Playback
  • 2.I2S Audio Playback Experiment
  • 3.Repeater Experiment
4. MicroPython Development Course
1. Before Development
  • 1. Environment Setup
  • 2. Build and Flash
  • 3. Thonny IDE
2. Basic Peripherals
  • 1. LED Control
  • 2. Button Detection
  • 3. Peripheral Interrupts
  • 4. TIMER_IT
  • 5. Watchdog Timer
  • 6. ADC
  • 7. PWM Breathing LED
  • 8. RGB LED Effects
3. Serial Communication and Storage System
  • 1. Serial UART Communication Experiment
  • 2. I2C_OLED Display Experiment
  • 3. SPI Bus Communication Experiment
  • 4. Flash Read and Write Experiment
  • 5. Print Storage
4. Network Protocols and Wireless Communication
  • 1. WIFI Network Basics
  • 2. WIFI STA Mode
  • 3. WIFI AP Mode
  • 4. UDP Client Experiment
  • 5. UDP Server Experiment
  • 6. TCP Client Experiment
  • 7. TCP Server Experiment
  • 8. HTTP Client Experiment
  • 9. HTTP Server Experiment
  • 10. MQTT
  • 11. Bluetooth Fundamentals
  • 12. Bluetooth Slave Mode
  • 13. Bluetooth Master Mode
5. Audio Applications
  • 1. I2S Audio Playback Experiment
  • 2. Repeater Experiment
Download
  • Code
  • Hardware_Info
  • 3D_Model_File
  • Software_Tools
  • VMware
  • VM_File
Download ZIP

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 TypeExample
Periodic tasksLED blinking, timed sensor sampling
Timeout judgmentCommunication timeout, long-press button detection
PWM generationBreathing light, motor speed control
Precise timingPulse measurement, frequency counting

2. Core Concepts

2.1 MicroPython Timer Types

The ESP32-S3 has 4 hardware timers (Timer 0~3):

Timer IDDescription
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.Timer directly uses the hardware timers.

2.2 Timer Modes

ModeTimer ConstantDescription
One-shotTimer.ONE_SHOTTriggers once when the time expires, then stops
PeriodicTimer.PERIODICRepeats 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 doesISR does not do
time.ticks_ms() reads the timestampprint()
isr_trigger_count += 1 accumulates an integerLED 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 state
trigger   = isr_trigger_count # atomic read
now       = isr_capture_time
enable_irq(irq_state)         # restore the interrupt state

Reading/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

xxxxxxxxxx
import time
t = 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 when ticks_ms() wraps back to 0.

2.6 Core API

​x
from machine import Timer

tim = Timer(0)                                         # use timer 0
tim.init(period=10, mode=Timer.PERIODIC, callback=fn)  # 10ms period
tim.deinit()                                           # stop the timer
ParameterDescription
periodTimer period, in milliseconds
modeTimer.PERIODIC or Timer.ONE_SHOT
callbackTimer 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

xxxxxxxxxx
Script 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

xxxxxxxxxx
from machine import Timer, disable_irq, enable_irq  # Timer + IRQ control
import time            # ticks_ms / ticks_diff

isr_capture_time  = 0  # timestamp captured by the ISR (ms)
isr_trigger_count = 0  # total ISR trigger count

disable_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

xxxxxxxxxx
def 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 count

The 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

xxxxxxxxxx
tim = Timer(0)                                               # hardware timer 0
tim.init(period=10, mode=Timer.PERIODIC, callback=timer_callback)  # 10ms periodic

print("Timer started (period 10 ms)")  # timer started

5.4 Main Loop — Cumulative Printing + Critical Section

xxxxxxxxxx
start = 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))  # print

Execution timing:

xxxxxxxxxx
ISR (every 10ms):  ─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─ ...
                └┴┴┴┴┴┴┴┴┴┴┴┴┴─ ...
                  trigger_count accumulates: 1, 2, 3, ...
Main loop:
  read trigger, find >= 100 → disable IRQ → read trigger+time → enable IRQ → print
  read trigger, find >= 200 → disable IRQ → read trigger+time → enable IRQ → print
  ...

The trigger = isr_trigger_count outside 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:

xxxxxxxxxx
Timer 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

Serial port output

Due to slight jitter in ISR execution and main-loop scheduling, elapsed may not be exactly a whole multiple of 1000ms; ±1ms is perfectly normal.

6.3 Verification Methods

OperationExpected Result
Power upShell prints one line per second
Change period=10 to period=50Prints once every 5s (100 × 50ms)
Change the threshold 100 to 50Prints twice per second (every 500ms)
Remove disable_irq / enable_irqStill works (atomic 32-bit read/write), but not logically rigorous
Add print("ISR") in the ISR100 prints per second → Shell freezes

7. Common Problems

SymptomCauseSolution
Timer does not triggerperiod is in milliseconds; wrote 10000Confirm the unit: 10ms = period=10
Shell print interval is unstableISR and main loop run in time-sharing; the main loop is preempted by other tasksNormal phenomenon; use ESP-IDF for high real-time requirements
No error after removing disable_irq32-bit integer reads/writes are atomic on the ESP32-S3But not across two variables — keeping the critical section is correct
elapsed jumps > 1s during printingMain loop overloaded or GC reclaiming causes the if to be missedChange the threshold 100 to 50 to reduce the single interval
Timer.init() reports an errorThe timer is already occupiedtim.deinit() before init, or use another Timer ID
Peripheral Interrupts
Watchdog Timer

COMPANY

  • About us
  • Team Style
  • Blog

LEARNING & EXPLORATION

  • Tutorials
  • Edge AI hardware
  • Educational robots
  • Embedded intelligent hardware

WHERE TO BUY

  • Yahboom Online Store
  • Amazon
  • Alibaba
  • AliExpress
  • Mercado

TECHNOLOGY SUPPORT

  • Email: support@yahboom.com

BE A DISTRIBUTOR

  • Email: sales@yahboom.com
QR Code

Copyright © 2017-2026 Yahboom. All Rights Reserved.

EN/中文