class Timer – control hardware timers

Hardware timers handle timing of periods and events. Timers are perhaps the most flexible and heterogeneous type of hardware in MCUs and SoCs, varying greatly from one model to another. MicroPython’s Timer class defines the baseline operation of executing a callback at a given period (or once after a delay), and allows specific boards to define more non-standard behavior (hence not portable to other boards).

See important constraints regarding Timer callbacks.

Note

Memory cannot be allocated inside irq handlers (interrupts), so exceptions raised in handlers do not provide much information. See micropython.alloc_emergency_exception_buf() for how to address this limitation.

Constructors

class machine.Timer(id, ...)

Construct a new timer object with the given id.

  • id - Any positive integer

Methods

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

    • Timer.ONE_SHOT - The timer runs once until the configured period of the channel expires.

    • Timer.PERIODIC - The timer runs periodically at the configured frequency of the channel.

  • period - The period of the timer execution in milliseconds. Executes once every period ms. period value range: 0 < period <= 3435973836

  • callback - The callback function of the timer

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()

Get and return the current timer counter value.

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

Deinitialize the timer. Stop the timer and disable the timer peripheral.

Constants

Timer.ONE_SHOT
Timer.PERIODIC
Timer-controlled LED blinking
 1# fork by http://www.1zlab.com/wiki/micropython-esp32/timer/
 2
 3from machine import Timer, Pin
 4import utime
 5
 6
 7def toggle_led(led_pin):
 8    '''
 9    Toggle the LED state
10    '''
11    led_pin.value(not led_pin.value())
12
13
14def led_blink_timed(timer, led_pin, freq=10):
15    '''
16    The LED blinks at a specific frequency
17    LED blink period = 1000ms / frequency
18    State change interval (period) = LED blink period / 2 
19    '''
20    # Calculate the state change interval time in ms
21    period = int(0.5 * 1000 / freq)
22    # Initialize the timer
23    # Here the callback uses a lambda expression, because the callback function needs to pass in led_pin
24    timer.init(period=period, mode=Timer.PERIODIC, callback=lambda t: toggle_led(led_pin))
25
26
27# Declare pin D2 as the LED pin
28led_pin = Pin(2, Pin.OUT)
29timer = Timer(1)  # Create a timer object
30led_blink_timed(timer, led_pin, freq=20)