class Timer – control hardware timers — MicroPython latest documentation (original) (raw)

MicroPython

This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions.

If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

Hardware timers deal with timing of periods and events. Timers are perhaps the most flexible and heterogeneous kind of hardware in MCUs and SoCs, differently greatly from a model to a model. MicroPython’s Timer class defines a baseline operation of executing a callback with a given period (or once after some delay), and allow specific boards to define more non-standard behaviour (which thus won’t be portable to other boards).

See discussion of important constraints on Timer callbacks.

Note

Memory can’t be allocated inside irq handlers (an interrupt) and so exceptions raised within a handler don’t give much information. Seemicropython.alloc_emergency_exception_buf() for how to get around this limitation.

If you are using a WiPy board please refer to machine.TimerWiPyinstead of this class.

Constructors

class machine.Timer(id, /, ...)

Construct a new timer object of the given id. id of -1 constructs a virtual timer (if supported by a board).id shall not be passed as a keyword argument.

See init for parameters of initialisation.

Methods

Timer.init(*, mode=Timer.PERIODIC, freq=-1, period=-1, callback=None)

Initialise the timer. Example:

def mycallback(t): pass

periodic at 1kHz

tim.init(mode=Timer.PERIODIC, freq=1000, callback=mycallback)

periodic with 100ms period

tim.init(period=100, callback=mycallback)

one shot firing after 1000ms

tim.init(mode=Timer.ONE_SHOT, period=1000, callback=mycallback)

Keyword arguments:

Timer.deinit()

Deinitialises the timer. Stops the timer, and disables the timer peripheral.

Constants

Timer.ONE_SHOT

Timer.PERIODIC

Timer operating mode.