Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,9 @@ Please report problems at https://github.com/kovirlabs/nu/issues.
your `microbit` folder, to copy them either way or delete them. **REPL**
and **Plotter** work as in CircuitPython
mode, and autocomplete knows micro:bit MicroPython 2.x (sound, microphone,
logo, `log`, `power`, radio, music…). Until it has been tried on real
logo, `log`, `power`, radio, music…). The first time, Nu puts six starter
programs (a dice, a heartbeat, a score keeper…) in `microbit/examples` to
open and flash. Until it has been tried on real
micro:bits it isn't in the installers: run Nu from source with
`uv sync --extra microbit`. See
[The BBC micro:bit](https://kovirlabs.github.io/nu/microbit/).
Expand Down
7 changes: 7 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,13 @@ the maintainer's checklist is in `plugins/microbit/README.md`)
MicroPython 2.x (microphone, speaker, `Sound`, `audio.SoundEffect`, `log`, `power`,
`pin_logo`, `run_every`, radio, music, neopixel, speech…), checked against the v2-docs and
`micropython-microbit-stubs`; V2-only entries say "(micro:bit V2)".
- [x] **Starter programs** (2026-11, `feature/microbit-examples`): six examples
(`nu_microbit/examples/`: hello, buttons, heartbeat, dice, tilt_plot for the Plotter,
score_keeper writing a file for the Files pane), V1 + V2, copied into
`<workspace>/microbit/examples` by `ensure_workspace_assets` the first time (an existing
folder is left alone). A test checks each only uses names `from microbit import *` gives.
The firmware pins were re-checked (2026-11-14): V2 2.1.2 and V1 1.1.1 are still the newest
releases.

**6c. Packaging + distribution:**
- [ ] **After the maintainer's hardware pass**: promote to a default-enabled bundled plugin —
Expand Down
17 changes: 17 additions & 0 deletions docs/microbit.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,23 @@ one with a microphone, a speaker and a touch-sensitive logo).

4. Click **Flash**. After a few seconds the micro:bit runs your program.

The first time you use micro:bit mode, Nu puts some starter programs in an
`examples` folder in your `microbit` folder. Click **Load** to open one, then
**Flash** it and change it. Each one says at the top what it does and what to
try:

| Program | What it does |
|---|---|
| `hello.py` | Scrolls a message, then shows a smiley face. |
| `buttons.py` | Shows a different face for button A, button B and both. |
| `heartbeat.py` | A heart that beats forever. |
| `dice.py` | Shake the micro:bit to roll a dice. |
| `tilt_plot.py` | Prints how the micro:bit is tilted, for the **Plotter**. |
| `score_keeper.py` | Keeps a score with the buttons, saved in a file on the micro:bit (see it with **Files**). |

They work on both the V1 and the V2. Nu doesn't copy them again, so your
changes stay, and if you delete the folder it stays deleted.

As you type, Nu suggests what comes next: type `display.` and it lists what
the display can do. The suggestions cover the V2's extras too (sound, the
microphone, the logo, data logging); their descriptions end with
Expand Down
2 changes: 1 addition & 1 deletion plugins/microbit/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ below has passed on real boards.
| `files.py` | The Files pane's jobs: list, copy each way, delete, through mpremote. GUI-free; all I/O injected. |
| `files_pane.py` | The Files pane widget: the board's files and the learner's `microbit` folder, side by side. |
| `worker.py` | Runs a flash or files job on a `QThread`, reporting back through signals. |
| `mode.py` | `MicrobitMode`: buttons, board detection, wiring. |
| `mode.py` | `MicrobitMode`: buttons, board detection, wiring; copies `examples/` (starter programs, V1 and V2) into the learner's `microbit/examples` folder the first time. |
| `api/` | Autocomplete stubs for micro:bit MicroPython 2.x (and 1.x). |

```
Expand Down
20 changes: 20 additions & 0 deletions plugins/microbit/nu_microbit/examples/buttons.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Buttons
#
# Press button A for a happy face, button B for a sad one, and both together
# for a surprise. The program checks the buttons over and over, forever.
#
# Try: show a different image for each button, or count the presses with
# button_a.get_presses() and scroll the number.

from microbit import *

while True:
if button_a.is_pressed() and button_b.is_pressed():
display.show(Image.SURPRISED)
elif button_a.is_pressed():
display.show(Image.HAPPY)
elif button_b.is_pressed():
display.show(Image.SAD)
else:
display.clear()
sleep(100)
14 changes: 14 additions & 0 deletions plugins/microbit/nu_microbit/examples/dice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Dice
#
# Shake the micro:bit to roll a dice: it shows a number from 1 to 6.
#
# Try: roll two dice and show their total, or make a coin (heads or tails).

from microbit import *
import random

display.show("?")
while True:
if accelerometer.was_gesture("shake"):
display.show(random.randint(1, 6))
sleep(50)
14 changes: 14 additions & 0 deletions plugins/microbit/nu_microbit/examples/heartbeat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Heartbeat
#
# A heart that beats forever: a big heart, then a small one, again and again.
#
# Try: make it beat faster by changing the numbers in sleep() (they're in
# milliseconds: 1000 is one second).

from microbit import *

while True:
display.show(Image.HEART)
sleep(500)
display.show(Image.HEART_SMALL)
sleep(500)
11 changes: 11 additions & 0 deletions plugins/microbit/nu_microbit/examples/hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Hello, micro:bit!
#
# Click Flash to put this program on your micro:bit. It scrolls a message
# across the lights, then shows a smiley face.
#
# Try: change the message, or show Image.HEART instead of Image.HAPPY.

from microbit import *

display.scroll("Hello!")
display.show(Image.HAPPY)
39 changes: 39 additions & 0 deletions plugins/microbit/nu_microbit/examples/score_keeper.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Score keeper
#
# Count points with the buttons: A adds one, B takes one away. The score is
# saved in a file on the micro:bit, called score.txt, every time it changes,
# so it's still there after you unplug the micro:bit.
#
# Click Files to see score.txt on the micro:bit, and copy it to your computer.
#
# Try: show a happy face when the score reaches 10.


from microbit import *


def load_score():
try:
with open("score.txt") as f:
return int(f.read())
except (OSError, ValueError):
return 0 # No file yet, or it doesn't hold a number.


def save_score(score):
with open("score.txt", "w") as f:
f.write(str(score))


score = load_score()
display.show(score)
while True:
if button_a.was_pressed():
score = score + 1
save_score(score)
display.show(score)
if button_b.was_pressed():
score = score - 1
save_score(score)
display.show(score)
sleep(50)
16 changes: 16 additions & 0 deletions plugins/microbit/nu_microbit/examples/tilt_plot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Tilt plotter
#
# Flash this, then click Plotter: tilt the micro:bit and watch the lines move.
# The micro:bit prints how much it's tilted left-right (x) and forwards-back
# (y), and Nu's plotter draws a graph of any numbers printed like this, in
# brackets with a comma.
#
# Try: add accelerometer.get_z() to see up-down too.

from microbit import *

while True:
x = accelerometer.get_x()
y = accelerometer.get_y()
print((x, y))
sleep(100)
24 changes: 24 additions & 0 deletions plugins/microbit/nu_microbit/mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import logging
import os
import shutil

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QGuiApplication
Expand All @@ -33,6 +34,10 @@

logger = logging.getLogger(__name__)

#: Starter programs, copied into the learner's micro:bit folder (see
#: MicrobitMode.ensure_workspace_assets).
EXAMPLES_DIR = os.path.join(os.path.dirname(__file__), "examples")

#: The toolbar's Flash button (and its icon, images/microbit-flash.svg).
FLASH_BUTTON = "microbit-flash"
#: The toolbar's Files button (and its icon, images/microbit-files.svg).
Expand Down Expand Up @@ -221,6 +226,25 @@ def compatible_board(self, port):
board.board_name(serial_number, port.description()),
)

def ensure_workspace_assets(self, workspace_dir):
"""
The first time: put some starter programs in an `examples` folder in
the learner's micro:bit folder (`<workspace>/microbit/examples`), to
open, flash and change. An existing `examples` folder is left alone,
so the learner's changes (or its deletion) stick.
"""
target = os.path.join(workspace_dir, "microbit", "examples")
if os.path.exists(target):
return
try:
shutil.copytree(
EXAMPLES_DIR, target, ignore=shutil.ignore_patterns("__pycache__")
)
except OSError:
logger.exception("Couldn't copy the micro:bit examples to %s", target)
return
logger.info("Copied the micro:bit examples to %s", target)

def activate(self):
self.active = True
super().activate()
Expand Down
59 changes: 59 additions & 0 deletions plugins/microbit/tests/test_microbit_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,65 @@ def test_plotter_without_a_device(mm):
assert "Could not find an attached device." in mm.view.show_message.call_args[0]


EXAMPLES = [
"buttons.py",
"dice.py",
"heartbeat.py",
"hello.py",
"score_keeper.py",
"tilt_plot.py",
]


def test_examples_copied_the_first_time(mm, tmp_path):
workspace = tmp_path / "mu_code"
mm.ensure_workspace_assets(str(workspace))
examples = workspace / "microbit" / "examples"
assert sorted(os.listdir(examples)) == EXAMPLES
assert "from microbit import *" in (examples / "hello.py").read_text()
# The learner's changes (and deletions) stay.
(examples / "hello.py").write_text("# mine")
(examples / "dice.py").unlink()
mm.ensure_workspace_assets(str(workspace))
assert (examples / "hello.py").read_text() == "# mine"
assert not (examples / "dice.py").exists()


def test_examples_cant_be_copied(mm, tmp_path, caplog):
with mock.patch("nu_microbit.mode.shutil.copytree", side_effect=OSError("full")):
mm.ensure_workspace_assets(str(tmp_path))
assert "Couldn't copy the micro:bit examples" in caplog.text


def test_examples_are_valid_micropython_for_the_microbit():
"""
Each example compiles, and every name it takes from `microbit` is one
the micro:bit has (Check's list of what `from microbit import *` brings).
"""
import ast
import builtins

known = set(MicrobitMode.star_imports["microbit"])
builtins_and_modules = set(dir(builtins)) | {"random", "f"}
for name in EXAMPLES:
path = os.path.join(mode_module.EXAMPLES_DIR, name)
with open(path, encoding="utf-8") as f:
source = f.read()
tree = ast.parse(source, name)
assigned = {
node.id
for node in ast.walk(tree)
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store)
} | {node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)}
used = {
node.id
for node in ast.walk(tree)
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)
}
unknown = used - known - assigned - builtins_and_modules
assert not unknown, (name, unknown)


def test_activate_and_deactivate(mm):
mm.activate()
assert mm.active is True
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,7 @@ builtins = ["_"]
extend-exclude = [
"mu/modes/api", # generated API stubs
"plugins/*/nu_*/api", # plugins' generated API stubs
"plugins/microbit/nu_microbit/examples", # MicroPython for the board
"docs",
]

Expand Down
Loading