Skip to content

stm: support the uf2-stm32f bootloader's reset signatures - #11903

Merged
dhalbert merged 1 commit into
adafruit:mainfrom
vegardw:stm-uf2-bootloader
Nov 18, 2026
Merged

dhalbert merged 1 commit into
adafruit:mainfrom
vegardw:stm-uf2-bootloader

Conversation

@vegardw

@vegardw vegardw commented Nov 18, 2026

Copy link
Copy Markdown

Adds opt-in support for STM32 boards that boot through the
uf2-stm32f bootloader, as MakeCode Arcade consoles do.
No upstream board sets the new flag yet. The ELECFREAKS Retro Arcade (STM32F412RE) will, in its
board PR; its MCU support is #11896.

Problem

uf2-stm32f runs first after every reset and reads RTC->BKP0R (its main_f4.c and bl.c):

RTC->BKP0R The bootloader
0x71a21877 (boot signature) opens its UF2 drive and stays there
0x24a22d12 (app signature) starts the application at once
anything else opens its UF2 drive for a few seconds, then starts the application; once USB enumerates, it waits 24 hours instead

CircuitPython's resets leave RTC->BKP0R alone. So with USB connected, microcontroller.reset()
and the reset into safe mode stop in the UF2 drive until someone presses reset.
RunMode.BOOTLOADER arms ST's ROM DFU loader instead of the UF2 drive these boards use, and
RunMode.UF2 is ignored on STM.

Fix

A board flag, BOARD_UF2_STM32F_BOOTLOADER, off by default. With it set:

  • reset_cpu() writes the app signature just before NVIC_SystemReset(). That covers
    microcontroller.reset() and the reset into safe mode.
  • reset_to_bootloader() writes the boot signature instead of arming ST's ROM loader, and
    RunMode.UF2 is treated like RunMode.BOOTLOADER. That covers both run modes and the
    1200-baud touch.

The signature is written just before each reset because port_init() resets the backup domain
at startup, after the bootloader has read it. The bootloader's own resetIntoApp() and
resetIntoBootloader() use the same two values.

common_hal_mcu_reset() now calls reset_cpu() instead of NVIC_SystemReset() directly, so
microcontroller.reset() takes the same path. For boards without the flag, reset_cpu() is
just NVIC_SystemReset().

This is the UF2 side that #11270 left open ("#3444 UF2 preference still unimplemented"): on
boards with this bootloader, RunMode.BOOTLOADER now opens the UF2 drive instead of ST's ROM
loader.

Testing

On an ELECFREAKS Retro Arcade (STM32F412RE) with USB connected, using its board definition (not
yet upstream), on main 883e63fae6:

Check Without the flag This PR
microcontroller.reset() stays in the UF2 drive CircuitPython restarts
RunMode.UF2, then reset() ignored: an ordinary reset the UF2 drive opens; copying a UF2 to it flashes the board, and CircuitPython restarts
RunMode.BOOTLOADER, then reset() arms ST's ROM loader as for RunMode.UF2

The first row's "without the flag" result was observed with a test build that turns the flag
off: after microcontroller.reset() the board stayed in the UF2 drive for the 40 s watched. The
other two follow from the code. The script below checked the "This PR" column on macOS, and on
Linux in an earlier run on an older main. The reset into safe
mode takes the reset_cpu() path too; it came back in safe mode during an earlier fault, but the
script doesn't trigger it. Boards without the flag, one per STM family plus Meowbit ru (the
tightest image CI builds), all build on main 883e63fae6 and are 32 bytes smaller.

How to run the test

You need a board running uf2-stm32f with firmware that sets the flag, and pyserial
(sudo apt install python3-serial). Start with an empty code.py, so the board reaches the REPL
after each restart. Let the desktop mount the bootloader drive (or mount it when it appears),
then run the script with the CircuitPython UF2 to put back after each bootloader visit:

python3 bootloader_test.py /dev/ttyACM0 firmware.uf2

It finds the board again by its USB serial number after each reset, since Linux may give it a
new ttyACM number. Expect PASS for all three checks.

bootloader_test.py
#!/usr/bin/env python3
"""Check the reset paths of a board with the uf2-stm32f bootloader.

Usage: python3 bootloader_test.py PORT FIRMWARE.uf2
       (PORT is e.g. /dev/cu.usbmodem1301, /dev/ttyACM0 or COM5;
        FIRMWARE.uf2 is the CircuitPython build to put back afterwards)

1. microcontroller.reset() must come back as CircuitPython, not the bootloader.
2. and 3. RunMode.UF2 and RunMode.BOOTLOADER must each bring up the bootloader's
   drive. The script then copies FIRMWARE.uf2 to it, and CircuitPython must
   start again.

Needs pyserial (pip install pyserial). Runs on macOS, Linux and Windows.
"""

import argparse
import os
import platform
import shutil
import sys
import time
from pathlib import Path

import serial
import serial.tools.list_ports

PROMPT = b">>> "


def uf2_drives():
    """Mounted drives that have an INFO_UF2.TXT, as UF2 bootloaders do."""
    if platform.system() == "Windows":
        import string

        roots = [Path(f"{letter}:\\") for letter in string.ascii_uppercase]
    else:
        roots = list(Path("/Volumes").glob("*")) + list(Path("/media").glob("*"))
        roots += list(Path("/media").glob("*/*")) + list(Path("/run/media").glob("*/*"))
    found = []
    for root in roots:
        try:
            if (root / "INFO_UF2.TXT").is_file():
                found.append(root)
        except OSError:  # empty card readers and the like
            pass
    return found


def wait_for(condition, seconds):
    deadline = time.monotonic() + seconds
    while time.monotonic() < deadline:
        result = condition()
        if result:
            return result
        time.sleep(0.5)
    return None


def repl(port_name, statements):
    """Get a >>> prompt and send each statement. Return False if there was no prompt."""
    try:
        port = serial.Serial(port_name, 115200, timeout=0.1)
    except serial.SerialException:
        return False
    try:
        port.write(b"\x03\x03\r")
        out = b""
        deadline = time.monotonic() + 5
        while time.monotonic() < deadline and not out.endswith(PROMPT):
            out += port.read(port.in_waiting or 1)
        if not out.endswith(PROMPT):
            port.close()
            return False
        for statement in statements:
            port.write(statement.encode() + b"\r")
            time.sleep(0.3)
        port.close()
    except (serial.SerialException, OSError):
        pass  # the port goes away when a statement resets the board
    return True


def board_id(port_name):
    """The USB identity of the board on port_name, so it can be found again after a reset."""
    path = os.path.realpath(port_name)  # Linux /dev/serial/by-id/... links point to the tty
    for p in serial.tools.list_ports.comports():
        if p.device in (port_name, path):
            return (p.vid, p.pid, p.serial_number)
    return None


def circuitpython_back(ident, port_name):
    """Wait until the board's serial port is back and answers at the REPL. Return the port.

    Linux may give the board a new ttyACM number after a reset, so the port is found by the
    board's USB identity, not by its old name.
    """
    time.sleep(2)

    def answers():
        for p in serial.tools.list_ports.comports():
            same = (p.vid, p.pid, p.serial_number) == ident if ident else p.device == port_name
            if same and repl(p.device, []):
                return p.device
        return None

    return wait_for(answers, 40)


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("port")
    parser.add_argument("firmware", type=Path)
    args = parser.parse_args()
    if not args.firmware.is_file():
        sys.exit(f"No such file: {args.firmware}")
    if uf2_drives():
        sys.exit("A UF2 drive is already mounted; eject it or finish flashing first.")
    ident = board_id(args.port)
    if ident is None:
        sys.exit(f"No serial port {args.port}; python3 -m serial.tools.list_ports lists them.")
    port = args.port
    ok = True

    print("1. microcontroller.reset()")
    repl(port, ["import microcontroller", "microcontroller.reset()"])
    back = circuitpython_back(ident, port)
    in_bootloader = uf2_drives()
    passed = bool(back) and not in_bootloader
    ok &= passed
    port = back or port
    print(
        f"   PASS: back in CircuitPython on {port}"
        if passed
        else f"   FAIL: CircuitPython={bool(back)}, UF2 drive={in_bootloader}"
    )

    for step, mode in ((2, "UF2"), (3, "BOOTLOADER")):
        print(f"{step}. on_next_reset(RunMode.{mode}) and reset()")
        repl(
            port,
            [
                "import microcontroller",
                f"microcontroller.on_next_reset(microcontroller.RunMode.{mode})",
                "microcontroller.reset()",
            ],
        )
        drives = wait_for(uf2_drives, 20)
        if not drives:
            print("   FAIL: no UF2 drive appeared")
            ok = False
            continue
        info = (drives[0] / "INFO_UF2.TXT").read_text(errors="replace").splitlines()[0]
        print(f"   PASS: UF2 drive {drives[0]} ({info})")
        shutil.copyfile(args.firmware, drives[0] / args.firmware.name)
        back = circuitpython_back(ident, port)
        ok &= bool(back)
        port = back or port
        print(
            f"   PASS: flashed, and CircuitPython started on {port}"
            if back
            else "   FAIL: CircuitPython did not come back"
        )

    print("PASS" if ok else "FAIL")
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()

Trade-offs and Alternatives

  • RTC->BKP0R also holds the STM alarm module's wake flag, and the bootloader clears that
    register on every boot, so deep-sleep wake reasons can't work behind it. The Retro Arcade board
    turns alarm off. Moving the flag to another backup register would be a separate change.
  • The Meowbit's bootloader (KittenBot's fork) uses the same signatures, but I haven't tried this
    on a Meowbit, so this PR doesn't turn the flag on there.
  • Jumping into the bootloader from the running application would avoid the reset, but leaves
    peripherals and interrupts as they were. The signatures are the interface the bootloader
    provides for this.

Generative AI

I used generative AI (Claude Code and Codex) to write and test this change. I have reviewed it,
and I am responsible for the code and this description.

🤖 Generated with Claude Code

MakeCode Arcade consoles such as the ELECFREAKS Retro Arcade boot
through the uf2-stm32f bootloader, which reads a signature from
RTC->BKP0R on every reset. Without one it opens its UF2 drive and, once
USB enumerates, stays there. So on these boards microcontroller.reset()
and the reset into safe mode would stop in the bootloader.

Add BOARD_UF2_STM32F_BOOTLOADER, off by default. With it set,
reset_cpu() writes the bootloader's app signature just before
resetting, and reset_to_bootloader() writes its boot signature instead
of arming ST's ROM loader. RunMode.UF2 then works like
RunMode.BOOTLOADER; both, and the 1200-baud touch, open the UF2 drive.
microcontroller.reset() now goes through reset_cpu(), which is
unchanged for boards without the flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@dhalbert dhalbert left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@vegardw Is this really a bug that should be fixed in the bootloader?

@mmoskal is no longer at Microsoft, so the repo may be a dead end, but it could be forked. But I can understand that if a workaround is possible, that's fine.

@dhalbert
dhalbert merged commit 07a3721 into adafruit:main Nov 18, 2026
39 checks passed
@vegardw

vegardw commented Nov 18, 2026

Copy link
Copy Markdown
Author

@dhalbert I'll ask claude to help me investigate if something should be fixed in the bootloader. Thanks for merging.

@vegardw
vegardw deleted the stm-uf2-bootloader branch November 18, 2026 14:01
@vegardw

vegardw commented Nov 18, 2026

Copy link
Copy Markdown
Author

I looked into it with help from Claude Code, and I don't think it's a bootloader bug: it's how uf2-stm32f is meant to be used.

uf2-stm32f sends every reset to its UF2 drive unless the app has first written an "app" signature to RTC->BKP0R. That was a deliberate change from the PX4 bootloader it's based on (c3691b9, May 2018), together with the 24-hour wait once USB is connected. Three days later, the same author made MakeCode's target_reset() write that signature (923f3dc in codal-stm32, "Skip bootloader on reboot"). So on these consoles the reset button is the way into the drive, and the app says when a reset should go straight back to it. MakeCode games do what this PR does, much like DBL_TAP_MAGIC_QUICK_BOOT on SAMD.

The bootloader could tell a software reset from the button by itself by checking RCC->CSR, as one of its build options already does for power-on resets. But consoles already sold would keep their current bootloader, so CircuitPython would need the signature anyway.

While reading the code I did find one small real bug: it turns off the LSE on every boot (RCC_BDCR &= RCC_BDCR_RTCEN, missing a ~). It came from the PX4 bootloader, which has since fixed it. It doesn't affect CircuitPython, because port_init() resets the backup domain anyway.

@dhalbert

Copy link
Copy Markdown
Collaborator

While reading the code I did find one small real bug: it turns off the LSE on every boot (RCC_BDCR &= RCC_BDCR_RTCEN, missing a ~). It came from the PX4 bootloader, which has since fixed it. It doesn't affect CircuitPython, because port_init() resets the backup domain anyway.

Go ahead and fix it if it's a bug: one less cent of technical debt.

vegardw added a commit to vegardw/circuitpython that referenced this pull request Nov 18, 2026
Brings in the STM32F412Rx MCU support (adafruit#11896) and the uf2-stm32f
bootloader support (adafruit#11903), both now merged upstream.

The F412Rx pin tables conflicted: the merged version is main's, plus
the FSMC entries from the display-bus commit. The resulting files are
the same as before the merge. The tree is now main plus the display
bus and board commits, the board README and Stage at the commit that
adds this board.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
vegardw added a commit to vegardw/circuitpython that referenced this pull request Nov 19, 2026
The MCU, bootloader and display-bus support are now in main (adafruit#11896,
adafruit#11903, adafruit#11908), as is the audiopwmio silent-source fix (adafruit#11889). Say
so, update the base and free flash, and state briefly what was tested
on the device and what wasn't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants