Class Timer – Hardware Control Timer

Timer for hardware processing cycle and event time. Timers are probably the most flexible and heterogeneous hardware types in MCUs and SoCs, and vary greatly from one model to another. MicroPython’s Timer class defines a baseline operation that performs callbacks within a given time period (or executes a callback after a delay), and allows a specific board to define more non-standard behaviors (so it cannot be ported to other boards).

Reference for the timer callback 重要约束

Note

Memory cannot be allocated in the IRQ handler (interrupt), so exceptions raised in the handler will not provide much information. To understand how to resolve this limitation:func:micropython.alloc_emergency_exception_buf .

Construct object

class machine.Timer(id, ...)

Construct a new timer object with the given ID.

  • id - Any positive integer

Method

Timer.init(*, mode=Timer.PERIODIC, period=-1, callback=None)
  • mode - Timer mode, can be one of the following:

    • Timer.ONE_SHOT - The timer runs once until the time limit of the configured channel expires.
    • Timer.PERIODIC - The timer runs regularly at the channel’s configured frequency。
  • period - The period of the timer execution (in ms), executed once every period ms. Period range: 0 < period <= 3435973836

  • callback - Timer callback function

Initialize timer, example:

tim.init(period=100)                         # periodic with 100ms period
tim.init(mode=Timer.ONE_SHOT, period=1000)   # one shot firing after 1000ms
Timer.value()

Obtain and return the current count value of the timer.

value = tim.value()
print(value)
Timer.deinit()

Cancel the initialization of the timer. Stop the timer and disable timer peripherals.

Constant

Timer.ONE_SHOT
Timer.PERIODIC
Timer control LED blink
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# fork by http://www.1zlab.com/wiki/micropython-esp32/timer/

from machine import Timer, Pin
import utime


def toggle_led(led_pin):
    '''
    LED状态反转
    '''
    led_pin.value(not led_pin.value())


def led_blink_timed(timer, led_pin, freq=10):
    '''
    led 按照特定的频率进行闪烁
    LED闪烁周期 = 1000ms / 频率
    状态变换间隔(period) = LED闪烁周期/ 2 
    '''
    # 计算状态变换间隔时间 ms
    period = int(0.5 * 1000 / freq)
    # 初始化定时器
    # 这里回调是使用了lambada表达式,因为回调函数需要传入led_pin
    timer.init(period=period, mode=Timer.PERIODIC, callback=lambda t: toggle_led(led_pin))


# 声明引脚 D2 作为LED的引脚
led_pin = Pin(2, Pin.OUT)
timer = Timer(1)  # 创建定时器对象
led_blink_timed(timer, led_pin, freq=20)