Timer Usage Tutorial#
What is Timer?#
Timer is a hardware module used to execute tasks at fixed time intervals. Common uses include:
Periodically executing callback functions (such as timed printing, timed collection)
One-time delayed trigger events (such as startup delay)
Implementing software timers, clocks, task scheduling, and other functions
K230 Timer Features#
Feature |
Description |
|---|---|
Number of timers |
Built-in 6 hardware timers |
Time precision |
Minimum period is 1 microsecond |
Supported modes |
One-shot mode ( |
Supported types |
Hardware timer / Software timer (number -1) |
Callback mechanism |
Automatically calls the user-specified function on timeout |
Application Example: Timed Print Task#
The following example demonstrates how to use Timer to achieve:
One-time delayed execution
Periodic timed triggering
Resource release
Example Code#
from machine import Timer
import time
# ========= Create timer ========= #
tim = Timer(-1) # -1 indicates software timer
# ========= One-shot mode: trigger after 100ms ========= #
tim.init(period=100, mode=Timer.ONE_SHOT, callback=lambda t: print("单次触发:1"))
time.sleep(0.2) # Main program delays 200ms to ensure callback triggers
# ========= Periodic mode: trigger once per second ========= #
tim.init(freq=1, mode=Timer.PERIODIC, callback=lambda t: print("周期触发:2"))
time.sleep(2) # Main program waits 2 seconds to observe output
# ========= Release timer ========= #
tim.deinit()
Key Parameter Description#
Parameter |
Type |
Description |
|---|---|---|
|
Integer (ms) |
Timer period (in milliseconds), used for one-shot or periodic timing. The minimum |
|
Integer (Hz) |
Timer frequency (in Hertz), |
|
Constant |
|
|
Function |
Function automatically called when the timer triggers |
Mode Details#
One-Shot Mode Timer.ONE_SHOT#
tim.init(period=100, mode=Timer.ONE_SHOT, callback=func)
Timer triggers only once
Automatically stops when the time is up
Periodic Mode Timer.PERIODIC#
tim.init(freq=2, mode=Timer.PERIODIC, callback=func)
Triggers once every 0.5 seconds
Will continue running until manually stopped
Usage Notes#
Note |
Description |
|---|---|
Software Timer Number |
Software timers created with |
Callback Execution Timing |
The callback function runs in the system interrupt context; avoid blocking operations or |
No Re-initialization |
If a Timer is running, calling |
Resource Release |
Use |
Application Scenarios#
Real-time timing control: LED blinking, buzzer alarms
Periodic sampling: sensor data reading
Timeout control: task execution timeout handling
System heartbeat: periodically printing an “alive” flag
Tip
For detailed usage of the Timer module, please refer to the K230 Timer API Documentation
