class Timer – control hardware timers
Hardware timers handle the timing of periods and events. Timers are perhaps the most flexible and diverse hardware type in an MCU and SoC, with a wide range of different functions and limitations.
The Timer class provides the baseline operation of executing a callback at a given period (or after a delay), and allows specific boards to define more non-standard behavior (which therefore will not be portable to other boards).
For important constraints on Timer callbacks, see machine_callbacks.
Note
Memory cannot be allocated in interrupt handlers (interrupts), so exceptions raised in handlers do not provide much information.
See micropython.alloc_emergency_exception_buf() for how it helps 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- the timer mode, which can be one of the following:Timer.ONE_SHOT- the timer runs once until the configured channel period expires.Timer.PERIODIC- the timer runs periodically at the configured channel frequency.
period- the timer execution period (milliseconds); it executes once every period milliseconds. Period range: 0 < period <= 3435973836callback- the timer callback function
Initialize the timer, example:
tim.init(period=100) # Periodic timer with a period of 100ms
tim.init(mode=Timer.ONE_SHOT, period=1000) # One-shot timer that triggers once 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
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 LED state
10 '''
11 led_pin.value(not led_pin.value())
12
13
14def led_blink_timed(timer, led_pin, freq=10):
15 '''
16 LED blinks at a specific frequency
17 LED blink period = 1000ms / frequency
18 State toggle interval (period) = LED blink period / 2
19 '''
20 # Calculate state toggle interval in ms
21 period = int(0.5 * 1000 / freq)
22 # Initialize timer
23 # Lambda used here because callback needs led_pin parameter
24 timer.init(period=period, mode=Timer.PERIODIC, callback=lambda t: toggle_led(led_pin))
25
26
27# Declare pin D2 as LED pin
28led_pin = Pin(2, Pin.OUT)
29timer = Timer(1) # Create timer object
30led_blink_timed(timer, led_pin, freq=20)