5. machine module

MicroPython contains a machine module with specific functions related to the microbit.
Some useful methods from the machine module are below.

5.1. time_pulse_us

time_pulse_us is used by distance sensors.
machine.time_pulse_us(pin, pulse_level, timeout_us=1000000)

Return the duration of a pulse, in microseconds, on the given pin.

Parameters:
  • pin – The pin to measure the pulse on. This should be a pin object, e.g. pin14.

  • pulse_level – The pulse level to measure (0 or 1). 0 to time a low pulse or 1 to time a high pulse.

  • timeout_us – The timeout in microseconds. Default is 1,000,000 microseconds (1 second).

Returns:

The duration of the pulse in microseconds, or -1 if the timeout was reached.

e.g. pulse_time = machine.time_pulse_us(pin14, 1, 1160000) measures the time for the pulse to be reflected back.
  1. If the current input value of the pin is different to pulse_level, the function first waits until the pin input becomes equal to pulse_level. The function will return -2 if there was timeout waiting for this condition.

  2. It then times the duration that the pin is equal to pulse_level. If the pin is already equal to pulse_level then timing starts straight away. The function will return -1 if there was timeout waiting for this condition.

  3. The timeout is the same for both cases and given by timeout_us in microseconds.

Button A is connected to pin5, which reads 0 while the button is held. The code shows how long button A was held, in milliseconds. No extra hardware is needed.
from microbit import *
import machine

display.scroll("Hold A", delay=80)
while True:
    # Wait up to 5 seconds for a press, then time how long pin5 stays at 0
    duration = machine.time_pulse_us(pin5, 0, 5000000)
    if duration > 0:
        display.scroll(duration // 1000, delay=80)
    sleep(200)

5.2. reset

machine.reset()

Resets the microbit like pushing the external reset button and starts the program from the beginning.

The count starts again from 0 when button A is pressed.
from microbit import *
import machine

count = 0
while True:
    display.show(count % 10)
    count += 1
    if button_a.is_pressed():
        machine.reset()
    sleep(500)