radio_ping.py

micro:bit V2 (BBC micro:bit v2) · File : radio_ping.py · Language : MicroPython · Use case : Communication radio sans fil entre deux micro:bit

The built-in 2.4 GHz radio exchanges without a router: one board sends a ping per second, the other answers pong, and each board shows received messages. The radio module handles group and channel addressing itself.

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. Two micro:bit V2 boards (or more); no network infrastructure.

Wiring

No wiring. Keep the boards more than 20 cm apart the first time to avoid near-field saturation.

How it works

radio.config(group, channel) sets the logical network; send() broadcasts, receive_bytes() reads without blocking (None when empty). The ping/pong pair proves the link both ways.

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

Send the temperature or step count instead of ping, or switch to radio.send_number() for a compact binary protocol.

radio_ping.py

# Radio 2.4 GHz : ping/pong entre deux micro:bit (canaux 1-100).
# A charger sur DEUX cartes ; la V2 inclut la radio BLE/802.15.
from microbit import *
import radio

radio.config(group=7, channel=40, power=6)
radio.on()

compteur = 0
while True:
    # Envoyer un ping chaque seconde.
    compteur += 1
    radio.send('ping %d' % compteur)
    display.show(Image.YES)

    # Ecouter la reponse pendant 1 s (non bloquant par morceaux).
    t0 = running_time()
    while running_time() - t0 < 1000:
        msg = radio.receive_bytes()
        if msg:
            display.scroll(msg.decode(), delay=60)
            break
        sleep(20)

    # Repondre a tout ping recu d'une autre carte.
    msg = radio.receive_bytes()
    if msg and msg.startswith(b'ping'):
        radio.send('pong %s' % msg[5:].decode())

# radio.on() active la pile ; send/receive utilisent le groupe.
# port=... permet plusieurs reseaux sur le meme canal.

← Back to the board