5. 硬件定时器

定时器可用于各种各样的任务,定期调用函数、计数事件和生成 PWM 信号是最常见的用例。每个定时器由两个 16 位通道组成,这些通道可以连接在一起形成一个 32 位定时器。每个定时器都需要配置操作模式,但随后可以在每个通道上独立配置周期(或频率)。通过使用回调方法,定时器事件可以调用 Python 函数。

以固定频率切换 LED 的示例用法:

from machine import Timer
from machine import Pin
led = Pin('GP16', mode=Pin.OUT)                  # enable GP16 as output to drive the LED
tim = Timer(3)                                   # create a timer object using timer 3
tim.init(mode=Timer.PERIODIC)                    # initialize it in periodic mode
tim_ch = tim.channel(Timer.A, freq=5)            # configure channel A at a frequency of 5Hz
tim_ch.irq(handler=lambda t:led.toggle(), trigger=Timer.TIMEOUT)        # toggle a LED on every cycle of the timer

使用命名函数进行回调的示例:

from machine import Timer
from machine import Pin
tim = Timer(1, mode=Timer.PERIODIC, width=32)
tim_a = tim.channel(Timer.A | Timer.B, freq=1)   # 1 Hz frequency requires a 32 bit timer

led = Pin('GP16', mode=Pin.OUT) # enable GP16 as output to drive the LED

def tick(timer):                # we will receive the timer object when being called
    global led
    led.toggle()                # toggle the LED

tim_a.irq(handler=tick, trigger=Timer.TIMEOUT)         # create the interrupt

进一步的例子:

from machine import Timer
tim1 = Timer(1, mode=Timer.ONE_SHOT)                               # initialize it in one shot mode
tim2 = Timer(2, mode=Timer.PWM)                                    # initialize it in PWM mode
tim1_ch = tim1.channel(Timer.A, freq=10, polarity=Timer.POSITIVE)  # start the event counter with a frequency of 10Hz and triggered by positive edges
tim2_ch = tim2.channel(Timer.B, freq=10000, duty_cycle=5000)       # start the PWM on channel B with a 50% duty cycle
tim2_ch.freq(20)                                                   # set the frequency (can also get)
tim2_ch.duty_cycle(3010)                                           # set the duty cycle to 30.1% (can also get)
tim2_ch.duty_cycle(3020, Timer.NEGATIVE)                           # set the duty cycle to 30.2% and change the polarity to negative
tim2_ch.period(2000000)                                            # change the period to 2 seconds

5.1. Timer 类的附加常量

Timer.PWM

PWM 定时器工作模式。

Timer.A
Timer.B

选择定时器通道。使用 32 位定时器时必须是 ORed (Timer.A | Timer.B)。

Timer.POSITIVE
Timer.NEGATIVE

定时器通道极性选择(仅在 PWM 模式下相关)。

Timer.TIMEOUT
Timer.MATCH

定时器通道 IRQ 触发。