boutons.py

micro:bit V2 (BBC micro:bit v2) · File : boutons.py · Language : MicroPython · Use case : Réagir aux boutons A et B (appui court, long, inclinaison)

The script uses the two A/B buttons: was_pressed for short presses, is_pressed with running_time for long presses, and both together. Built-in images (HAPPY, SAD, HEART) display with no manual drawing.

Required hardware

A BBC micro:bit V2 (nRF52833, 5×5 LED matrix, A/B buttons, accelerometer + compass, microphone and speaker) powered over USB or a battery pack. No part: A/B buttons are built under the board.

Wiring

No wiring. On a case, find the button side: A top left, B top right.

How it works

was_pressed() returns true once per press (internal flag); is_pressed() tests the instant state; running_time() counts milliseconds since boot to detect the long press.

Running it

Open python.microbit.org, paste the MicroPython program and send it to the board (the micro:bit shows up as a MICROBIT drive). Press reset to restart.

Variants

Use accelerometer.is_gesture(SHAKE) as a third button with no part, or count presses with button_a.get_presses().

boutons.py

# Boutons A et B : appui court, appui long, combinaison des deux.
from microbit import *

display.show(Image.HAPPY)

while True:
    if button_a.was_pressed():
        display.show(Image.HAPPY)
        print('A presse')
    if button_b.was_pressed():
        display.show(Image.SAD)
        print('B presse')

    # Appui long (maintenu plus de 500 ms) sur A : coeur.
    if button_a.is_pressed():
        t0 = running_time()
        while button_a.is_pressed():
            if running_time() - t0 > 500:
                display.show(Image.HEART)
                sleep(300)
                break

    # Les deux boutons : affichage du compteur de boussole.
    if button_a.is_pressed() and button_b.is_pressed():
        display.scroll(str(accelerometer.get_steps()))
        button_a.wait_until_released()
    sleep(10)

← Back to the board