8. utime

MicroPython contains an utime module based upon the time module in the Python standard library.
This module gets measure time intervals and create delays.

8.1. sleep

The standard microbit library has its own sleep method (in millisecs).
utime.sleep may be convenient for micro sleeps or sleeps in seconds.
utime.sleep(seconds)

Sleep for the given number of seconds. seconds is an int or float.

utime.sleep_ms(ms)

Delay for given number of milliseconds. milliseconds is a positive int or 0.

utime.sleep_us(us)

Delay for given number of microseconds. microseconds is a positive int or 0.

The code below has a sleep of 2 seconds between scrolling text.
from microbit import *
import utime

while True:
    display.scroll(".")
    utime.sleep(2)

8.2. ticks

utime.ticks_ms()

Returns an increasing millisecond counter with an arbitrary reference point, that wraps around after some value.

utime.ticks_us()

Returns an increasing microsecond counter with an arbitrary reference point, that wraps around after some value.

To find out wrap value use:
from microbit import *
import utime

# Find out TICKS_MAX used by this port
print(utime.ticks_add(0, -1))

8.3. ticks_add

utime.ticks_add(ticks, delta)

Offset ticks value by a given number, which can be either positive or negative. Given a ticks value, this function allows to calculate a ticks value, delta ticks before or after it.

Find out TICKS_MAX for the wrapping.
from microbit import *
import utime

# Find out TICKS_MAX
tick_max = utime.ticks_add(0, -1)
print(tick_max)
Use for a deadline:
from microbit import *
import utime

timer = 3000
deadline = utime.ticks_add(utime.ticks_ms(), timer)
while utime.ticks_diff(deadline, utime.ticks_ms()) > 0:
    utime.sleep_ms(200)
display.show(Image.SKULL)

8.4. ticks_diff

utime.ticks_diff(ticks1, ticks2)

Measure ticks difference between values returned from utime.ticks_ms() or ticks_us() functions, as a signed value which may wrap around.

The argument order is the same as for subtraction operator, ticks_diff(ticks1, ticks2) has the same meaning as ticks1 - ticks2.

The code below, checks for a change in the pin2 reading for up to 2 seconds, then displays a “TIMEDOUT” message.
from microbit import *
import utime

display.scroll(pin2.read_digital())
start = utime.ticks_ms()
while pin2.read_digital() == 0:
    if utime.ticks_diff(utime.ticks_ms(), start) > 2000:
        display.scroll("TIMEDOUT")