Skip to main content

Section 3.7 Timers and timing

There are several ways to keep track of time in MicroPython (and on microcontrollers more generally).

Subsection 3.7.1 Sleep / delay

The simplest way to wait for a bit of time is to use the time.sleep() method.

This works well for simple tasks, but it has a serious problem when you're trying to implement a state machine: when you call sleep(), the processor can't do anything else. If a button is pressed or a communication arrives or something else happens that the processor should respond to, it can't --- at least until the sleep duration is over.

Subsection 3.7.2 Reading the current time

A better way to implement the countdown is to keep track of how much time is left using the built-in clock.

However, you might also want to print an informative message every second. Since the main loop runs much faster than this (in order to catch and respond to other events quickly) we have to use the timer to tell when enough time has passed before printing the message.

Subsection 3.7.3 More precise timing

Although the code above works on MicroPython, time.time() may only return a time with a precision of 1 second. To get more precise timing, you can use the MicroPython utime module and the ticks_ms() function, which returns a time value in milliseconds.

import utime
now = utime.ticks_ms()
stopTime = now + 10 * 1000 # Time is measured in milliseconds now

# Code as before