Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flash ESP32 and Arduino boards from Rust and the browser

nanoflash is a Rust toolkit that lays out flash and writes firmware to ESP32 and Arduino boards, from the command line, as a Cargo runner and in the browser. One API serves the boards of several vendors. In the browser, it uses Web Serial. One layout file describes the partitions of a board, one manifest describes what to write, and nanoflash checks every image before it erases a byte.

It flashes the ESP32 family (ESP32, ESP32-S2, ESP32-S3, ESP32-C2, ESP32-C3, ESP32-C5, ESP32-C6, ESP32-H2, ESP32-P4) through the Espressif ROM loader, the Arduino Nano 33 BLE and the Arduino SAMD21 boards through SAM-BA, and Arduino’s AVR boards (Uno, Nano, Pro Mini, Mega 2560, Leonardo, Micro, Pro Micro) through their STK500v1, STK500v2 and AVR109 bootloaders.

What it does

  • Lays out the flash. A TOML layout file gives the flash size and named partitions with a role. nanoflash computes the offsets, checks alignment, overlap and size, reports the headroom of every partition, and writes the table that each family needs: the Espressif partition table, an MBR, linker regions or Rust constants. Partitions can grow with the flash that the chip reports.
  • Flashes boards. One board manifest gives the protocol, chip, layout, images, reset sequence and optional SHA-256 digests. Existing esp-web-tools manifests work unchanged. Images can be binary, Intel HEX or ELF files. Nothing is erased before every input is checked.
  • Fits the Rust workflow. nanoflash run is a Cargo runner, so cargo run builds, flashes and opens the serial monitor. cargo nanoflash runs every command as a Cargo subcommand. The build feature gives the build.rs of a firmware its layout constants and a whole memory.x.
  • Monitors the board. nanoflash monitor shows the serial output, sends what you type, follows the board through resets, and decodes defmt frames.
  • Runs in the browser. The npm package and the <nanoflash-button> web component use the same Rust code, compiled to WebAssembly, over Web Serial. The flasher page flashes a board from a manifest URL or from files on your computer, with nothing to install.
  • Works in CI. No prompts, --json output, clear exit codes.

Who it is for

  • Firmware developers who flash ESP32 and Arduino boards and want one tool instead of esptool, bossac and avrdude.
  • Rust embedded developers who want cargo run to flash and monitor, and a layout file as the one source of truth for the partitions and the linker regions.
  • Projects that ship firmware to users and want a web flasher, or a flash button on their own page.

What it does not do

  • It does not build firmware, sign it or provision secure boot. Verification of signatures is a hook of the caller.
  • It is not a debugger. Debug probes (CMSIS-DAP) come later.
  • It does not flash from Firefox or Safari, which do not implement Web Serial. Use the command there.
  • It does not patch the Espressif bootloader header or initialise otadata.

How this guide is organized

It has four parts, one per need:

Status

Layout checks, the table writers and flashing work natively and in the browser. They are tested against recorded transcripts, Espressif’s QEMU (ESP32 and ESP32-C3), arduino/BOSSA’s emulated SAM-BA bootloader and the Arduino STK500 bootloaders emulated by simavr. The release workflow attaches the binaries of the command to its GitHub releases. The crates nanoflash and nanoflash-cli are on crates.io, and the browser package nanoflash is on npm. USB DFU, UF2, CMSIS-DAP and Nordic serial DFU come next.

nanoflash is free software under the MIT or Apache-2.0 licence, at your option. The source, issues and releases are on GitHub.

Flash your first ESP32-S3

In this tutorial, you build ESP-IDF’s hello_world example, describe the flash of an ESP32-S3-DevKitC-1 in a layout file, write a board manifest, and flash the board with nanoflash. At the end, the board prints Hello world! and you see it in the serial monitor.

What you need

  • An ESP32-S3-DevKitC-1 (or another ESP32-S3 board with 8 MiB of flash), connected through its USB port (USB-Serial-JTAG, USB identity 303a:1001).
  • ESP-IDF installed, with IDF_PATH set.
  • The nanoflash command. See Install nanoflash.
  • On Linux, access to serial ports (the dialout group).

1. Build the firmware

Build hello_world for the ESP32-S3:

$ cd $IDF_PATH/examples/get-started/hello_world
$ idf.py set-target esp32s3 build

Leave the default console configuration: the USB-Serial-JTAG secondary console must stay enabled, or the text Hello world! never reaches the port.

Create a directory for the project and copy the two images into it:

$ mkdir -p ~/esp32-s3-hello/firmware
$ cp build/bootloader/bootloader.bin build/hello_world.bin ~/esp32-s3-hello/firmware/
$ cd ~/esp32-s3-hello

2. Describe the flash

Create layout.toml:

[flash]
size = "8 MiB"
alignment = "4 KiB"
base-address = 0x0

[[partition]]
name = "bootloader"
role = "bootloader"
offset = 0x0
size = "32 KiB"

[[partition]]
name = "partition-table"
role = "partition-table"
offset = 0x8000
size = "4 KiB"

[[partition]]
name = "nvs"
role = "custom"
size = "24 KiB"
espressif = { type = "data", subtype = "nvs" }

[[partition]]
name = "phy_init"
role = "custom"
size = "4 KiB"
espressif = { type = "data", subtype = "phy" }

[[partition]]
name = "application"
role = "firmware"
offset = 0x10000
size = "1 MiB"
alignment = "64 KiB"

This is the partition table of ESP-IDF’s default single-application layout.

3. Check the layout

$ nanoflash layout check layout.toml --image application=firmware/hello_world.bin

The table shows each partition with its offset and size. The application line shows the size of hello_world.bin and the headroom left in its partition. If the image does not fit, nanoflash stops here, before any device is involved.

4. Write the board manifest

Create manifest.toml:

[[board]]
identifier = "esp32-s3-devkitc-1"
name = "ESP32-S3-DevKitC-1"
protocol = "espressif"
chip = "esp32-s3"
layout = "layout.toml"
reset = "espressif-usb-serial-jtag"
application-devices = [{ vendor = 0x303a, product = 0x1001 }]
bootloader-devices = [{ vendor = 0x303a, product = 0x1001 }]

[[board.image]]
partition = "bootloader"
path = "firmware/bootloader.bin"

[[board.image]]
partition = "application"
path = "firmware/hello_world.bin"

The manifest does not list the partition table: nanoflash generates it from the layout.

5. Flash the board

Connect the board and run:

$ nanoflash flash --board manifest.toml
connecting
writing at 0x0
writing at 0x8000
writing at 0x10000
verifying
resetting
flashed esp32-s3-devkitc-1 (esp32-s3, 8 MiB)
...
verified

nanoflash found the port from the USB identity of the board, reset the chip into its ROM loader, wrote the bootloader, the partition table and the application, checked them with MD5, and reset the chip into the application.

6. See the output

$ nanoflash monitor --board manifest.toml --reset

The board restarts and prints Hello world!. Press Ctrl-C to quit.

What you learned

  • A layout file describes the flash once, and layout check shows the headroom of every image.
  • A board manifest names the layout and the images. nanoflash generates the partition table.
  • flash checks everything before it erases, then writes and verifies.

Next steps

Flash and monitor a Nano 33 BLE with cargo run

In this tutorial, you build the example firmware of the repository for the Arduino Nano 33 BLE. Its memory layout comes from a nanoflash layout file, and cargo run flashes it through the SAM-BA bootloader and opens the serial monitor. You write no memory.x and call no objcopy or bossac.

What you need

  • An Arduino Nano 33 BLE (nRF52840) and a USB cable.

  • Rust 1.95 or later with the target thumbv7em-none-eabihf:

    $ rustup target add thumbv7em-none-eabihf
    
  • The nanoflash command. Install it from crates.io (see Install nanoflash for the other ways):

    $ cargo install --locked nanoflash-cli
    
  • A clone of the repository:

    $ git clone https://github.com/AlixANNERAUD/nanoflash
    $ cd nanoflash/examples/nano33ble
    

1. Look at the board files

The example is a package of its own, with its own [workspace], Cargo.lock and target directory, because it builds for a microcontroller.

board/layout.toml describes the flash: Arduino’s bootloader in the first 64 KiB, the application after it, from 0x10000.

[flash]
size = "1 MiB"
base-address = 0x0

[[partition]]
name = "bootloader"
role = "bootloader"
offset = 0x0
size = "64 KiB"

[[partition]]
name = "application"
role = "firmware"
size = "remaining"

board/manifest.toml describes the board. It lists no image: the runner supplies the ELF file.

[[board]]
identifier = "arduino-nano-33-ble"
name = "Arduino Nano 33 BLE"
protocol = "samba"
chip = "nrf52840"
layout = "layout.toml"
reset = "touch-1200"
application-devices = [{ vendor = 0x2341, product = 0x805a }]
bootloader-devices = [{ vendor = 0x2341, product = 0x005a }]

Cargo.toml names the board in [package.metadata.nanoflash], so every nanoflash command in this directory knows it.

2. Look at how the firmware gets its layout

build.rs reads the layout of the board of the package, adds the RAM, and writes the constants and the whole memory.x that cortex-m-rt includes:

fn main() {
    nanoflash::build::Build::package()
        .memory("RAM", 0x2000_0000, 256 * 1024)
        .generate()
        .unwrap_or_else(|error| panic!("{error}"));
    println!("cargo:rustc-link-arg-bins=-Tlink.x");
}

src/main.rs includes the constants:

#![allow(unused)]
fn main() {
mod layout {
    include!(concat!(env!("OUT_DIR"), "/nanoflash_layout.rs"));
}

static APPLICATION_SIZE: u32 = layout::application::SIZE;
}

The firmware does nothing else: it loops forever.

3. Build

$ cargo build --release

The build links with the generated memory.x. Check that the ELF file fits its partition:

$ nanoflash layout check --image application=target/thumbv7em-none-eabihf/release/nanoflash-example-nano33ble

The application line shows the size of the firmware and the headroom left. Without a layout file, layout check uses the layout of the board of the package.

4. Flash and monitor

.cargo/config.toml sets the target and the runner:

[build]
target = "thumbv7em-none-eabihf"

[target.thumbv7em-none-eabihf]
runner = "nanoflash run"

Connect the board and run:

$ cargo run --release

Cargo builds the firmware and hands the ELF file to nanoflash run. The runner:

  1. touches the port of the sketch at 1200 baud, so that the board restarts into its bootloader (2341:005a);
  2. writes the application at 0x10000 through SAM-BA and checks it with CRC-16;
  3. restarts the board into the application;
  4. opens the serial monitor on the device of the application.

The example prints nothing, so the monitor stays open and empty. Press Ctrl-C to quit.

If the touch does not start the bootloader, press the reset button of the board twice and run the command again. To flash only, run cargo run --release -- --no-monitor.

What you learned

  • [package.metadata.nanoflash] names the board once, for the build script and for the command.
  • The build feature turns the layout into Rust constants and a memory.x.
  • nanoflash run is the Cargo runner: cargo run builds, flashes and monitors.

Next steps

Add a flash button to a web page

In this tutorial, you put a <nanoflash-button> on a web page of your own and flash an ESP32-S3 from Chrome, over Web Serial. You reuse the firmware of Flash your first ESP32-S3 and the JSON manifest of the repository.

What you need

  • The ESP32-S3 board and the two images of the first tutorial (bootloader.bin and hello_world.bin).
  • Chrome, Edge or Opera. Firefox and Safari do not implement Web Serial.
  • mise and Python 3. The tutorial builds the package from the repository, next to the example manifest. In your own project, npm install nanoflash gives the same package.

1. Build the browser package

$ git clone https://github.com/AlixANNERAUD/nanoflash
$ cd nanoflash
$ mise install
$ mise run web-wasm
$ npm --prefix web ci
$ npm --prefix web run build

web-wasm compiles the library to WebAssembly modules, one per protocol. npm run build compiles the TypeScript package into web/dist, with the modules in web/dist/wasm.

2. Put the firmware next to the manifest

The repository has a JSON manifest for the ESP32-S3-DevKitC-1, hardware/esp32-s3/manifest.json. It names firmware/bootloader.bin and firmware/hello_world.bin. Copy your images there:

$ mkdir -p hardware/esp32-s3/firmware
$ cp ~/esp32-s3-hello/firmware/*.bin hardware/esp32-s3/firmware/

Git ignores this directory.

3. Write the page

Create flash-page/index.html at the root of the repository:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Flash my board</title>
    <style>
      nanoflash-button { --nanoflash-button-background: #1f6feb; }
    </style>
  </head>
  <body>
    <h1>Flash my board</h1>
    <nanoflash-button id="button" manifest="../hardware/esp32-s3/manifest.json" label="Install"></nanoflash-button>
    <pre id="log"></pre>
    <script type="module">
      import "../web/dist/button.js";

      const button = document.getElementById("button");
      const log = document.getElementById("log");
      for (const name of ["nanoflash-done", "nanoflash-error"]) {
        button.addEventListener(name, (event) => {
          const detail = event.detail instanceof Error ? event.detail.message : JSON.stringify(event.detail);
          log.textContent += `${name} ${detail}\n`;
        });
      }
    </script>
  </body>
</html>

In a project that installs the package from npm, the import is import "nanoflash/button";.

4. Serve the page

A page needs a secure origin to use Web Serial, and localhost is one. From the root of the repository:

$ python3 -m http.server 8000 --bind 127.0.0.1

Open http://localhost:8000/flash-page/ in Chrome.

5. Flash

  1. Connect the board.
  2. Press Install. Chrome shows the ports that match the USB identity of the manifest.
  3. Choose USB JTAG/serial debug unit.
  4. Watch the progress. The button ends in the done state, and the log shows the report of nanoflash-done.

The page used the same Rust code as the command, compiled to WebAssembly: it checked the images, generated the partition table from the layout, wrote and verified the flash.

What you learned

  • <nanoflash-button> needs one attribute, the URL of a JSON manifest.
  • The browser asks the user for the port. Only Chromium-based browsers on a secure origin can flash.
  • The events nanoflash-done and nanoflash-error tell the page what happened.

Next steps

Install nanoflash

The command nanoflash and its twin cargo-nanoflash come from crates.io: a download through cargo binstall, or a build with cargo install. They also come as an archive from GitHub Releases, or as a build from the repository. The crates nanoflash and nanoflash-cli are on crates.io. The browser package nanoflash is on npm.

From crates.io

cargo binstall downloads the archive of the release of nanoflash-cli that matches the host, and installs both commands without a build. It reads [package.metadata.binstall] of nanoflash-cli (see Release archives):

$ cargo binstall nanoflash-cli

cargo install builds both commands for the host with Rust 1.95 or later. --locked uses the dependency versions of the release:

$ cargo install --locked nanoflash-cli

From GitHub Releases

Each release of the command has one archive per target. Release archives lists the six targets and what each archive holds.

Linux and macOS

Download, check and unpack the archive of your host, then copy both commands to a directory of your PATH. On a Linux host with an Intel or AMD processor:

$ base=https://github.com/AlixANNERAUD/nanoflash/releases/latest/download
$ curl -fsSLO "$base/nanoflash-x86_64-unknown-linux-musl.tar.gz"
$ curl -fsSLO "$base/nanoflash-x86_64-unknown-linux-musl.sha256"
$ sha256sum -c nanoflash-x86_64-unknown-linux-musl.sha256
nanoflash-x86_64-unknown-linux-musl.tar.gz: OK
$ tar -xzf nanoflash-x86_64-unknown-linux-musl.tar.gz
$ install -m 755 nanoflash-x86_64-unknown-linux-musl/nanoflash \
    nanoflash-x86_64-unknown-linux-musl/cargo-nanoflash ~/.local/bin/
$ nanoflash --version

sha256sum -c (shasum -a 256 -c on macOS) reads the checksum file and needs the archive in the same directory.

Windows

Download, check and unpack the archive with PowerShell. The checksum file holds the hash in lower case and Get-FileHash prints it in upper case, so the comparison ignores case (-eq does):

> $base = "https://github.com/AlixANNERAUD/nanoflash/releases/latest/download"
> $name = "nanoflash-x86_64-pc-windows-msvc"
> Invoke-WebRequest "$base/$name.zip" -OutFile "$name.zip"
> Invoke-WebRequest "$base/$name.sha256" -OutFile "$name.sha256"
> (Get-FileHash "$name.zip" -Algorithm SHA256).Hash -eq (Get-Content "$name.sha256").Split(" ")[0]
True
> Expand-Archive "$name.zip" -DestinationPath .

Check where an archive came from

The checksum file comes from the same release as the archive, so it detects a damaged download only. To check where an archive came from, verify its build provenance with the GitHub command line:

$ gh attestation verify nanoflash-x86_64-unknown-linux-musl.tar.gz --repo AlixANNERAUD/nanoflash

macOS: remove the quarantine attribute

The binaries are not signed and not notarised. A browser marks the downloaded archive with the quarantine attribute, and macOS then refuses to run the binaries. Remove the attribute from the unpacked directory (Apple silicon, then Intel):

$ xattr -dr com.apple.quarantine nanoflash-aarch64-apple-darwin
$ xattr -dr com.apple.quarantine nanoflash-x86_64-apple-darwin

An archive that curl downloads has no quarantine attribute.

From the repository

To install the state of the main branch, which can be newer than the last release, build the command from the repository with Rust 1.95 or later. This builds both commands for the host:

$ cargo install --locked --git https://github.com/AlixANNERAUD/nanoflash nanoflash-cli

Linux: get access to serial ports

A user needs the permission to open a serial port. On Debian, Ubuntu and Fedora the group dialout has it. On Arch Linux the group is uucp. Add yourself to the group, then log in again:

$ sudo usermod -aG dialout "$USER"

The browser package

npm install nanoflash

See Use the browser package.

Write a layout file

A layout file describes the flash of a board once. The command, the build.rs of the firmware and the browser read the same file. Every key is in Layout file.

Describe the flash

Create a TOML file with a [flash] table:

# layouts/esp32-s3-8mb.toml
[flash]
size = "8 MiB"
alignment = "4 KiB"
base-address = 0x0
  • alignment is the default alignment of every partition. Omit it for 4 KiB.
  • base-address is where the flash is mapped. Set it when the linker regions or the addresses of Intel HEX and ELF images need it. Omit it for 0x0.

Add the partitions

Add one [[partition]] per partition, in the order of the flash:

[[partition]]
name = "bootloader"
role = "bootloader"
offset = 0x0
size = "32 KiB"

[[partition]]
name = "partition-table"
role = "partition-table"
offset = 0x8000
size = "4 KiB"

[[partition]]
name = "nvs"
role = "custom"
size = "24 KiB"
espressif = { type = "data", subtype = "nvs" }

[[partition]]
name = "application"
role = "firmware"
size = "3 MiB"
alignment = "64 KiB"

[[partition]]
name = "storage"
role = "storage"
filesystem = "littlefs"
size = "remaining"
  1. Give each partition a unique name and a role.
  2. Give a fixed offset only where the bootloader or the chip needs one. nanoflash places the others after the previous partition, at their alignment.
  3. Give each partition a size. Use "remaining" for the last partition to take what is left.
  4. Add per-family attributes (espressif, mbr, linker) where the role is not enough. A custom partition needs them on Espressif.

Let partitions grow with the flash

When one product ships with several flash sizes, let the chip tell the size:

[flash]
size = "detect"
minimum = "4 MiB"

[[partition]]
name = "storage"
role = "storage"
size = { minimum = "1 MiB", grow = 3, maximum = "8 MiB" }
  • Keep fixed offsets in ascending order.
  • Do not let a firmware or update partition grow.
  • Put the partitions that must stay in place before the first partition that grows.

Growable partitions explains how the free space is shared.

A board with a bootloader at a fixed address

A board without a partition table on the flash, such as the Arduino Nano 33 BLE, needs only the bootloader and the application:

# Arduino Nano 33 BLE (nRF52840): Arduino's bootloader in the first 64 KiB, the application after it.
[flash]
size = "1 MiB"
base-address = 0x0

[[partition]]
name = "bootloader"
role = "bootloader"
offset = 0x0
size = "64 KiB"

[[partition]]
name = "application"
role = "firmware"
size = "remaining"

Next steps

Write a board manifest

A board manifest tells nanoflash how to reach a board and what to write to it. Every key is in Board manifest.

Write one board

# boards/esp32-s3.toml
[[board]]
identifier = "esp32-s3-devkitc"
name = "ESP32-S3-DevKitC"
protocol = "espressif"
chip = "esp32-s3"
layout = "../layouts/esp32-s3-8mb.toml"
reset = "espressif-usb-serial-jtag"
application-devices = [{ vendor = 0x303a, product = 0x1001 }]

[[board.image]]
partition = "bootloader"
path = "../build/bootloader.bin"

[[board.image]]
partition = "application"
path = "../build/application.bin"
  1. Set protocol and chip. Supported boards lists the values.
  2. Name the layout. Paths are relative to the manifest.
  3. List the USB identities of the board in application-devices, and in bootloader-devices when the bootloader has another identity. nanoflash then finds the port by itself.
  4. Add one [[board.image]] per image. Give the partition of the layout, or an offset.
  5. Do not add an image for the partition table: nanoflash generates it from the layout.

Pin the images

Add the SHA-256 digest of an image to refuse any other file:

[[board.image]]
partition = "bootloader"
path = "../build/bootloader.bin"
sha256 = "d67c656e01756650d77717b0839985a056ec28ffe174601d690fc407a2ceffca"

Do not pin an image that changes at every build.

Erase a data partition before writing

[[board.erase]]
partition = "nvs"

See Erase the flash.

An Arduino board with a 1200-baud touch

The Nano 33 BLE, the SAMD21 boards and the Leonardo restart into their bootloader after a 1200-baud touch. The bootloader has another USB identity. List both:

[[board]]
identifier = "arduino-nano-33-ble"
name = "Arduino Nano 33 BLE"
protocol = "samba"
chip = "nrf52840"
layout = "layout.toml"
reset = "touch-1200"
application-devices = [{ vendor = 0x2341, product = 0x805a }]
bootloader-devices = [{ vendor = 0x2341, product = 0x005a }]

[[board.image]]
partition = "application"
path = "firmware/hello.ino.bin"

A firmware with its own USB identity, for example the pid.codes identity 0x1209:0x0001, adds it to application-devices next to the identity of the Arduino sketch.

An AVR board takes the .hex file of the Arduino IDE as its image. protocol is stk500v1 (Uno, Nano, Pro Mini), stk500v2 (Mega 2560) or avr109 (Leonardo, Micro, Pro Micro).

Several boards in one manifest

List several [[board]] tables, with different identifiers. They may use different protocols. nanoflash picks the board from the USB identity of the port and the detected chip. --board-identifier picks one by hand.

Use the manifest in the browser

The browser reads JSON. Write the same keys in JSON, with board as an array:

{
  "board": [
    {
      "identifier": "esp32-s3-devkitc-1",
      "protocol": "espressif",
      "chip": "esp32-s3",
      "layout": "layout.toml",
      "reset": "espressif-usb-serial-jtag",
      "application-devices": [{ "vendor": "0x303a", "product": "0x1001" }],
      "image": [
        { "partition": "bootloader", "path": "firmware/bootloader.bin" },
        { "partition": "application", "path": "firmware/hello_world.bin" }
      ]
    }
  ]
}

An existing esp-web-tools manifest also works, with no change.

Check a layout and write its table

Check a layout

$ nanoflash layout check layouts/esp32-s3-8mb.toml
flash 8 MiB (0x800000), unallocated 4 KiB
name             role             offset    end       size      image  headroom
bootloader       bootloader       0x0       0x8000    32 KiB    -      -
partition-table  partition-table  0x8000    0x9000    4 KiB     -      -
nvs              custom           0x9000    0xf000    24 KiB    -      -
application      firmware         0x10000   0x310000  3 MiB     -      -
storage          storage          0x310000  0x800000  5056 KiB  -      -

The command exits with 1 and names the partitions and the addresses when the layout has an error.

See the headroom of an image

Pass the image of a partition:

$ nanoflash layout check layouts/esp32-s3-8mb.toml --image application=build/application.bin

Or check every image that a manifest writes:

$ nanoflash layout check --manifest boards/esp32-s3.toml

Without a layout file, --manifest checks the layout of the board of the manifest. Add --board-identifier when its boards use different layouts. In a Cargo package with [package.metadata.nanoflash], nanoflash layout check alone checks the layout of that board with its images.

An ELF file or an Intel HEX file is accepted as an image too. mise run example uses nanoflash layout check --image application=<ELF file> to check that the firmware starts at the offset of its partition and fits its size.

Preview a larger chip

A layout with size = "detect" is checked for its minimum flash size. To see the layout on a larger chip, pass --flash-size:

$ nanoflash layout check layouts/esp32-s3-detect.toml --flash-size "8 MiB"
flash 8 MiB (0x800000), minimum 4 MiB (0x400000), unallocated 60 KiB
name             role             offset    end       size      minimum  growth     image  headroom
...
storage          storage          0x320000  0x800000  4992 KiB  0 B      +4992 KiB  -      -

Images are still checked against the partition sizes on the minimum flash, as flash does. A fixed layout refuses --flash-size, and so does a size below the minimum.

Get JSON for a script

Add --json for one JSON document with the same data.

Write the table

$ nanoflash layout write layouts/esp32-s3-8mb.toml --format espressif --output partition-table.bin

--format is espressif, mbr, linker or constants. Layout file describes each output. flash writes the Espressif table by itself, so you need this command only to give the table to another tool.

Flash a board

Flash with a manifest

$ nanoflash flash --board boards/esp32-s3.toml
connecting
writing at 0x0
writing at 0x8000
writing at 0x10000
verifying
resetting
flashed esp32-s3-devkitc (esp32-s3, 8 MiB)
  0x0  bootloader  21 KiB
  0x8000  partition-table  3 KiB
  0x10000  application  812 KiB
verified

nanoflash checks every image before it erases anything, writes the images and the partition table, checks what it wrote, and resets the board into its application.

  • Port. nanoflash uses the only port that suits the board. When several ports suit it, pass --port.
  • Board. In a Cargo package with [package.metadata.nanoflash], --board is optional. When the manifest has several boards and the device cannot tell, pass --board-identifier.
  • Speed. --baud-rate changes the speed (460800 through a UART bridge by default). USB-Serial-JTAG boards and the ESP32-C2 stay at 115200 baud: see Espressif.
  • Verification. --no-verify skips the MD5, CRC-16 or read-back checks.
  • Scripts. --json prints one JSON document. The exit code is 0 on success, 1 for an input error, 2 for a device or connection error and 3 when the flash does not read back as written.

Find out what is attached

$ nanoflash detect --port /dev/ttyACM0
protocol espressif
chip esp32-s3
flash 8 MiB
usb 303a:1001
secure download mode no

Pass --protocol when the USB identity of the port does not tell, for example a Nano clone behind a CH340 bridge.

Flash an Espressif ELF file

An Espressif board can take an ELF file as the image of its application partition. The command turns it into an application image with espflash 4.7.

  • The partition must have the role firmware or update.
  • The image goes at a multiple of 0x10000, not below 0x10000.
  • The command writes a temporary file in the temporary directory of the system (TMPDIR on Unix) and removes it.

Other programs that use the library must provide the conversion themselves.

Flash an Arduino Nano 33 BLE or SAMD21 board

$ nanoflash flash --board hardware/nano33ble/manifest.toml
connecting
writing at 0x10000
verifying
resetting
flashed arduino-nano-33-ble (nrf52840, 1 MiB)
  0x10000  application  84 KiB
verified

nanoflash touches the port of the sketch at 1200 baud, waits for the port of the bootloader, writes and checks the images with CRC-16, then resets into the application. The bootloader at the start of the flash is never written.

If the touch does not start the bootloader, press the reset button of the board twice (the orange LED pulses) and pass the port of the bootloader.

The SAMD21 bootloader erases more than it writes. What flash erases describes it.

Flash an Arduino AVR board

Arduino’s AVR boards take the .hex file that the Arduino IDE builds.

$ nanoflash flash --board hardware/uno/manifest.toml
connecting
writing at 0x0
verifying
resetting
flashed arduino-uno-r3 (atmega328p, 32 KiB)
  0x0  application  300 B
verified
  • Uno, Nano, Pro Mini (stk500v1): a pulse on DTR resets them into Optiboot or the older ATmegaBOOT. nanoflash tries 115200 baud, then 57600. Pass --baud-rate 57600 for a Nano with the old bootloader to skip the first try.
  • Mega 2560 (stk500v2): its bootloader limits the order of the images. See What flash erases.
  • Leonardo, Micro, Pro Micro (avr109): a 1200-baud touch starts Caterina on its own port.

When the bootloader does not answer, press the reset button just before flashing: the bootloader of the Uno listens for only about a second after a reset. On the Leonardo, press reset once (the LED pulses) and pass the port of the bootloader within 8 seconds.

Pages are written whole and read back. The bootloader at the top of the flash is never written.

Flash a chip with more flash than the layout

A board whose layout has size = "detect" is checked against the minimum of the layout before connecting, then placed again for the flash that the chip reports:

$ nanoflash flash --board boards/esp32-s3-detect.toml
...
warning: the chip has 0x800000 bytes of flash, more than the minimum of 0x400000 of the layout, so partitions grew: "storage" from 0xe0000 to 0x4e0000 bytes; the bootloader image must be built for this flash size or with flash size detection
flashed esp32-s3-devkitc-detect (esp32-s3, 8 MiB)
  • Images and erase entries that name a partition follow it, and the partition table is generated for the reported size.
  • Images and erase entries given by offset, Intel HEX and ELF images and a manifest image of the partition table cannot follow the chip. They are refused when they touch a partition that moves, or for the table, when any partition grows or moves.
  • On an Espressif board, build the bootloader for this flash size or with flash size detection (one bootloader per flash size). The chip refuses a bootloader header that names more flash than it has.

Erase the flash

By default, flash erases only the regions that it writes, rounded to the erase unit. Data partitions such as NVS or storage keep their content, except on the SAMD21.

Erase one partition before writing

Add an erase entry to the board of the manifest:

[[board.erase]]
partition = "nvs"

Or give a region:

[[board.erase]]
offset = 0x9000
size = "24 KiB"

Erase entries are checked with the images, before anything is erased. On the SAMD21, an erase entry must end at the end of the flash. On the Mega 2560, it must start at 0x0, unless --erase-all is given.

To reset otadata on Espressif, list an erase entry for its partition, or an image for it. nanoflash does not initialise otadata by itself.

Erase the whole flash

$ nanoflash flash --board boards/esp32-s3.toml --erase-all

--erase-all erases the flash first, from the lowest offset that the bootloader writes to the end:

BootloaderWhat --erase-all erases
Espressif ROM loaderThe whole flash.
SAM-BA, Nano 33 BLEFrom 0x10000 to the end, with 0xFF pages. The bootloader stays.
SAM-BA, SAMD21From 0x2000 to the end. The bootloader stays.
AVRPages programmed with 0xFF up to where the bootloader starts, or up to the bootloader partition of the layout when it starts lower.

In the browser, pass eraseAll: true to prepared.flash, or set the erase-all attribute of <nanoflash-button>. A manifest with prompt-erase = true makes the button offer a checkbox.

Why the SAMD21 erases more

The SAMD21 bootloader erases from the lowest written address to the end of the flash, data partitions included. What flash erases describes this and the other bootloaders.

Build one flash image

nanoflash image build merges the images of a board into one flash image, with 0xFF between them. Use it for a production programmer, an emulator or a comparison.

$ nanoflash image build --board boards/esp32-s3.toml --fill --output flash.bin
wrote 8388608 bytes to flash.bin
  • The image holds the images of the manifest and the partition table generated from the layout.
  • --fill pads the image to the flash size of the layout.
  • --json prints one JSON document instead of the sentence.

A layout that detects the flash size

A merged image cannot follow the chip, so image build builds a detect layout for its minimum flash size, and --fill pads to the minimum. To build for another size, pass --flash-size:

$ nanoflash image build --board boards/esp32-s3-detect.toml --flash-size "16 MiB" --fill --output flash-16.bin

The partition table is generated for that size, the images go where their partitions then are, and --fill pads to that size.

Check the headroom first

nanoflash layout check --manifest boards/esp32-s3.toml shows the headroom of every image that the manifest writes. See Check a layout.

Monitor the serial output

nanoflash monitor shows what the application of a board writes to its serial port and sends what you type.

$ nanoflash monitor --board hardware/nano33ble/manifest.toml
monitoring /dev/ttyACM0 at 115200 baud; Ctrl-C quits
connected to /dev/ttyACM0
boot

Choose the port and the speed

  • The port is --port, else the only one that suits the board (--board gives its USB identities), else the only USB serial port.
  • The port opens at 115200 baud. --baud-rate changes it.
  • In a Cargo package with [package.metadata.nanoflash], the board of the package is used without --board. Without a board, the monitor still works.

The notes go to standard error, and the output of the board goes to standard output, byte for byte. You can redirect the output to a file.

Type to the board

  • Line mode (default): each line of standard input goes to the board with \n at its end. When standard input ends, the monitor goes on showing the output.
  • Raw mode (--raw): standard input must be a terminal. Each key goes to the board as the terminal encodes it, without waiting for the end of the line. The terminal goes back to its state when the command ends.

Ctrl-C quits in both modes, and the exit code is 0.

Restart the board first

--reset first resets the board into its application through its bootloader, so that you see the output from the start. It needs the protocol of the board: pass --board, or use a port with a known USB identity.

When the board restarts

When the board leaves (a reset, or a sketch that restarts its USB device), the monitor waits up to 30 s for the same device and opens it again. If the device does not come back, the exit code is 2. Exit code 1 is an input error, such as --raw without a terminal.

Get JSON lines

--json prints one JSON object per line of output, each with its time (RFC 3339, UTC), and the events connected, disconnected and error. A failure is the last line.

$ nanoflash monitor --port /dev/ttyACM0 --json
{"timestamp":"2026-11-24T09:30:01.250Z","event":"connected","port":"/dev/ttyACM0"}
{"timestamp":"2026-11-24T09:30:01.412Z","line":"boot"}
{"timestamp":"2026-11-24T09:30:09.870Z","event":"disconnected"}

Command line lists every record.

Decode defmt logs

A firmware that logs with defmt writes compact frames, not text. nanoflash monitor --elf decodes them with the format strings of the ELF file of the firmware.

Requirements

  • The firmware frames each defmt frame as esp-println does: the two bytes ff 00, the frame, and one byte 00. A plain stream of frames, as defmt-serial writes it, is not supported.
  • The frames use the rzcobs encoding, the default of defmt. The raw encoding is refused.
  • The ELF file is the one that the board runs. Its .defmt section holds the table of the format strings.

Decode the output

$ nanoflash monitor --board boards/esp32-s3.toml --elf target/xtensa-esp32s3-none-elf/release/firmware
boot
[INFO ] temperature 21 (src/main.rs:12)
  • A frame is shown on its own line: [INFO ] message (file:line). The location is shown only when the ELF file has debug information for the statement. The timestamp of the firmware, if it defines one, comes first.
  • The text between frames is shown as it is.
  • A frame that cannot be decoded (a statement that the table does not have, or damaged bytes) is shown as [MALFORMED defmt frame].
  • When the device leaves, a frame that was not finished is malformed. The text after the device comes back is not hidden.

--elf with a file that has no defmt table, or that uses the raw encoding, is an input error. Without --elf, the bytes of a frame are shown as text.

nanoflash run decodes the frames by itself when its image is an ELF file with a defmt table. When the table cannot be used, run writes a note on standard error and does not decode.

Get JSON

With --json, a frame is a record:

{"timestamp":"2026-11-24T09:30:01.412Z","defmt":{"level":"info","message":"temperature 21","device_timestamp":null,"location":{"file":"src/main.rs","line":12,"module":"firmware"}}}

location is null without debug information. The text before a frame is emitted first, as a line with "complete":false when it has no line feed. A malformed frame is the event malformed_defmt_frame.

Limits

  • The framing finds a frame by its first bytes. A ff 00 in plain text (output at another baud rate, a binary dump) starts a frame: the bytes up to the next 00 are not text. A text-only firmware may print no 00, so its output is hidden until a 00 byte comes, and the monitor shows one [MALFORMED defmt frame].
  • A frame is at most 4096 bytes. A longer frame is malformed, and the bytes up to the next 00 are dropped.
  • defmt-decoder 1.2.0, the crate that decodes the frames, can end the process on bytes that claim a very long slice of Format values ({=[?]}). It asks for the memory of the whole count before it reads any element, and the monitor cannot catch that. See issue 8.

Troubleshooting: the terminal stays in raw mode

When the process ends on the defmt-decoder failure above, the terminal stays in raw mode, because the end skips the code that restores it. Run reset (or stty sane) to restore the terminal.

The serial monitor and defmt explains how the decoder works.

Flash and monitor with cargo run

nanoflash run is a runner for Cargo. It writes the firmware that Cargo built to the board, then shows what the firmware writes to its serial port, as nanoflash monitor does.

Set up the runner

  1. Write a board manifest and a layout. The manifest needs no image: the runner supplies the ELF file. The layout needs one partition with the role firmware.

  2. Name the board in the Cargo.toml of the firmware:

    # Cargo.toml
    [package.metadata.nanoflash]
    board = "boards/nano33ble.toml"     # the board manifest, relative to this Cargo.toml
    # board-identifier = "arduino-nano-33-ble"   # the board of the manifest, when it has several
    
  3. Add the runner to .cargo/config.toml:

    # .cargo/config.toml
    [target.thumbv7em-none-eabihf]
    runner = "nanoflash run"
    

    runner = "nanoflash run --board boards/nano33ble.toml" also works, with a path relative to the directory of cargo run.

Run

$ cargo run --release
flashed arduino-nano-33-ble (nrf52840, 1 MiB)
  0x10000  application  64 KiB
verified
hello from the sketch

Cargo gives the ELF file to the runner. The arguments after -- in cargo run -- ... are options of nanoflash run:

  • -- --no-monitor only flashes. Use it when the serial port of the application speaks a binary protocol, not text: the monitor would show garbage and keep the port open.
  • -- --baud-rate 9600 sets the baud rate of the serial output. --flash-baud-rate sets the baud rate of flashing, with the exceptions that Espressif lists.
  • -- --raw sends each key as you type it. The command checks for a terminal before it flashes.
  • -- --erase-all, -- --no-verify, -- --port <port> and -- --progress <format> have the meaning that they have for flash and monitor.
  • -- --json prints the monitor as JSON lines, and the first line is the event flashed with the report of the flash.

When the ELF file has a defmt table, the runner decodes the defmt frames. See Decode defmt logs.

Make sure the monitor finds the application

flash resets the board into its application, and the monitor opens the application-devices of the board and waits up to 30 s for it. When the board starts in its bootloader and the manifest lists no application-devices, the monitor waits for the bootloader identity, which never comes back, and fails after 30 s. List the application-devices of the board.

A firmware with its own USB identity (not the identity of the Arduino sketch) needs it in the list too. An Arduino board with a 1200-baud touch shows the entries for the Nano 33 BLE and how to add that identity.

Use cargo nanoflash

The archives and the installation from the source give two commands: nanoflash and cargo-nanoflash. Cargo runs the second one as a subcommand, so cargo nanoflash <arguments> does the same as nanoflash <arguments>, with the same output and the same exit code:

$ cargo nanoflash flash
$ cargo nanoflash monitor --baud-rate 9600
$ cargo nanoflash layout check

cargo nanoflash flash only flashes. It does not build the firmware: cargo run builds with the target, the profile and the features that Cargo knows, and hands the ELF file to the runner. To flash without cargo run, build first, and name the built ELF file as an image of the board manifest, for example ../target/thumbv7em-none-eabihf/release/firmware:

$ cargo build --release && cargo nanoflash flash

Generate memory.x and layout constants

The build feature lets the build.rs of a firmware read its layout file. The firmware then gets the offsets and sizes of its partitions as Rust constants, and its linker regions from the same file. Build and cargo features lists every function and file.

Add the build dependency

[build-dependencies]
nanoflash = { version = "0.1", features = ["build"] }

The dependency comes from crates.io. To use the state of the main branch, which can be newer than the last release, replace version = "0.1" with git = "https://github.com/AlixANNERAUD/nanoflash". The example firmware examples/nano33ble uses a path dependency instead, so that CI builds it against the library of the same commit.

Generate the constants from a layout file

// build.rs
fn main() {
    nanoflash::build::generate("layouts/board.toml").unwrap();
}
#![allow(unused)]
fn main() {
// src/main.rs: FLASH_SIZE, and a module per partition with OFFSET, SIZE and ADDRESS
include!(concat!(env!("OUT_DIR"), "/nanoflash_layout.rs"));
}

The build script also writes nanoflash_memory.x, the MEMORY regions of the layout, to OUT_DIR and adds that directory to the linker search path.

Use the board of the package

Name the board once, in the Cargo.toml of the firmware:

[package.metadata.nanoflash]
board = "boards/board.toml"

Build::package() reads the layout of that board, so build.rs does not repeat the path:

// build.rs
fn main() {
    nanoflash::build::Build::package().generate().unwrap();
}

Without board-identifier, all boards of the manifest must use the same layout.

Write the whole memory.x

The linker script of cortex-m-rt (link.x) starts with INCLUDE memory.x and uses the regions FLASH and RAM. Build::memory adds the regions that are not partitions, such as the RAM, and writes the whole memory.x to OUT_DIR:

// build.rs
fn main() {
    nanoflash::build::Build::package()
        .memory("RAM", 0x2000_0000, 256 * 1024)
        .generate()
        .unwrap();
    // The runtime of the firmware chooses its linker script.
    println!("cargo:rustc-link-arg-bins=-Tlink.x");
}

Then:

  1. Delete the memory.x of the firmware. generate fails with an error that names the file when a memory.x is in the workspace root or in the package directory.
  2. Do not pass -Tnanoflash_memory.x. link.x includes a file named memory.x.
  3. Turn off the memory-x feature of HAL crates such as embassy-stm32 and stm32-metapac. Their memory.x can win over the generated file, and nanoflash cannot check it.
  4. Keep binaries for the host in another package. The guard script goes to every binary of the package, and a binary that does not link the generated memory.x fails with symbol not found: __nanoflash_memory_x.

A region name must use ASCII letters, digits and _, must not start with a digit, must be given once, and must not be the name of a region of the layout (FLASH for the firmware partition, the name of any other partition in upper case, or its linker region).

Troubleshooting: symbol not found: __nanoflash_memory_x

The link linked another memory.x than the generated one. rust-lld reports nanoflash_memory_guard.x:5: symbol not found: __nanoflash_memory_x, and GNU ld reports the same symbol as unresolved in an expression. Remove the other memory.x. Cargo links again only when the package changes, so the failure can wait for your next edit. How the generated memory.x is protected explains why.

Keep your own memory.x

When the layout holds every region that the firmware needs, a memory.x that includes the generated regions still works. Put it in the directory where the linker runs (the workspace root, or the package directory without a workspace), and do not call memory:

INCLUDE nanoflash_memory.x

Layouts that detect the flash size

With size = "detect", the files are written for the minimum flash of the layout. FLASH_SIZE becomes FLASH_MINIMUM_SIZE, a growing partition has MINIMUM_SIZE instead of SIZE, and a partition that moves has no OFFSET, no ADDRESS and no linker region. See Build and cargo features.

See it working

examples/nano33ble is a firmware that uses Build::package().memory(...). The tutorial Flash and monitor a Nano 33 BLE with cargo run walks through it.

Migrate from esptool, bossac or avrdude

nanoflash replaces the flashing tool of each family with one command and one manifest per project. This page maps the usual commands of esptool, bossac and avrdude to nanoflash.

From esptool

Write the offsets of the images in a board manifest once, or give each image a partition of a layout:

[[board]]
identifier = "my-board"
protocol = "espressif"
chip = "esp32-s3"

[[board.image]]
offset = 0x0
path = "build/bootloader/bootloader.bin"

[[board.image]]
offset = 0x8000
path = "build/partition_table/partition-table.bin"

[[board.image]]
offset = 0x10000
path = "build/hello_world.bin"

esptool 5 writes its commands with hyphens (write-flash), and esptool 4 with underscores (write_flash).

esptoolnanoflash
write-flash <offset> <file> ...nanoflash flash --board <manifest>
erase-flash before a writenanoflash flash --board <manifest> --erase-all
chip-id, flash-idnanoflash detect --port <port>
merge-binnanoflash image build --board <manifest> --output <file>
An esp-web-tools manifestUse it as it is: nanoflash flash --board manifest.json
--baud--baud-rate (USB-Serial-JTAG boards and the ESP32-C2 stay at 115200 baud, see Espressif)
--port--port, or nothing when only one port suits the board

These esptool commands have no equivalent: read-flash, verify-flash, read-mac, image-info and elf2image. nanoflash has no command that reads the flash. erase-region is an [[board.erase]] entry of the manifest.

With a layout, nanoflash also generates the partition table, so the manifest does not list it. Do not list the image of the partition table with a layout whose partitions grow with the flash.

nanoflash does not patch the bootloader header (flash size, mode, frequency) and does not initialise otadata. Build the bootloader with the right header, and list an image or an erase entry for otadata when you need it reset.

From bossac (Nano 33 BLE, SAMD21)

bossacnanoflash
bossac -d --port=<name> -U -i -e -w -v <bin> -Rnanoflash flash --board <manifest> --port <port> --json
bossac -U -R (leave the bootloader)nanoflash detect --port <bootloader port> --protocol samba
  • -i prints the device information: the output of flash and detect already names the chip and the flash.
  • -e sends X from the start of the application, which erases nothing on the bootloader of the Nano 33 BLE: the writes erase the pages. nanoflash flash does the same by default. --erase-all is the stricter equivalent: it clears the whole application area with 0xFF pages (slower), for when stale bytes after the image must go.
  • The touch, the wait for the bootloader and the reset happen inside flash. The port may be the port of the sketch or of the bootloader.
  • Exit code 2 replaces “No device found”, and exit code 3 a failed verification.

A manifest for a firmware with its own USB identity lists:

  • application-devices = [{ vendor = 0x1209, product = 0x0001 }] (its pid.codes identity, for a firmware that enters the bootloader on baud == 1200 && !dtr);
  • bootloader-devices = [{ vendor = 0x2341, product = 0x005a }];
  • an image at offset = 0x10000 of the .bin file, or the ELF file itself.

nanoflash layout write --format linker or the constants of the build feature give the same FLASH region as a hand-written memory.x.

A Cargo runner that calls objcopy and bossac

A firmware that Cargo flashes with a runner that calls objcopy and bossac can use nanoflash run instead. The runner takes the ELF file, so the conversion is not needed.

  1. Add a board manifest and a layout file (copy the ones of examples/nano33ble/board), and name the manifest in [package.metadata.nanoflash].

  2. List the USB identities of the board in application-devices and bootloader-devices. The touch at 1200 baud moves the board from the first to the second. An Arduino board with a 1200-baud touch shows the entries of the Nano 33 BLE. Add the identity of your firmware to application-devices when it has its own.

  3. Replace the runner in .cargo/config.toml with nanoflash run. When the serial port of the application speaks a binary protocol and not text, use nanoflash run --no-monitor, which only flashes.

From avrdude (Uno, Nano, Mega 2560, Leonardo)

avrdude -p<mcu> -c<protocol> -P<port> -b<speed> -D -Uflash:w:<file>.hex:i becomes:

$ nanoflash flash --board <manifest> --port <port> --json
  • -D (no chip erase) is the default behaviour: pages are erased as they are written.
  • The chip and the protocol come from the manifest. -b<speed> is --baud-rate. Without it, nanoflash tries the usual rates of the bootloader (see Supported boards). -carduino is protocol = "stk500v1" (or "arduino"), -cwiring is "stk500v2" (or "wiring"), and -cavr109 is "avr109".
  • The image is the same .hex file.
  • nanoflash reads back every page that it writes.

Use the browser package

The npm package nanoflash flashes boards from a web page over Web Serial. It is the Rust library compiled to WebAssembly, behind a TypeScript API with no runtime dependency. Every export is in Browser API.

Before you start

  • Web Serial exists in Chromium-based browsers only (Chrome, Edge, Opera), on a secure origin (https: or localhost). isSupported() tells whether the browser has it.
  • The browser reads JSON manifests: nanoflash’s (the keys of the TOML manifest, with board as an array) or an esp-web-tools manifest.
  • Install the package with npm install nanoflash, or build it from the repository with mise run web.

Add a button with no code

<script type="module">import "nanoflash/button";</script>
<nanoflash-button manifest="firmware/manifest.json" label="Install"></nanoflash-button>

The element handles the port chooser, the progress, the errors and the second permission of Arduino boards. Style it with CSS custom properties and parts. The tutorial Add a flash button to a web page walks through it.

Flash from your own code

import { isSupported, prepare, NanoflashError } from "nanoflash";

if (!isSupported()) showMessage("Use a Chromium based browser, or the command line.");
// Before the click: reads the manifest and starts loading the WebAssembly module.
const prepared = await prepare("/boards/esp32-s3.json");
if (prepared.promptErase) showEraseCheckbox();

button.addEventListener("click", async () => {
  try {
    const report = await prepared.flash({
      eraseAll: checkbox.checked,
      onProgress: ({ stage, done, total }) => showProgress(stage, done, total),
      onMessage: (text) => log(text),
    });
    showMessage(`Flashed ${report.board} (${report.chip.chip}), verified: ${report.verified}`);
  } catch (error) {
    if (error instanceof NanoflashError) showMessage(`${error.kind} (${error.errorClass}): ${error.message}`);
    else throw error;
  }
});
  1. Call prepare before the click. It reads the manifest and starts to load the module.
  2. Call prepared.flash straight from the click handler. A browser shows the port chooser only during a user gesture, and an await may end it. prepared.flash asks for the port before its first await.
  3. Show report.warnings. Each warning has a kind and the message to show. onMessage also receives the three warnings about the flash size.

A manifest may mix protocols. The USB identity of the chosen port, matched against the application-devices and bootloader-devices of each board, picks the boards and so the module to load. With no devices listed, the boards that a serial bridge suits are candidates. A port that suits no board fails with no-matching-board, and one that suits boards of several protocols with several-protocols: give boardIdentifier.

Arduino boards and the bootloader permission

An Arduino board that runs a sketch is reset into its SAM-BA bootloader by opening its port at 1200 baud and clearing DTR. The bootloader then appears as another USB device (the Nano 33 BLE goes from 2341:805a to 2341:005a), which the page has no permission for the first time.

  1. flash waits 15 s for the bootloader among the granted ports, then fails with not-granted.
  2. From a second click, ask for that port with navigator.serial.requestPort({ filters: prepared.bootloaderFilters }) (the bootloader-devices of the manifest), and call prepared.flash({ port }) with it. The component does this with its second button.
  3. The browser keeps the grant, so the next flash finds the bootloader by itself.

A board already in its bootloader (double tap on reset) is flashed as it is.

The Leonardo, Micro and Pro Micro (AVR109) do the same: the touch, then Caterina on its own USB identity (2341:8036 becomes 2341:0036 on a Leonardo). Caterina goes back to the sketch 8 s after the touch, so flash waits 5 s for it before it fails with not-granted. For the first grant, press the reset button of the board once and choose its port while the LED pulses. The bootloader permission text of the component says so when the manifest has an avr109 board.

The Uno, Nano, Pro Mini and Mega 2560 keep their port: a pulse on DTR resets them into their bootloader, through the USB serial chip of the board or a serial bridge.

Detect a chip

import { detect } from "nanoflash";

const chip = await detect({ protocol: "espressif" });
console.log(chip.chip, chip.flashSize);

protocol names the protocol, and so the module to load.

Check a layout and write its table

import { checkLayout, writeLayout } from "nanoflash";

const text = await (await fetch("/layouts/esp32-s3-8mb.toml")).text();
const report = await checkLayout(text, [{ partition: "application", size: 1_048_576 }]);
const table: Uint8Array = await writeLayout(text, "espressif"); // or "mbr", "linker", "constants"

For a layout with size = "detect", pass flashSize to see it on a larger chip:

const report = await checkLayout(text, [], "layout.toml", { flashSize: "16 MiB" });
const table = await writeLayout(text, "espressif", "layout.toml", { flashSize: 16_777_216 });

Handle errors

Every failure is a NanoflashError with a kind and an errorClass.

  • no-port-chosen: the user closed the port chooser.
  • port-request-refused: the browser did not show the chooser. A page in an iframe needs allow="serial", and a permissions policy may block Web Serial.
  • not-granted: the board came back as a device that the page has no permission for.
  • module-broken: a WebAssembly module trapped. Ask the user to reload the page.

Errors and warnings lists every kind.

Bundle the package

Each module is a separate dynamic import, loaded relative to the module that imports it. If your bundler does not copy the .wasm files that it finds this way, copy node_modules/nanoflash/dist/wasm next to the chunk.

Use the flasher page

The flasher page at https://alixanneraud.github.io/nanoflash/flasher/ flashes a board from a manifest that you give as an https: URL or as files on your computer. Nothing to install: open it in Chrome, Edge or Opera. The site hosts no firmware and no manifest.

Flash from files on your computer

  1. Open the flasher page.
  2. Select the manifest (exactly one .json file) and every file that it names: the layout and the images.
  3. Press Install, choose the port of the board, and wait for done.

The page replaces each relative path of the manifest (layout, image[].path, parts[].path) by the selected file with the same name (the last segment of the path). Two different paths with one file name are refused with a message that names both. A manifest that names a URL needs the same confirmation as a manifest URL.

Flash from a manifest URL

  1. Open https://alixanneraud.github.io/nanoflash/flasher/?manifest=<URL>, or paste the URL in the manifest field. The URL must use https:.
  2. Read the boards and the origins that the page shows. Tick the checkbox to confirm the source of the manifest. The label names the whole manifest URL and every other origin that the manifest loads files from.
  3. Press Install, choose the port of the board, and wait for done.

Publish a manifest for the flasher page

To give your users a one-click link:

  1. Publish the manifest and its files on a server that allows cross-origin reads (Access-Control-Allow-Origin). raw.githubusercontent.com and GitHub Pages send it. The download URLs of GitHub releases do not.
  2. Do not redirect to another origin: the page refuses it.
  3. Use paths relative to the manifest. The page resolves them against the manifest URL.
  4. Share https://alixanneraud.github.io/nanoflash/flasher/?manifest=<URL of your manifest>.

Your users still confirm the origin of the manifest before anything is flashed. Browser support and security explains why.

Troubleshooting: the page refuses to start

The page refuses to run inside a frame. Open it in its own tab.

Troubleshooting: which version runs

The footer shows the version of web/package.json and the short hash of the commit that the site was built from.

Work on the flasher page

To run or change the page itself, see Work on the flasher page.

Release and publish

This page is for maintainers. A release creates git tags and GitHub releases. It publishes nothing to crates.io or npm. A second step, the workflow publish.yml, publishes a release to the registries by hand (see “Publish to crates.io and npm”).

How a release happens

  1. Every push to main runs .github/workflows/release.yml. The job release-plz-pr opens or updates the release pull request (chore: release vX.Y.Z). The pull request changes the versions and the changelogs of the crates that changed.
  2. Merge the release pull request after the checks pass.
  3. The push to main runs the job release-plz-release. release-plz runs in git-only mode (git_only = true in release-plz.toml). It creates two tags and two GitHub releases:
    • vX.Y.Z for the library nanoflash;
    • nanoflash-cli-vX.Y.Z for the command nanoflash-cli. This release is marked as the latest release.
  4. The crate nanoflash-web is not released (release = false). Its publish = false setting does not exclude it in git-only mode.
  5. The job release-plz-release outputs the list of releases (releases, a JSON array of package_name, prs, tag and version).
  6. The job plan reads that list. When it contains nanoflash-cli, the job binaries calls .github/workflows/binaries.yml with the tag of that release. Otherwise binaries does not run.
  7. To publish the release to crates.io, start publish.yml by hand (see “Publish to crates.io and npm”).

The lockfile of the example firmware (examples/nano33ble/Cargo.lock) records the version of the path dependency nanoflash. release-plz does not update it. mise run example builds the example without --locked, so Cargo updates that entry. Commit the changed lockfile with the next change of the example.

A tag and a release created with GITHUB_TOKEN start no other workflow. A workflow that must run for a release is called by release.yml itself.

Assets of the release of the command

The release nanoflash-cli-vX.Y.Z has no assets for the minutes that binaries.yml needs to build and upload them. binaries.yml builds the command for six targets on native runners. Release archives lists the targets and the three assets of each target: the archive, its checksum and its software bill of materials.

The job build attests the build provenance of each archive. Verify an archive with:

gh attestation verify nanoflash-<target>.tar.gz --repo AlixANNERAUD/nanoflash
gh attestation verify nanoflash-<target>.zip --repo AlixANNERAUD/nanoflash

The job sbom runs after every build job succeeds. It runs mise run release-sbom, which writes the six SBOMs into target/sbom/, and uploads them to the release.

The archive names have no version, so the URL of the latest release does not change. The metadata [package.metadata.binstall] in crates/nanoflash-cli/Cargo.toml names these archives: its pkg-url and bin-dir must follow every change of their names or of their directory.

When the assets are missing

When a job of binaries.yml fails, the release keeps the assets that were uploaded before the failure. A run on the tag uses the workflow and the sources of the tag, so it cannot use a fix made after the tag.

  • When the cause is outside the repository (a runner, the network, an outage of GitHub), use “Re-run failed jobs” on the run of release.yml, or start the workflow again on the tag:

    gh workflow run binaries.yml --ref <tag> -f tag=<tag>
    

    <tag> is the tag of the release, for example nanoflash-cli-v0.1.0. The command must name the tag in --ref. The provenance names the commit of the run, and the jobs fail when the tag is not that commit. Uploads replace the assets that exist.

  • When the cause is in the workflow or in the sources, fix it on main and release the next version.

Dry run

To build the archives without a release, start the workflow by hand without a tag:

gh workflow run binaries.yml

A dry run builds, tests and packs the six targets. It uploads nothing to a release, writes no SBOM and attests nothing. It keeps each archive and its checksum as a workflow artifact for 7 days.

Site on GitHub Pages

.github/workflows/pages.yml deploys the site to https://alixanneraud.github.io/nanoflash/. The guide (docs/, built with mdBook) is the root of the site. The flasher page (web/flasher) is at https://alixanneraud.github.io/nanoflash/flasher/. The site has a sitemap.xml and a robots.txt at its root (see “Make the sitemap known to search engines”). The workflow runs:

  • after each push to main that changes docs/, web/, crates/nanoflash/, crates/nanoflash-web/, Cargo.toml, Cargo.lock, mise.toml or the workflow;
  • when you start it by hand (gh workflow run pages.yml --ref main).

The job build runs mise run pages. That task builds the four WebAssembly modules and runs mise run web-size: the job fails when a module is over 256000 bytes with gzip -9. The task then builds the guide (mise run docs) and assembles the site in target/pages, and the job uploads it with actions/upload-pages-artifact. The job deploy publishes it with actions/deploy-pages in the environment github-pages. Runs of the workflow do not overlap, and a running deployment is not cancelled. Both jobs run only in the repository of the owner.

The flasher page shows the version of web/package.json and the short hash of the commit that the site was built from (flasher/site.json). The site hosts no firmware and no manifest. The version of the page does not change the npm package: this workflow publishes nothing to npm.

Enable GitHub Pages once, before the first push that runs the workflow. Without it, the job deploy fails with a 404 error.

  1. Open Settings, Pages, and set “Source” to “GitHub Actions”. Or run:

    gh api -X POST repos/AlixANNERAUD/nanoflash/pages -f build_type=workflow
    
  2. Start the workflow: gh workflow run pages.yml --ref main.

  3. Open the URL that the run page shows for the job deploy, then open its flasher/ page in Chrome or Edge. The footer of the flasher page shows the version and the commit.

To check the site on the computer, run mise run pages-serve. It serves the guide at http://localhost:8000/ and the flasher page at http://localhost:8000/flasher/.

Make the sitemap known to search engines

Crawlers read robots.txt only at the root of the host, here https://alixanneraud.github.io/robots.txt. That address belongs to another repository, which does not exist. The file robots.txt of this site is at /nanoflash/robots.txt, so crawlers do not read it, and its Sitemap: line does not make the sitemap known. Do one of these steps:

  • Add the property https://alixanneraud.github.io/nanoflash/ (a URL prefix) in Google Search Console and in Bing Webmaster Tools, and submit https://alixanneraud.github.io/nanoflash/sitemap.xml in each tool.
  • Or create the repository AlixANNERAUD.github.io and put a robots.txt at its root with the line Sitemap: https://alixanneraud.github.io/nanoflash/sitemap.xml.

Search Console checks the ownership of the property with an HTML file or a meta tag. Neither is in the site yet.

Publish to crates.io and npm

release-plz runs in git-only mode, so it never publishes. The workflow .github/workflows/publish.yml publishes a release to the registries. It starts by hand only (workflow_dispatch). The crates nanoflash and nanoflash-cli have been on crates.io since version 0.1.0, and the npm package nanoflash since version 0.1.0.

Before you publish

A published version cannot be replaced. Crates.io and npm accept a yank or a deprecation, but not a change of the files. Before you publish a version:

  1. Run the hardware checks of Run the hardware tests with the boards of the loop, including the monitor and run check and the browser check.
  2. Fix every failure on main and let release-plz propose the next version.
  3. Check that web/package.json in the release pull request has the new version of the library. release-plz does not change web/package.json. After release-plz writes the branch, release.yml sets the version of crates/nanoflash in web/package.json and web/package-lock.json and pushes a commit when the version changes. When the repository has no secret RELEASE_PLZ_TOKEN, a push with the default GITHUB_TOKEN starts no other workflow, so release.yml also starts the CI on the head of the branch.
  4. Merge the release pull request only after the checks pass.
  5. Wait for release.yml to create the release and for binaries.yml to upload the archives. The command cargo binstall nanoflash-cli needs the archives of the release.

Start the workflow

Start the workflow on the branch main and name the tag of the library release:

gh workflow run publish.yml --ref main -f tag=v0.1.1 -f npm=true

The workflow has three inputs:

InputDefaultMeaning
tagnoneThe tag of the library release, vX.Y.Z. The jobs check out this tag and publish its sources.
cratestrueRun the job crates: publish nanoflash and nanoflash-cli to crates.io.
npmfalseRun the job npm: stage the npm package nanoflash.

Both jobs run only in the repository of the owner, and only when the run starts on main. A run on another branch publishes nothing, so that the secret and the trust of npm never reach the workflow file of another branch. Runs of the workflow do not overlap, and a running publication is not cancelled.

The job crates

  1. Checks that the tag has the form vX.Y.Z and that version in crates/nanoflash/Cargo.toml is the version of the tag. The job fails otherwise.
  2. Runs mise run package, the same package check as release.yml: every crate is packed and built from its package.
  3. Runs cargo publish --workspace --locked with the secret CARGO_REGISTRY_TOKEN. Cargo publishes nanoflash before nanoflash-cli, because the command depends on the library. It skips nanoflash-web (publish = false).

The repository secret CARGO_REGISTRY_TOKEN must exist. A version that is already on crates.io makes the publication fail. Start the next release instead.

The job npm

The job has no token. npm trusted publishing lets the workflow file publish.yml of this repository stage a version of the package nanoflash, and nothing else. The trusted publisher is set in the settings of the package on npmjs.com:

FieldValue
PublisherGitHub Actions
Organization or userAlixANNERAUD
Repositorynanoflash
Workflow filenamepublish.yml
Environment namenone
Allowed actionsnpm stage publish only. npm publish and npm dist-tag are not allowed.

The publishing access of the package requires two-factor authentication and refuses tokens that bypass it. A staged version is not public: a maintainer approves it with two-factor authentication.

The job:

  1. Checks that version in web/package.json is the version of the tag.
  2. Runs mise run web: builds the WebAssembly modules, checks their size, builds the package and runs its tests.
  3. Runs npm stage publish --access public --provenance --ignore-scripts in web/, with npm 11.21.3: Node 22 comes with npm 10, and npm stage needs npm 11.15.0 or later. npm exchanges the OpenID Connect token of the run for a short-lived credential and signs the provenance statement with it, so the job has the permission id-token: write.

Then approve the version. On npmjs.com, open Staged Packages, check the version and its files, and approve it. The command npm stage approve <stage-id> (npm 11.15.0 or later) does the same. The version gets the dist-tag that npm stage publish names, latest by default.

Run the hardware tests

This page is for contributors. Four checks run the flashing path against something other than a transcript: Espressif’s QEMU, arduino/BOSSA’s SAM-BA emulator and Arduino’s AVR bootloaders in simavr (no board needed), and real boards attached to a machine. Two manual checks cover the monitor, the Cargo runner and the browser package. How nanoflash is tested explains where these checks fit.

The files are in the directory hardware/ of the repository.

QEMU

mise run test-qemu runs hardware/qemu/run.sh esp32 and hardware/qemu/run.sh esp32c3 on an x86-64 or AArch64 Linux machine with libslirp (Debian: libslirp0). For each chip the script

  1. downloads Espressif’s QEMU release pinned in QEMU_RELEASE (from https://github.com/espressif/qemu/releases) into target/qemu/ (or $QEMU_DIRECTORY), and refuses an archive without the SHA-256 digest pinned in the script,
  2. starts it in UART download mode with its serial port on a pseudo-terminal (-serial pty),
  3. flashes the manifest hardware/qemu/<chip>.toml (the fixture images, a 4 MiB layout, no reset) and records the traffic: the ESP32 at 115200 baud, since the emulated ESP32 stops answering after CHANGE_BAUDRATE, the ESP32-C3 at 460800 baud,
  4. stops QEMU, builds the expected image with nanoflash image build --fill and compares it with the emulated flash (cmp),
  5. replays the recording with --replay, which must succeed: the recorder and the replayer agree on the traffic of the real ROM.

The qemu job of .github/workflows/ci.yml runs this and is allowed to fail: it is not a required check. If the emulated ROM cannot run a step (for example the flash identifier), record the step here.

When Espressif publishes a new release, update QEMU_RELEASE, QEMU_VERSION and the four digests (from the checksum.sha256 asset of the release) in the script, and check the flags against the esp32 and esp32c3 pages of https://github.com/espressif/esp-toolchain-docs/tree/main/qemu (the strap modes 0x0f and 0x02 select the UART download mode).

SAM-BA emulator

mise run test-samba-emulator runs hardware/samba-emulator/run.sh on Linux or macOS with git, python3, make and a C++ compiler (no package to install, no root). The script

  1. fetches https://github.com/arduino/BOSSA at the commit pinned in BOSSA_COMMIT into target/samba-emulator/BOSSA (or $SAMBA_EMULATOR_DIRECTORY/BOSSA), refuses a checkout at another commit, and builds bossac (make prints wx-config: not found: only the graphical BOSSA needs wxWidgets). BOSSA is BSD-3-Clause: it is only built and run as a test tool, and none of its code is in this repository,
  2. runs hardware/samba-emulator/emulate.py, which starts BOSSA’s emulated Arduino Nano 33 BLE bootloader (tests/samba.py) on a pseudo-terminal for each scenario and prints <name> ok or <name> FAILED: <why>:
    • nanoflash: flashes hardware/samba-emulator/nano33ble.toml (the fixture application at 0x10000, no reset, no USB identity) and records the traffic; the flash holds the image and 0xFF elsewhere, the emulator saw X first and K last,
    • same-flash-as-bossac: flashes a 154600-byte image with nanoflash, and with bossac -U -i -e -w -v <image> -R on a fresh emulator; the images are identical in both flashes, and so is everything outside the last page. The rest of the last page differs: nanoflash pads it with 0xFF, bossac with 0x00,
    • crc-mismatch: the emulator corrupts one byte; exit code 3, verification-failed, then K,
    • no-bootloader: the emulator never answers; exit code 2, no-bootloader, nothing written,
    • below-the-application: an image at 0x0; exit code 1, below-writable-flash, nothing erased or written,
  3. replays the recording with --replay, which must succeed.

crates/nanoflash/tests/transcripts/samba/recorded/emulator-nano33ble.transcript is a copy of the recording, replayed by cargo test.

The samba-emulator job of .github/workflows/ci.yml runs this and is allowed to fail: BOSSA is fetched from GitHub, and the emulator is not the real bootloader. If it fails while nanoflash did not change, first check whether the emulator or bossac changed. To move to a newer BOSSA, update BOSSA_COMMIT (and the commit named in the first line of the copied transcript), run the task, read the new tests/samba.py for changed commands, then copy target/samba-emulator/nano33ble.transcript over the recorded transcript, keeping its first comment line.

simavr

mise run test-simavr runs hardware/simavr/run.sh on Linux with curl and a C compiler. It flashes three of Arduino’s STK500 bootloaders, run unmodified by simavr 1.6. The script

  1. downloads optiboot_atmega328.hex (the Uno’s Optiboot), ATmegaBOOT_168_atmega328.hex (the old Nano bootloader) and stk500boot_v2_mega2560.hex (the Mega 2560’s wiring bootloader) from https://github.com/arduino/ArduinoCore-avr at the commit pinned in ARDUINO_AVR_COMMIT into target/simavr/ (or $SIMAVR_DIRECTORY),
  2. finds simavr’s headers and static libraries through pkg-config (libsimavr-dev installed), or else, on Debian or Ubuntu without root, fetches the package with apt-get download libsimavr-dev and unpacks it into target/simavr/root; it stops with install libsimavr-dev (Debian, Ubuntu) when neither works,
  3. builds hardware/simavr/harness.c against them into target/simavr/harness. The harness loads the bootloader at the top of a blank flash, runs it at 16 MHz and no faster than wall time (Optiboot’s one-second watchdog would otherwise expire between two commands), puts UART0 on a pseudo-terminal under /dev/pts (not simavr’s /tmp/simavr-uart0 link), presses the reset button while the application is blank (Optiboot otherwise jumps to it), and writes the flash to a file when the bootloader starts the application,
  4. for each scenario, flashes hardware/simavr/<board>.toml (the AVR fixture application, the board’s layout, no reset, no USB identity) through the pseudo-terminal and records the traffic, waits for the application to start, compares the flash below the bootloader with nanoflash image build --fill, and replays the recording with --replay:
    • optiboot: an ATmega328P with Optiboot, uno.toml, 0x7E00 bytes,
    • atmegaboot: an ATmega328P with ATmegaBOOT, nano.toml with --baud-rate 57600 (simavr ignores the host’s baud rate, so this checks the explicit rate and the 2 KiB bootloader), 0x7800 bytes,
    • mega2560: an ATmega2560 with the wiring bootloader, mega2560.toml, 0x3E000 bytes,
  5. prints <name>: flashed, flash content identical, transcript replayed for each.

The emulator cannot check the DTR reset pulse (a pseudo-terminal has none), the fallback from 115200 to 57600 baud (any rate works) nor Caterina (USB): the transcripts of crates/nanoflash/tests/transcripts/avr/ and the boards cover those.

crates/nanoflash/tests/transcripts/avr/recorded/simavr-{optiboot,atmegaboot,mega2560}.transcript are copies of the recordings, replayed by cargo test.

simavr (GPL-3.0-or-later) and the bootloaders (GPL) are only downloaded or installed and run: none of their code is in this repository, the harness is written from simavr’s public headers, and the harness binary, which links simavr statically, is never distributed.

The simavr job of .github/workflows/ci.yml runs this after apt-get update, without installing simavr: the script fetches libsimavr-dev (about 136 KB) with apt-get download. Installing the package instead would pull mesa and LLVM through libsimavrparts1 (about 240 MB on a bare Ubuntu), which the statically linked harness does not need. It is allowed to fail: the images come from GitHub and simavr is not the chip. If it fails while nanoflash did not change, first check whether simavr (the package version) or the pinned images changed. To move to a newer ArduinoCore-avr, update ARDUINO_AVR_COMMIT (and the commit named in the first line of each recorded transcript), delete target/simavr/*.hex, run the task, and copy target/simavr/<name>.transcript over the recorded transcripts, keeping their first comment line.

Real boards

Firmware is never committed. Build ESP-IDF’s hello_world example for the ESP32-S3:

cd $IDF_PATH/examples/get-started/hello_world
idf.py set-target esp32s3 build
mkdir -p <repository>/hardware/esp32-s3/firmware
cp build/bootloader/bootloader.bin build/hello_world.bin <repository>/hardware/esp32-s3/firmware/

Leave the default console configuration: the USB-Serial-JTAG secondary console must stay enabled, or the text Hello world! never reaches the port. hardware/*/firmware/ is ignored by git.

On the machine the boards are attached to, copy hardware/boards.example.toml to hardware/boards.toml (ignored by git) and fill one [[board]] per board: its name, the manifest (relative to the file), the serial port (the stable /dev/serial/by-id/... path) and the text expected on the port after a flash. Then run:

mise run test-hardware

For each board the test flashes with --record target/hardware/<name>-flash.transcript, checks the report is verified, reads the port for up to 15 seconds until expect appears, and runs nanoflash detect with --record target/hardware/<name>-detect.transcript, which must name the chip of the manifest. Transcripts worth keeping go next to the others in crates/nanoflash/tests/transcripts/<protocol>/ (the QEMU recordings are espressif/flash-esp32-qemu.transcript and espressif/flash-esp32c3-qemu.transcript; the emulator’s is samba/recorded/emulator-nano33ble.transcript).

The test is #[ignore]d: cargo test skips it, and it does nothing unless NANOFLASH_HARDWARE names the boards file.

Arduino Nano 33 BLE

Build the hello sketch (it prints Hello world! on the USB serial port every 500 ms):

arduino-cli core install arduino:mbed_nano
arduino-cli compile --fqbn arduino:mbed_nano:nano33ble \
  --output-dir hardware/nano33ble/firmware hardware/nano33ble/hello

This gives hardware/nano33ble/firmware/hello.ino.bin, linked at 0x10000, which hardware/nano33ble/manifest.toml flashes. Then add the arduino-nano-33-ble entry of hardware/boards.example.toml to hardware/boards.toml.

What a flash does: a 1200-baud touch on the sketch (2341:805a), up to 15 seconds for the bootloader (2341:005a) to appear, then N#, V#, I#, X, buffered S/Y writes per 4 KiB, Z (checksum) per 4 KiB, and K# (reset). If no bootloader appears, double-tap the reset button (the orange LED pulses) and pass the bootloader’s port. The test reopens the port for 15 seconds, which covers the sketch coming back after K#; its detect touches the sketch again.

The commands that replace bossac are in Migrate from esptool, bossac or avrdude.

Arduino AVR boards

One sketch serves the four boards: hardware/avr-hello/avr-hello.ino prints Hello world! at 115200 baud every 500 ms. Build it for each board you own; the hex file stays out of git (hardware/*/firmware/ is ignored):

arduino-cli core install arduino:avr
arduino-cli compile --fqbn arduino:avr:uno --output-dir hardware/uno/firmware hardware/avr-hello
arduino-cli compile --fqbn arduino:avr:nano:cpu=atmega328 --output-dir hardware/nano/firmware hardware/avr-hello
arduino-cli compile --fqbn arduino:avr:mega:cpu=atmega2560 --output-dir hardware/mega2560/firmware hardware/avr-hello
arduino-cli compile --fqbn arduino:avr:leonardo --output-dir hardware/leonardo/firmware hardware/avr-hello

Use arduino:avr:nano:cpu=atmega328old for a Nano with the old bootloader (57600 baud). nanoflash reads the avr-hello.ino.hex that arduino-cli writes (the manifests name firmware/avr-hello.ino.hex). Then add the entries of hardware/boards.example.toml for the boards you own to hardware/boards.toml; the test passes --protocol from the manifest to detect, so Nano clones whose USB bridge has no known identity are detected too.

What a flash does:

  • Uno, Nano (STK500v1): a DTR pulse resets the board into its bootloader, then sync (GET_SYNC), signature check, page writes, read-back and leave (the application starts). The Nano tries 115200 baud, then 57600.
  • Mega 2560 (STK500v2): the same pulse, then CMD_SIGN_ON, signature check, page writes (CMD_PROGRAM_FLASH_ISP), read-back and leave.
  • Leonardo (AVR109): a 1200-baud touch makes the sketch reset into Caterina, which shows up as a new serial port; nanoflash waits up to 7 seconds for it (Caterina itself stays in the bootloader for only 8 seconds). Then the S identifier, signature (s), block writes, read-back, and E to leave.

The Mega 2560 limits its application to 0x0..0x3C000 and the order of its images (hardware/mega2560/layout.toml): see What flash erases.

When the bootloader does not answer, press the reset button just before flashing (the Uno’s bootloader only listens for about a second after a reset). On the Leonardo, press reset once (the LED pulses) and pass the bootloader’s port within 8 seconds.

Recording: test-hardware records target/hardware/<name>-flash.transcript. Copy the ones worth keeping into crates/nanoflash/tests/transcripts/avr/recorded/, with a first comment line naming the board and its bootloader, and add a replay to the list of replays_the_simavr_recordings.

The commands that replace avrdude are in Migrate from esptool, bossac or avrdude.

Hardware workflow

.github/workflows/hardware.yml (Hardware, started by hand with workflow_dispatch) runs mise run test-hardware on a runner labelled self-hosted and nanoflash-hardware. Register the runner on the machine that has the boards, and build the firmware and write hardware/boards.toml in its checkout before a run.

Check the monitor and the runner

mise run test-hardware flashes boards only. Nothing in the loop runs nanoflash monitor, nanoflash run or an ELF image. Check them by hand with the Arduino Nano 33 BLE and the hello sketch above, before a registry release:

  1. Run nanoflash monitor --board hardware/nano33ble/manifest.toml. Expect Hello world! lines and exit with Ctrl-C. Then run it with --reset: the board restarts through its bootloader and the lines come back. Run it with --raw and type a key.
  2. From examples/nano33ble, run cargo run --release. Expect the flash report, the restart of the board and its serial output. The example prints nothing, so the check is that the command flashes and keeps the monitor open. Add -- --no-monitor to flash only.
  3. Run nanoflash monitor --elf <ELF file with defmt> on a firmware that uses defmt, and check that the frames are decoded.
  4. Run nanoflash flash with an ELF file as the image of the manifest, on one Espressif board and one SAM-BA board.

Check the browser package

The browser package (web/) is checked by hand against a board:

  1. Build the firmware as above.
  2. mise run web-demo serves the repository root on port 8000 and prints http://localhost:8000/web/demo/?manifest=/hardware/esp32-s3/manifest.json (the manifest hardware/esp32-s3/manifest.json is the JSON twin of manifest.toml); open it in Chrome or Edge.
  3. Press Install, pick the USB JTAG/serial debug unit port, and wait for done.
  4. Confirm Hello world! with nanoflash detect --port <port> and a serial terminal.

For the Nano 33 BLE, build its firmware as above and run mise run web-demo with ?manifest=/hardware/nano33ble/manifest.json (the JSON twin of its manifest.toml), pick the Nano’s port, then answer the second button with the bootloader’s port (2341:005a) when Chrome asks. The page asks for it once: Chrome remembers the grant, and the next Install finds the bootloader by itself.

For the AVR boards, build their firmware as above and run mise run web-demo with ?manifest=/hardware/uno/manifest.json, then ?manifest=/hardware/leonardo/manifest.json (answer the second button with the Leonardo bootloader’s port).

Develop and contribute

This page is for contributors. You need mise, which installs the pinned tools of mise.toml.

mise install

Before you push

ChangeRun
Any changemise run check (format, clippy, tests, cross builds for thumbv7em-none-eabihf and wasm32-unknown-unknown) and mise run deny (licences, advisories, bans and sources of the dependencies).
The build or cargo features, or examples/nano33blemise run example: builds the example firmware, checks with layout check --image that its ELF file fits the application partition, and checks that the linker refuses a memory.x that appears after a build.
The browser package, the web feature or nanoflash-webmise run web: builds the WebAssembly modules, checks their size, type-checks the package and runs its Node tests.
web/flashermise run pages: assembles the site in target/pages.

Other tasks:

TaskRole
mise run msrvBuilds the workspace with the minimum supported Rust version (1.95).
mise run featuresTests the library with each feature combination that matters.
mise run coverageWrites the coverage of the workspace to coverage.lcov.
mise run packagePackages every crate as crates.io would, and builds each one from its package.
mise run external-parsersChecks the Espressif partition table writer against ESP-IDF’s gen_esp32part.py.
mise run web-wasmBuilds the WebAssembly modules into web/src/wasm.
mise run web-sizeFails when a WebAssembly module is above 256000 bytes once compressed with gzip -9.
mise run web-testRuns the tests of the web package in Node, against a mocked Web Serial port.
mise run web-demoServes the demonstration page at http://localhost:8000/web/demo/.
mise run pages-serveServes the flasher site at http://localhost:8000/.
mise run test-qemu, test-samba-emulator, test-simavr, test-hardwareSee Run the hardware tests.

Rules of the code

  • Licence MIT OR Apache-2.0 on every crate.
  • The invariants of the library (no panic, bounded loops, no unsafe, no_std, features that only add code) are in Invariants. The example firmware follows the unsafe rule too.
  • No code from BOSSA, avrdude, Optiboot, Caterina, the Arduino bootloaders or simavr is copied. They are a behaviour reference or a test tool only.
  • Spell words out in identifiers, documentation and messages.
  • Conventional commits, from which release-plz makes the releases and the changelog.

AGENTS.md at the root of the repository has the full list of invariants.

Work on the flasher page

Run the page on your computer

$ mise run pages-serve

This builds the WebAssembly modules, checks their size, builds the package, the page and the guide, assembles the site in target/pages, and serves it at http://localhost:8000/. The flasher page is at http://localhost:8000/flasher/. Open the page through pages-serve: web/flasher/index.html alone does not work, because it needs flasher.css, flasher/ (the compiled page) and nanoflash/ (the compiled package) next to it.

mise run pages only assembles the site in target/pages: the guide at the root with sitemap.xml and robots.txt, and the flasher page in flasher/ with index.html, flasher.css, flasher/ (the compiled page), nanoflash/ (the compiled package without type declarations, with wasm/) and site.json.

Change the page

The page is in web/flasher, outside the npm package (files lists dist only).

  • npm run build:flasher compiles the page to web/flasher/dist (ignored by git), after npm run build. The tests web/test/flasher.test.mjs and web/test/flasher-page.test.mjs (the trust gate, in a simulated browser page) import that output. On a fresh checkout, run mise run web-test, which builds it, and not npm test alone.
  • index.html carries a Content Security Policy in a meta element. It contains the SHA-256 hash of the import map, and flasher.test.mjs fails when the hash is wrong. Change the import map and the hash together.
  • After a change to web/flasher, run mise run pages.

Release and publish describes the deployment.

Write the documentation

The guide is in docs/src, in four parts: tutorials, how-to guides, reference and explanation. docs/src/SUMMARY.md lists every page. Use relative links between pages.

Layout file

A layout file (TOML) describes the flash of one board: its size and its named partitions. The nanoflash command, the build feature and the browser package read the same file. Unknown keys are refused.

# layouts/esp32-s3-8mb.toml
[flash]
size = "8 MiB"
alignment = "4 KiB"          # default alignment of every partition
base-address = 0x0           # where flash is mapped, for the linker writer

[[partition]]
name = "bootloader"
role = "bootloader"
offset = 0x0
size = "32 KiB"

[[partition]]
name = "partition-table"
role = "partition-table"
offset = 0x8000
size = "4 KiB"

[[partition]]
name = "nvs"
role = "custom"
size = "24 KiB"
espressif = { type = "data", subtype = "nvs" }   # per-family attributes

[[partition]]
name = "application"
role = "firmware"
size = "3 MiB"
alignment = "64 KiB"

[[partition]]
name = "storage"
role = "storage"
filesystem = "littlefs"       # informative; drives the Espressif subtype
size = "remaining"            # shares what is left with the other growing partitions

Sizes and offsets

Sizes and offsets are integers (4096), hexadecimal integers or text (0x1000, "0x1000"), or text with a binary unit: B, KiB, MiB, GiB ("4 KiB", "8 MiB", "512 B").

[flash]

KeyRequiredValue
sizeyesThe flash size, or "detect": the size is read from the chip when flashing.
minimumwith size = "detect"A fixed size with a minimum is refused. The smallest flash that the layout supports. Offline tools (layout check, layout write, build, image build without --flash-size) resolve the layout for it.
alignmentnoThe default alignment of every partition. Default 4 KiB (0x1000).
base-addressnoThe address at which the flash is mapped, for the linker writer and for the addresses of Intel HEX and ELF images. Default 0x0.

[[partition]]

Partitions are listed in file order.

KeyRequiredValue
nameyesA name, unique in the layout. Images and erase entries of a manifest name it.
roleyesbootloader, partition-table, firmware, update, storage, crash-record or custom.
slotfor updateThe update slot number n.
offsetnoA fixed offset. Without it, the partition goes at the first offset after the previous partition that satisfies its alignment.
sizeyesA size, "remaining", or a table { minimum, grow, maximum }. See Growing sizes.
alignmentnoThe alignment of this partition. Default: the alignment of [flash].
filesystemnoInformative. On Espressif, fat, spiffs and littlefs select the subtype of a storage partition.
espressifnoAttributes of the Espressif partition table.
mbrnoAttributes of the MBR.
linkernoAttributes of the linker writer.

Roles

RoleMeaning
bootloaderThe bootloader.
partition-tableWhere the table writer puts its table. flash writes the generated table there unless a manifest image targets it.
firmwareThe application. nanoflash run writes its image to the one firmware partition.
updateAn update slot, with slot = <n>.
storageData, such as a file system.
crash-recordA crash record, such as a core dump.
customAnything else. On Espressif it needs explicit espressif attributes.

Per-family attributes

Per-family attributes live in a table named after the family. They override what the role implies.

TableKeys
espressiftype and subtype, by name (such as "data", "nvs", "phy", "ota", "coredump", "factory") or by number; encrypted and readonly, booleans.
mbrtype, the partition type byte; bootable, a boolean.
linkerregion, the name of the memory region.

The Espressif writer maps the roles like this: firmware to app/factory, update slot n to app/ota_n, storage to data with a subtype from filesystem, crash-record to data/coredump. Update slots require an otadata partition (espressif = { type = "data", subtype = "ota" }).

Growing sizes

A partition size is one of:

  • a size, such as "1 MiB";
  • "remaining", which is { minimum = 0, grow = 1 };
  • a table { minimum = "1 MiB", grow = 3, maximum = "8 MiB" }: at least minimum, plus a share of the free space weighted by grow (a whole number from 1, default 1), up to maximum (optional).
[flash]
size = "detect"                # read from the chip when flashing
minimum = "4 MiB"              # what offline tools resolve against

# in a partition: at least 1 MiB, three shares of the free space, at most 8 MiB
size = { minimum = "1 MiB", grow = 3, maximum = "8 MiB" }

Partitions that grow share the free space by weight, in steps that keep the partitions after them aligned. In a detect layout, fixed offsets must ascend in file order, and firmware and update partitions cannot grow. Growable partitions gives the rules and every error.

Table writers

nanoflash layout write --format <format> and writeLayout in the browser write:

FormatOutputNotes
espressifThe binary Espressif partition table, placed at the partition-table partition.Checked against esp-idf-part and gen_esp32part.py.
mbrA 512-byte master boot record.For SD cards and disk images. Sector size 512. Partition types come from the attributes or the role. Checked against mbrman and sfdisk.
linkerThe MEMORY regions of the layout (text).For families with no table on the flash, such as an nRF52840 behind a bootloader whose application starts at a fixed address.
constantsRust constants (text).The same constants as the build feature.

The linker regions and constants of a detect layout are written for its minimum flash. See Build and cargo features.

Board manifest

A board manifest lists the boards of a project, how to reset them and what to write to them. It is TOML or JSON with the same keys. The command tells them apart by their content. The browser reads JSON only: convert a TOML manifest to JSON with the same keys, with board as an array. Unknown keys are refused.

# boards/esp32-s3.toml
[[board]]
identifier = "esp32-s3-devkitc"            # selected with --board-identifier
name = "ESP32-S3-DevKitC"
protocol = "espressif"
chip = "esp32-s3"
layout = "../layouts/esp32-s3-8mb.toml"   # paths are relative to the manifest
reset = "espressif-usb-serial-jtag"
application-devices = [{ vendor = 0x303a, product = 0x1001 }]

[[board.image]]
partition = "bootloader"                  # or offset = 0x0
path = "../build/bootloader.bin"
sha256 = "d67c656e01756650d77717b0839985a056ec28ffe174601d690fc407a2ceffca"   # optional

[[board.image]]
partition = "application"
path = "../build/application.bin"

[[board.erase]]                           # optional: erased before writing
partition = "nvs"

Top level

KeyRequiredValue
boardyesThe boards, at least one. Each identifier is unique.
prompt-erasenotrue makes the web component offer a checkbox to erase the whole flash. Default false.

[[board]]

KeyRequiredValue
identifieryesThe board, as --board-identifier, boardIdentifier and board-identifier of the Cargo metadata name it.
namenoA name for people.
protocolyesespressif, samba, stk500v1 (alias arduino), stk500v2 (alias wiring) or avr109. The aliases are the names of Arduino’s boards.txt.
chipyesThe chip. See Supported boards.
layoutnoThe layout file, relative to the manifest, or a URL in the browser. Without a layout, images are placed by offset only.
resetnoThe reset sequence. See Reset sequences.
application-devicesnoThe USB identities of the board when it runs its application.
bootloader-devicesnoThe USB identities of the board in its bootloader, when they differ.
imagenoThe images to write.
erasenoThe regions to erase before writing.

A board needs at least one image or one erase entry to flash (nothing-to-flash). A manifest for nanoflash run may list no image: the runner supplies it.

Device filters

application-devices and bootloader-devices are lists of tables:

KeyRequiredValue
vendoryesThe USB vendor identifier, such as 0x2341.
productnoThe USB product identifier. Without it, any product of the vendor matches.
serial-numbernoThe USB serial number. Without it, any device matches. The browser package ignores it: Web Serial does not give the serial number.

The USB identity of the selected port picks the board among the boards of the manifest. The application and bootloader identities also let nanoflash find the board again after a reset that changes its USB identity (a 1200-baud touch). See How nanoflash works.

[[board.image]]

KeyRequiredValue
partitionone of the twoThe partition of the layout that the image goes to.
offsetone of the twoThe flash offset that the image goes to.
pathyesThe image file, relative to the manifest, or a URL in the browser. The command refuses URLs: download the file next to the manifest.
sha256noThe SHA-256 digest of the file, 64 hexadecimal digits. A file with another digest is refused.

Image formats:

  • Binary, written as it is.
  • Intel HEX (.hex, .ihex, by extension), as Arduino, PlatformIO and objcopy write it. It is decoded for every protocol, after the SHA-256 check and the verifier, which see the file as read. The image is the span from the lowest to the highest address, 0xFF in the gaps. Its lowest address is an address of the memory map: it must equal the offset of the image plus the base-address of the flash of the layout (misplaced-intel-hex). .eep files (EEPROM) are refused.
  • ELF, found by its content (the magic 7f 45 4c 46) whatever its name. It is decoded after the SHA-256 check, the verifier and the .eep refusal. The check for ELF content comes before the check for the .hex extension. A file named .elf that is not an ELF file is refused. Reading ELF files needs the elf feature of the library: without it, an ELF image is refused (elf-not-enabled). The command has it. The WebAssembly modules of the browser package do not.
    • For every protocol but Espressif, the image is the PT_LOAD segments that have file data, at their physical address (p_paddr, where .data is stored in the flash), from the lowest to the highest byte with 0xFF in the gaps, as for an Intel HEX image. The bytes that a segment has only in memory (.bss) are not written. The segments must not overlap and must lie in the flash window: from the base-address of the layout for the size of its flash, or without a layout, from 0 for the address limit of the protocol, spanning at most 32 MiB. The lowest address must equal the offset of the image plus the base-address (misplaced-elf). The segments of an AVR file from 0x800000 (the data, EEPROM, fuse and lock spaces of avr-gcc) are not written and are named in an elf-segments-not-written warning. This applies to the three AVR protocols and to any file whose machine is AVR.
    • On the Espressif protocol, the bootloader boots application images, not flat segments. The ELF file is checked, then the image source builds its application image through ImageSource::application_image. The default refuses (application-image). The file may go only to a firmware or update partition, or by offset to a board without layout, or to an offset that starts such a partition (elf-not-an-application). It goes at a multiple of 0x10000 and not below 0x10000 (misaligned-application-image). The check runs again after the layout is resolved for the chip. The image is placed by its partition, not by its addresses: it follows a detect layout like a binary image.
    • The nanoflash command builds the Espressif application image with espflash 4.7. It writes a partition table with one factory application partition, at the offset and with the size of the partition of the layout, to a temporary file in the temporary directory of the system (TMPDIR on Unix, TMP or TEMP on Windows), and removes the file afterward. A panic of espflash on a malformed ELF file becomes an error. The library, the browser package and other programs that use the library refuse, because they provide no application_image.

The partition table is generated from the layout and written with the images, unless an image replaces it.

[[board.erase]]

An erase entry names a partition, or an offset and a size (at least one byte), not both.

[[board.erase]]
partition = "nvs"

[[board.erase]]
offset = 0x9000
size = "24 KiB"

Reset sequences

ValueSequence
espressif-classicDTR and RTS through a UART bridge, as on most ESP32 boards.
espressif-usb-serial-jtagThe USB-Serial-JTAG peripheral of the ESP32-S3, ESP32-C3 and later chips.
touch-1200Open the port at 1200 baud and clear DTR: the sketch restarts into its bootloader, which appears as another USB device. SAM-BA and AVR109 boards.
uf2-touch-1200The same touch, for UF2 bootloaders, which no backend supports yet.
noneNo reset: the board is already in its bootloader.
{ custom = [...] }A list of steps, each { dtr = true, rts = false, wait = "100 ms" }. wait is a number of milliseconds or text such as "100 ms" or "2 s", at most 10 s.

Without reset, the backend chooses the usual sequence of its protocol: touch-1200 on SAM-BA and AVR109, and on Espressif espressif-usb-serial-jtag for the USB identity 303a:1001, else espressif-classic. The STK500 boards (Uno, Nano, Pro Mini, Mega 2560) are reset by a pulse on DTR. A sequence that does not apply to the protocol is refused (unsupported-reset).

Several boards in one manifest

A manifest may list several boards, of one protocol or of several. flash picks the one whose chip matches what the backend detects (as esp-web-tools does with chipFamily), or the one that --board-identifier names. A port that suits no board fails with no-matching-board, and one that suits boards of several protocols fails with several-protocols.

esp-web-tools manifests

An esp-web-tools manifest (JSON with builds[].chipFamily) is detected and converted on load:

  • protocol espressif, chip from chipFamily, one board per build;
  • images from parts, at their offsets, with path relative to the manifest or a URL;
  • no layout (offsets only);
  • the reset from serialType (cdc or uart) or from the detected port;
  • new_install_prompt_erase maps to the erase option of the web component (prompt-erase).

Only the fields that affect flashing are honoured. Improv Wi-Fi provisioning and home_assistant_domain are ignored. ESP8266 builds are refused with a clear error: the ESP8266 is not supported. The fields of the format are listed in Prior art and licences.

Command line

The nanoflash command checks and writes layouts, flashes boards, builds flash images and shows the serial output of a board. It has these subcommands:

nanoflash layout check [<layout>] [--image <partition>=<file>]... [--manifest <manifest>] [--board-identifier <identifier>] [--flash-size <size>] [--json]
nanoflash layout write <layout> --format espressif|mbr|linker|constants --output <file> [--flash-size <size>] [--json]
nanoflash flash [--board <manifest>] [--port <port>] [--board-identifier <identifier>] [--erase-all] [--no-verify] [--baud-rate <rate>] [--progress <format>] [--json]
nanoflash detect --port <port> [--protocol <protocol>] [--progress <format>] [--json]
nanoflash image build [--board <manifest>] [--board-identifier <identifier>] --output <file> [--fill] [--flash-size <size>] [--json]
nanoflash monitor [--port <port>] [--board <manifest>] [--board-identifier <identifier>] [--baud-rate <rate>] [--raw] [--reset] [--elf <file>] [--progress <format>] [--json]
nanoflash run <image> [--board <manifest>] [--board-identifier <identifier>] [--port <port>] [--erase-all] [--no-verify] [--baud-rate <rate>] [--flash-baud-rate <rate>] [--no-monitor] [--raw] [--progress <format>] [--json]

nanoflash --help and nanoflash <subcommand> --help print the options. nanoflash --version prints the version.

Common behaviour

  • No prompts. --port is required when more than one candidate port exists.
  • Errors go to standard error: each line of the message is printed as error: <line>, and the message has a hint when one helps. Every error message names the partitions and the addresses involved, in 0x hexadecimal.
  • --json prints one JSON document on standard output (one JSON object per line for monitor and run). A bad option with --json prints the bare error as JSON.
  • --progress human|json|quiet reports progress on standard error: one line per stage, one JSON object per event, or nothing. It is quiet with --json unless given.
  • Sizes such as --flash-size take an integer, hexadecimal or a number with a binary unit ("16 MiB").
  • Hidden options record and replay transcripts for the test suite: --record <file> on flash and detect records the session with real hardware, and --replay <file> replays one.
  • An argument that is not Unicode text is an input error on every platform but Unix, where arguments are bytes, as for a path.

Exit codes

CodeMeaning
0Success. Ctrl-C in monitor and run also exits with 0.
1Input error: an option, a file, a layout, a manifest, an image.
2Device or connection error. A device that does not come back to monitor within 30 s.
3Verification failure: the flash does not read back as written.

The board of the Cargo package

--board is optional on flash, image build, monitor and run. Without it, the board is the one that [package.metadata.nanoflash] of the Cargo.toml of the package names, and --board-identifier replaces its board-identifier. layout check without a layout file checks the layout of that board. See Build and cargo features for the keys and how the Cargo.toml is found. monitor works without a board: a Cargo.toml with no metadata is not an error there, unless --board-identifier is given.

nanoflash layout check

Checks a layout and prints the offset, size and headroom of every partition.

OptionMeaning
<layout>The layout file. By default the layout of the board of the Cargo package, or of --manifest.
--image <partition>=<file>An image written to a partition (binary, Intel HEX or ELF), to show its headroom. Repeatable. Conflicts with --manifest.
--manifest <manifest>A board manifest: check the images that it writes. Without a layout file, check the layout of its board. layout check warns when a manifest image of the partition table differs from the generated table.
--board-identifier <identifier>The board of the manifest, when several boards use different layouts. With a layout file, it needs --manifest: without it, the command fails with an input error.
--flash-size <size>Resolve a detect layout for this flash size. Refused for a fixed layout and below the minimum. Images are still checked against the partition sizes on the minimum flash, as flash does, so this option changes only the offsets, sizes and headroom shown.
--jsonPrint one JSON document instead of the table.
$ nanoflash layout check layouts/esp32-s3-8mb.toml
flash 8 MiB (0x800000), unallocated 4 KiB
name             role             offset    end       size      image  headroom
bootloader       bootloader       0x0       0x8000    32 KiB    -      -
partition-table  partition-table  0x8000    0x9000    4 KiB     -      -
nvs              custom           0x9000    0xf000    24 KiB    -      -
application      firmware         0x10000   0x310000  3 MiB     -      -
storage          storage          0x310000  0x800000  5056 KiB  -      -

For a detect layout, the report shows the minimum, adds the minimum and growth columns when a partition grows, and a line that names the partitions that move with the flash size:

$ nanoflash layout check layouts/esp32-s3-detect.toml --flash-size "8 MiB"
flash 8 MiB (0x800000), minimum 4 MiB (0x400000), unallocated 60 KiB
name             role             offset    end       size      minimum  growth     image  headroom
...
storage          storage          0x320000  0x800000  4992 KiB  0 B      +4992 KiB  -      -

nanoflash layout write

Writes a partition table, linker regions or Rust constants for a layout.

OptionMeaning
<layout>The layout file.
--format <format>espressif (binary partition table), mbr (binary master boot record), linker (linker memory regions, text) or constants (Rust constants, text).
--output <file>The file to write.
--flash-size <size>Resolve a detect layout for this flash size. The linker and constants formats refuse any size but the minimum.
--jsonPrint one JSON document instead of a sentence.

See Layout file for the formats.

nanoflash flash

Writes the images of a board to the device on a serial port.

OptionMeaning
--board <manifest>The board manifest (TOML or JSON). By default the board of the Cargo package.
--port <port>The serial port. By default the only one that suits the board.
--board-identifier <identifier>The board of the manifest to flash, when the device cannot tell. By default the one that the Cargo package names.
--erase-allErase the whole flash first, from the lowest offset that the bootloader writes to the end. A protected bootloader stays. On AVR, pages are programmed with 0xFF up to where the bootloader starts.
--no-verifyDo not check what was written (MD5, CRC-16 or read-back).
--baud-rate <rate>The baud rate to flash at. Default 460800 through a UART bridge on an Espressif board. USB-Serial-JTAG and the ESP32-C2 stay at 115200 baud whatever the value (Espressif). On STK500 it is the rate of the bootloader: STK500v1 tries 115200, then 57600; STK500v2 uses 115200 only. SAM-BA and AVR109 ignore it.
--progress <format>human, json or quiet.
--jsonPrint one JSON document instead of sentences.
$ nanoflash flash --board boards/esp32-s3.toml
connecting
writing at 0x0
writing at 0x8000
writing at 0x10000
verifying
resetting
flashed esp32-s3-devkitc (esp32-s3, 8 MiB)
  0x0  bootloader  21 KiB
  0x8000  partition-table  3 KiB
  0x10000  application  812 KiB
verified

With a layout whose flash size is detected, the warnings come before the report:

$ nanoflash flash --board boards/esp32-s3-detect.toml
...
warning: the chip has 0x800000 bytes of flash, more than the minimum of 0x400000 of the layout, so partitions grew: "storage" from 0xe0000 to 0x4e0000 bytes; the bootloader image must be built for this flash size or with flash size detection
flashed esp32-s3-devkitc-detect (esp32-s3, 8 MiB)

nanoflash detect

Connects to a device and tells what chip it is.

OptionMeaning
--port <port>The serial port. Required.
--protocol <protocol>espressif, samba, stk500v1 (alias arduino), stk500v2 (alias wiring) or avr109, when the USB identity of the device does not tell.
--progress <format>human, json or quiet.
--jsonPrint one JSON document instead of sentences.
$ nanoflash detect --port /dev/ttyACM0
protocol espressif
chip esp32-s3
flash 8 MiB
usb 303a:1001
secure download mode no

On SAM-BA and AVR boards, the output also has the lines writable from <offset> and writable to <offset>, before the usb line. detect resets the board into its application at the end.

nanoflash image build

Merges the images of a board into one flash image, 0xFF between them.

OptionMeaning
--board <manifest>The board manifest. By default the board of the Cargo package.
--board-identifier <identifier>The board of the manifest, when it has several.
--output <file>The file to write.
--fillPad the image to the flash size of the layout: the minimum of a detect layout, or --flash-size.
--flash-size <size>Build a detect layout for this flash size: the partition table is generated for it and the images go where their partitions then are. By default the minimum, because a merged image cannot follow the chip.
--jsonPrint one JSON document instead of a sentence.
$ nanoflash image build --board boards/esp32-s3.toml --fill --output flash.bin
wrote 8388608 bytes to flash.bin

nanoflash monitor

Shows what a board writes to its serial port and sends what you type.

OptionMeaning
--port <port>The serial port. By default the only one that suits the board, else the only USB serial port.
--board <manifest>The board manifest: its USB identities find the port, and --reset uses its protocol and reset sequence. By default the board of the Cargo package, if it names one.
--board-identifier <identifier>The board of the manifest, when it has several.
--baud-rate <rate>The baud rate of the serial output. Default 115200. 1200 is refused for a board whose reset is a 1200-baud touch.
--rawSend each key as the terminal encodes it, without waiting for the end of the line. Standard input must be a terminal. The terminal goes back to its state when the command ends.
--resetReset the board into its application first, through its bootloader. It needs the protocol of the board: pass --board, or use a port with a known USB identity.
--elf <file>Decode the defmt frames of this ELF file in the output. A file with no defmt table, or with the raw encoding, is an input error.
--progress <format>How to report the progress of --reset.
--jsonPrint one JSON object per line of output, with its time.

Behaviour:

  • Notes go to standard error. The output of the board goes to standard output, byte for byte.
  • In line mode (the default), each line of standard input goes to the board with \n at its end. When standard input ends, the monitor goes on showing the output.
  • Ctrl-C quits in both modes, and so does a signal, with exit code 0.
  • After it opens a port, the monitor clears DTR and RTS for an Espressif board and for a port with an unknown USB identity (a UART bridge), and sets DTR for a board with a known AVR or SAM-BA identity.
  • When the device leaves, the monitor waits up to 30 s for the same device and opens it again.
$ nanoflash monitor --board hardware/nano33ble/manifest.toml
monitoring /dev/ttyACM0 at 115200 baud; Ctrl-C quits
connected to /dev/ttyACM0
boot

JSON lines

With --json, standard output has one compact JSON object per line. Each has a timestamp (RFC 3339, UTC, milliseconds).

RecordFields
A line of outputline. "complete": false is added for output that ended without a line feed.
connected eventevent, port.
disconnected eventevent.
error eventevent, errors. A failure is the last line.
A defmt framedefmt: level, message, device_timestamp, location (file, line, module, or null without debug information).
malformed_defmt_frame eventevent.
$ nanoflash monitor --port /dev/ttyACM0 --json
{"timestamp":"2026-11-24T09:30:01.250Z","event":"connected","port":"/dev/ttyACM0"}
{"timestamp":"2026-11-24T09:30:01.412Z","line":"boot"}
{"timestamp":"2026-11-24T09:30:09.870Z","event":"disconnected"}

defmt frames

A frame is shown on its own line as [INFO ] message (file:line). The location is shown only when the ELF file has debug information for the statement. The timestamp of the firmware, if it defines one, comes first. A frame that cannot be decoded is shown as [MALFORMED defmt frame]. See Decode defmt logs and The serial monitor and defmt.

nanoflash run

Flashes an application, then shows what it writes to its serial port: a runner for Cargo.

OptionMeaning
<image>The firmware to flash: the ELF file that Cargo builds, or a binary or Intel HEX image. Options may come before or after it.
--board <manifest>The board manifest. The image replaces the one of its firmware partition. By default the board of the Cargo package.
--board-identifier <identifier>The board of the manifest, when it has several.
--port <port>The serial port. By default the only one that suits the board.
--erase-allAs for flash.
--no-verifyAs for flash.
--baud-rate <rate>The baud rate of the serial output. Default 115200.
--flash-baud-rate <rate>The baud rate to flash at, as --baud-rate of flash, with the same exceptions.
--no-monitorOnly flash. The output is then the output of flash.
--rawAs for monitor. Conflicts with --no-monitor. The command checks for a terminal before it flashes.
--progress <format>How to report the progress of flashing.
--jsonOne JSON document with --no-monitor, else one JSON object per line. The first line is the event flashed with the report of flash --json.

Behaviour:

  • The image replaces the application image of the board. With a layout, this is the image of the one partition with the role firmware (by name or by offset); the image is added when the manifest has none. Without a layout, it is the only image of the board. The new image targets the partition by name, has the absolute path of the file and has no digest, because the file changes at every build.
  • A layout with no firmware partition or with several, a manifest with several images for the firmware partition, and a board without layout that lists no image or several images, are input errors that name the board, the partitions and the offsets.
  • flash resets the board into its application, so the monitor does not reset it again. It opens the application-devices of the board, else the exact USB identity that the port had before flashing, else the path of the port when it has no USB identity, and waits up to 30 s.
  • When the board starts in its bootloader and lists no application-devices, the identity is the one of the bootloader, and the application never matches it: the monitor waits 30 s and fails. List the application-devices of the board to avoid it.
  • When the image is an ELF file with a defmt table, the monitor decodes the defmt frames. When the table cannot be used, run writes a note on standard error and does not decode.
$ nanoflash run firmware.elf --board boards/nano33ble.toml --json
{"timestamp":"2026-11-30T09:30:01.250Z","event":"flashed","report":{"board":"arduino-nano-33-ble",...}}
{"timestamp":"2026-11-30T09:30:03.011Z","event":"connected","port":"/dev/ttyACM0"}
{"timestamp":"2026-11-30T09:30:03.412Z","line":"hello from the sketch"}

cargo nanoflash

cargo-nanoflash is the same command under the name that Cargo looks for to run a subcommand. Cargo runs cargo-nanoflash nanoflash <arguments>. The binary drops the first argument when it is exactly nanoflash, once, then runs the command. Run directly, without that name, it behaves alike. The output, the errors and the exit codes are those of nanoflash, --help, --version and a bad option with --json included, because both binaries call the same function. Cargo sets no variable for a subcommand, so the package is found from the working directory.

cargo nanoflash flash only flashes. It does not build the firmware.

Errors and warnings

Every failure of the library has a kind and a class. The command prints the message, with its hint when it has one, and --json gives the kind and the fields. The browser package throws a NanoflashError with the same kind, its errorClass, the message and the fields in details. Every message names the partitions and the addresses involved, in 0x hexadecimal.

Classes

The class tells who can fix the error. It also gives the exit code of the command.

ClassWho actsExit code
inputFix the options, the manifest, the layout or the images.1
deviceCheck the device, its connection or its bootloader.2
verificationThe flash does not hold what was written.3

Error kinds

Input

KindMeaning
unsupported-resetThe reset sequence does not apply to the protocol.
out-of-rangeA value does not fit what the protocol can carry.
manifestThe manifest could not be read.
layoutThe layout of a board has errors.
layout-fileThe layout file of a board could not be read or parsed.
tableThe partition table cannot be written for the layout.
image-sourceAn image file could not be read.
checksum-mismatchAn image does not have the SHA-256 digest that the manifest gives.
image-rejectedThe verifier of the caller refused an image.
intel-hexAn Intel HEX image is invalid.
misplaced-intel-hexA valid Intel HEX image does not start where it is written. Its addresses are those of the memory map: the base address of the flash plus the offset that it is written at.
elf-not-enabledAn image is an ELF file, and this build of nanoflash does not read ELF files (the elf feature).
elfAn ELF image cannot be flashed.
misplaced-elfA valid ELF image does not start where it is written.
application-imageThe image source could not build the Espressif application image of an ELF file.
elf-not-an-applicationAn ELF image is written where the Espressif bootloader does not boot an application from: a partition that is not a firmware or update partition, or an offset that starts no partition of the layout.
misaligned-application-imageThe Espressif application image of an ELF file is written at an offset that is not a multiple of 0x10000, or below 0x10000.
image-needs-layoutAn image goes to a partition and the board has no layout.
unknown-partitionAn image or an erase entry names a partition that the layout does not define.
misaligned-imageAn image starts at an offset that the flash cannot erase from.
overlapping-imagesTwo images share flash sectors.
image-too-largeAn image does not fit in its partition.
partition-table-image-for-detected-flashAn image replaces the partition table of a layout whose partitions grow or move with the flash of the chip. The table that nanoflash generates for the chip would be lost.
fixed-offset-on-moving-partitionAn input tied to flash offsets (an image or an erase entry given by offset, an Intel HEX image, an ELF image decoded into flat segments) overlaps a partition that moves with the flash of the chip.
image-outside-flashAn image ends after the end of the flash.
misaligned-eraseAn erase entry does not start and end on the erase unit of the flash.
erase-outside-flashAn erase entry ends after the end of the flash of the layout.
outside-address-rangeAn image or an erase entry ends beyond what the protocol can address.
outside-detected-flashAn image or an erase entry ends after the end of the flash that the chip reports.
nothing-to-flashThe board of the manifest lists no image and no erase entry.
empty-imageAn image file has no byte.
out-of-memoryThere is not enough memory for a buffer.
unknown-boardThe requested board is not in the manifest.
no-matching-boardNo board of the manifest suits the device.
several-protocolsThe candidate boards speak several protocols. Give the board identifier.
several-boardsSeveral boards have the detected chip.
board-requiredThe manifest has several boards and none was chosen.
protocol-requiredThe protocol of the device cannot be told from its USB identity and none was given.
protocol-not-enabledThe protocol was not compiled in.
unknown-flash-sizeThe size of the flash is needed, and neither the layout nor the chip gave it.
flash-size-needs-detect-layoutA flash size was given for a board whose layout does not have size = "detect".
flash-too-smallThe flash of the chip is smaller than the layout.
unknown-bootloader-deviceThe USB identity that the bootloader of a device shows is unknown, so the device cannot be opened again after the reset.
below-writable-flashAn image or an erase entry starts in the flash that the bootloader protects.
above-writable-flashAn image or an erase entry ends in the flash that the bootloader occupies at the top of the flash.
erase-short-of-flash-endAn erase region stops before the end of flash, and the bootloader only erases from an offset to the end of flash (SAMD21).
image-below-writtenAn image comes after an image written above it, and the bootloader erases from the start of an image to the end of flash before it writes it (SAMD21).
page-out-of-erase-orderA page would be programmed where the bootloader does not erase it first. The wiring bootloader of the Mega 2560 erases one page per page programmed, in order from 0x0, wherever the programmed page goes.
not-connectedA backend was asked to erase, write, verify or reset before a successful connect.

Device

KindMeaning
transportThe serial port failed.
no-responseThe board did not answer a command.
no-syncThe board answered no SYNC after any reset.
not-in-download-modeThe boot log shows that the chip started in another mode than download mode.
romThe ROM loader refused a command.
invalid-responseThe board answered a command with something that cannot be its answer.
unknown-chipThe chip could not be identified.
unsupported-chipThe chip was identified, and nanoflash does not support it.
wrong-chipThe chip found is not the one of the selected board.
no-bootloaderNo bootloader answered: none appeared after the reset, or the port is not one.
unsupported-bootloaderThe bootloader lacks the commands that nanoflash needs.

Verification

KindMeaning
verification-failedThe flash does not hold what was written (MD5 or CRC-16).
read-back-differsThe flash read back differs from what was written (AVR).

Transport errors

A transport error (class device) carries the error of the serial port in its error field:

KindMeaning
ioThe operating system or the browser reported an error.
disconnectedThe device went away.
not-foundNo device matches the filter.
not-grantedThe browser has no permission for a device that matches the filter.
replayA replayed transcript diverged from what the host did (tests only).

The browser package gives a transport error the kind of the transport error inside it, such as not-granted or disconnected.

Browser package only

KindClassMeaning
no-port-choseninputThe user closed the port chooser.
port-request-refusedinputThe browser did not show the port chooser. A page in an iframe needs allow="serial", and a permissions policy may block Web Serial.
module-brokendeviceA WebAssembly module trapped. Every later call that needs the module fails with the same error. Reload the page.
invalid-argumentinputAn argument of a layout function does not parse, such as a flashSize text.
internaldeviceThe module threw something that is not an error of the library.

Warnings

A warning does not stop the flash. The report lists the warnings of the image preparation, then the warnings of a detect layout, then erases-to-end, then not-verified-in-secure-download-mode.

KindMeaning
partition-table-differsAn image of the manifest replaces the partition table that nanoflash generates from the layout, and differs from it.
partition-table-not-checkedAn image of the manifest replaces the partition table, and the table could not be generated from the layout to compare with.
not-verified-in-secure-download-modeThe chip is in secure download mode, whose ROM loader refuses SPI_FLASH_MD5: what was written was not read back.
erases-to-endThe bootloader (SAMD21) erased from the lowest image, from, to the end of flash, to. partitions are those of the layout in that range that no image is written to.
partitions-grewThe chip has more flash than the minimum of a detect layout, and the partitions that grow with the flash are larger than on the minimum. On Espressif, the bootloader image must be built for this flash size or with flash size detection.
partitions-movedThe chip has more flash than the minimum of a detect layout, and the partitions that move with the flash start elsewhere than on the minimum.
flash-size-not-detectedThe chip did not report its flash size: a detect layout stays resolved for its minimum.
elf-segments-not-writtenAn ELF image has loadable segments that are not part of the program memory of the chip (on AVR, the data, EEPROM, fuse and lock spaces from 0x800000). They are not written.

layout check also warns when a manifest image of the partition table differs from the generated table.

Supported boards and protocols

nanoflash flashes these chips natively and in the browser. Each protocol is one backend and, in the browser, one WebAssembly module (the three AVR protocols share the avr module).

Summary

Protocol (protocol =)Chips (chip =)BoardsVerifyImages
espressifesp32, esp32-s2, esp32-s3, esp32-c2, esp32-c3, esp32-c5, esp32-c6, esp32-h2, esp32-p4Any board with an Espressif chip, through its ROM loaderMD5Binary, Intel HEX, ELF (application image)
sambanrf52840Arduino Nano 33 BLECRC-16 (Z)Binary, Intel HEX, ELF
sambasamd21g18a, samd21j18a, samd21e18aArduino SAMD21 boards, such as the MKR WiFi 1010CRC-16 (Z)Binary, Intel HEX, ELF
stk500v1 (alias arduino)atmega328pArduino Uno, Nano, Pro Mini (Optiboot, ATmegaBOOT)Read-backBinary, Intel HEX, ELF
stk500v2 (alias wiring)atmega2560Arduino Mega 2560 (the wiring bootloader)Read-backBinary, Intel HEX, ELF
avr109atmega32u4Arduino Leonardo, Micro, Pro Micro (Caterina)Read-backBinary, Intel HEX, ELF

The browser package reads binary and Intel HEX images only: its WebAssembly modules do not have the elf feature. The ESP8266 is not supported. USB DFU, UF2, CMSIS-DAP (in the command only) and Nordic serial DFU are planned.

Espressif

  • The board resets into its ROM loader through DTR and RTS (espressif-classic, through a UART bridge) or through the USB-Serial-JTAG peripheral (espressif-usb-serial-jtag, USB identity 303a:1001).
  • The default baud rate is 460800 through a UART bridge. USB-Serial-JTAG and the ESP32-C2 stay at 115200 baud. When the caller asks for another rate on one of them, the flash goes on at 115200 baud and nanoflash reports a note with the reason. The USB-Serial-JTAG peripheral has no baud rate. The ESP32-C2 ROM loader computes its rates for a 40 MHz crystal, which many boards replace with a 26 MHz one. A request for 115200 baud gives no note.
  • Writes are compressed, except on the ESP32. No flasher stub is used: the ROM supports compressed writes and MD5.
  • In secure download mode, the ROM refuses SPI_FLASH_MD5, so what was written is not read back (not-verified-in-secure-download-mode).
  • An ELF image goes to a firmware or update partition at a multiple of 0x10000. The command turns it into an application image with espflash 4.7. The library and the browser package refuse ELF images on Espressif.
  • With a detect layout, build the bootloader for the flash size or with flash size detection.

SAM-BA (Arduino Nano 33 BLE, SAMD21)

  • A 1200-baud touch on the port of the sketch starts the bootloader, which appears as another USB device. The Nano 33 BLE goes from 2341:805a to 2341:005a. nanoflash waits up to 15 s for it.
  • nanoflash writes and checks the images with CRC-16, then resets into the application.
  • The bootloader at the start of flash is never written. writable_from is 0x10000 on the Nano 33 BLE and 0x2000 on the SAMD21 boards.
  • The SAMD21 bootloader erases more than it writes. What flash erases describes it.
  • --baud-rate is ignored.

AVR (Arduino Uno, Nano, Mega 2560, Leonardo)

  • Arduino’s AVR boards take the .hex file that the Arduino IDE builds.
  • STK500v1 (Uno, Nano, Pro Mini): a pulse on DTR resets the board into Optiboot or the older ATmegaBOOT. nanoflash tries 115200 baud, then 57600 (the old Nano bootloader).
  • STK500v2 (Mega 2560): the same pulse resets the board into the wiring bootloader, at 115200 baud only. It never erases above 0x3BFFF, so the application ends at 0x3C000, and its erase order limits the order of the images (What flash erases).
  • AVR109 (Leonardo, Micro, Pro Micro): a 1200-baud touch starts Caterina, which shows up on its own port (2341:8036 becomes 2341:0036 on a Leonardo). Caterina goes back to the sketch 8 s after the touch, so nanoflash waits 7 s for it natively and 5 s in the browser. --baud-rate is ignored.
  • Pages are written whole and read back to check them. The bootloader at the top of the flash is never written: writable_to is 0x7E00 on an Uno with Optiboot.
  • The bootloaders have no usable chip erase, so “erased” means “programmed with 0xFF”.

USB identities that detect knows

Without --protocol, detect picks the protocol from the USB identity of the port:

USB identityProtocol
Uno: 2341:0043, 2341:0001, 2a03:0043, 2341:0243, 2341:006a and kinstk500v1
Mega 2560: 2341:0010, 2341:0042 and their 2a03 and 02xx variantsstk500v2
Leonardo, Micro and other ATmega32U4 boards: 2341:8036, 2341:0036 and kin, with Adafruit’s and SparkFun’savr109
Any other product of vendor 0x2341samba
Vendor 0x303aespressif

A Nano or a Pro Mini behind a serial bridge (FTDI, CH340) has no known identity: pass --protocol, or a board manifest whose board lists no devices.

Library

The crate nanoflash is the library behind the command and the browser package. It is no_std with alloc, and it builds for thumbv7em-none-eabihf and wasm32-unknown-unknown with every no_std feature. The API documentation is on docs.rs. Add the crate from crates.io:

[dependencies]
nanoflash = { version = "0.1", features = ["toml", "flash", "espressif", "native"] }

Features

No feature is enabled by default. Every feature only adds code.

FeatureEnablesNeeds std
tomlReading layout files and board manifests from TOML.no
jsonReading board manifests from JSON, and esp-web-tools manifests.no
table-espressifThe Espressif partition table writer.no
table-mbrThe MBR writer.no
table-linkerThe linker regions and Rust constants writer.no
flashThe backend interface, its errors and progress events, image preparation and checks, shared by every protocol. Implies toml and table-espressif.no
espressifThe Espressif ROM loader backend. Implies flash.no
sambaThe SAM-BA backend of the Arduino Nano 33 BLE and SAMD21 boards. Implies flash.no
avrThe STK500v1, STK500v2 and AVR109 backends of Arduino’s AVR boards. Implies flash.no
elfReading the loadable segments of ELF images, over the object crate. Implies flash.no
testingTranscript replay and recording transports, and MemorySource.no
nativeThe host serial port over the serialport crate, and port listing.yes
webThe serial port of the browser over Web Serial, through hand-written wasm-bindgen bindings, without web-sys. No web_sys_unstable_apis flag is needed downstream.no
buildConstants and linker regions for the build.rs of a firmware. Implies toml, json, table-linker and cargo.yes
cargoThe board that [package.metadata.nanoflash] of a Cargo.toml names. Implies toml.yes

A function that needs a missing feature refuses with an error instead of failing to compile in two places: Backends::new returns protocol-not-enabled for a protocol whose feature is off, and image preparation returns elf-not-enabled for an ELF image without the elf feature.

Modules

ModuleFeatureRole
layoutLayout files, their resolution and report.
tabletable-*The table writers.
quantitySizes and offsets as integers, hexadecimal or numbers with a binary unit.
manifestBoard manifests (TOML, JSON) and esp-web-tools manifests (json).
transportThe SerialPort and PortProvider traits, DeviceFilter, transport errors.
backend, errorflashThe Backend trait, progress events, the errors and their class.
flashflashBoard selection, image preparation and checks (Intel HEX for every protocol, ELF decoded into flat segments or built into Espressif application images by the image source), the flash and detect orchestration, image_build.
espressifespressifThe ROM loader backend: SLIP, commands, chip table, resets, writes.
touchsamba or avrThe 1200-baud touch that SAM-BA and AVR109 share, and the bootloader device to wait for after it.
sambasambaThe SAM-BA backend of Arduino’s bootloaders: the ASCII commands with Arduino’s X, Y and Z, the chip families, writes and CRC-16 checks.
avravrThe AVR backend: the chip table, the commands of the STK500v1 (Optiboot, ATmegaBOOT), STK500v2 (Mega 2560) and AVR109 (Caterina) bootloaders, page writes and read-back checks, and the erase order of the Mega 2560.
nativenativeThe host serial port over serialport.
webwebThe serial port of the browser over Web Serial, and the provider that finds a device again among the granted ports.
testingtestingTranscript replay and recording, MemorySource.
buildbuildConstants and linker regions for a build.rs, from a layout file or from the board of the package, and a whole memory.x. See Build and cargo features.
cargocargoFinding the package from the Cargo variables or the working directory, reading the metadata, the layout of a board manifest.

Transport traits

#![allow(unused)]
fn main() {
pub trait SerialPort {
    /// Waits up to `timeout`; returns 0 when nothing arrived.
    async fn read(&mut self, buffer: &mut [u8], timeout: Duration) -> Result<usize, TransportError>;
    async fn write(&mut self, data: &[u8]) -> Result<(), TransportError>;
    async fn set_baud_rate(&mut self, baud_rate: u32) -> Result<(), TransportError>;
    async fn set_signals(&mut self, signals: Signals) -> Result<(), TransportError>; // DTR, RTS
    async fn sleep(&mut self, duration: Duration);
    fn identity(&self) -> Option<UsbIdentity>; // vendor, product, serial number
}

/// Finds or opens a port again, for resets that change the USB device (1200-baud touch,
/// USB-Serial-JTAG).
pub trait PortProvider {
    type Port: SerialPort;
    async fn open(&mut self, filter: &DeviceFilter, baud_rate: u32, timeout: Duration) -> Result<Self::Port, TransportError>;
    /// How long to wait for Caterina after a touch; 7 s by default.
    fn caterina_reopen_timeout(&self) -> Duration;
}
}

Public traits with async fn carry #[allow(async_fn_in_trait)] and have no Send bound, because browser APIs are single-threaded.

Backend trait

#![allow(unused)]
fn main() {
pub trait Backend {
    async fn connect(&mut self) -> Result<ChipInformation, Error>; // reset into the bootloader, detect
    async fn erase(&mut self, region: Region, progress: &mut dyn Progress) -> Result<(), Error>;
    async fn write(&mut self, segments: &[Segment<'_>], progress: &mut dyn Progress) -> Result<(), Error>;
    async fn verify(&mut self, segments: &[Segment<'_>], progress: &mut dyn Progress) -> Result<(), Error>;
    async fn reset_to_application(&mut self) -> Result<(), Error>;
    /// The whole flash in the order that `flash` sends it, before the first erase; `Ok` by default.
    fn check_plan(&self, erase_all: Option<Region>, erases: &[Region], segments: &[Segment<'_>]) -> Result<(), Error>;
}
}

ChipInformation, which connect returns, gives the protocol, the chip, the flash size, the secure download mode, the USB identity, writable_from (the lowest offset that the bootloader writes), writable_to (the end of the flash that the bootloader writes) and erases_to_end.

Hooks of the caller

TraitRole
ImageSourceReads the bytes of an image: files natively, fetch in the browser. With the elf feature, application_image builds the Espressif application image of an ELF file; the default refuses (application-image).
ImageVerifierCalled after the SHA-256 check, for signatures or anything else. () accepts every image.
ProgressReceives the progress events: stage, offset, bytes done and total.

Invariants

  • No panic on any input or device answer: checked arithmetic for every offset and size (u64), no indexing that can fail, no unwrap outside tests, fallible allocation for buffers sized by the input.
  • Every loop that waits on a device is bounded: attempt counts, inactivity timeouts passed to SerialPort::read, byte budgets.
  • #![forbid(unsafe_code)] in every crate.
  • The library is #![no_std] with extern crate alloc. Only the build, cargo and native features enable std.
  • Features only add code. default = []. A function that needs a missing feature returns an error (for example ProtocolNotEnabled).

Build and cargo features

The build feature gives the build.rs of a firmware the constants and linker regions of its layout. The cargo feature reads the board that the Cargo.toml of a package names. The command uses the same metadata. Generate memory.x and layout constants shows the steps.

The board of the package

# Cargo.toml
[package.metadata.nanoflash]
board = "boards/nano33ble.toml"     # the board manifest, relative to this Cargo.toml
# board-identifier = "arduino-nano-33-ble"   # the board of the manifest, when it has several
KeyRequiredValue
boardyesThe path of a board manifest (TOML or JSON, told apart by its content), relative to the directory of the Cargo.toml that holds it.
board-identifiernoThe board of the manifest. --board-identifier of the command replaces it.

Other keys are refused. The layout of the board is the layout file, relative to the manifest. Without board-identifier, all boards of the manifest must use the same layout.

How the Cargo.toml is found

  1. The Cargo.toml that CARGO_MANIFEST_PATH names, else the one in CARGO_MANIFEST_DIR. Cargo sets both for the runner of cargo run (CARGO_MANIFEST_PATH only in recent versions) and keeps the working directory.
  2. Else the nearest Cargo.toml from the working directory upwards.

The first Cargo.toml found decides. A virtual workspace, a package without the table, and a Cargo.toml above one that has no table, all name no board. The message names the Cargo.toml that was read and the table to add. [workspace.metadata.nanoflash] is not read.

cargo nanoflash does not set the Cargo variables, so it finds the package from the working directory. A build script reads the Cargo.toml in CARGO_MANIFEST_DIR.

The build feature

[build-dependencies]
nanoflash = { version = "0.1", features = ["build"] }

The dependency comes from crates.io. Build::package and Build::memory exist since version 0.1.0. The example firmware examples/nano33ble uses a path dependency, so that CI builds it against the library of the same commit.

Functions

FunctionRole
nanoflash::build::generate(path)Build::layout(path).generate().
Build::layout(path)Use a layout file. A relative path is relative to the package directory.
Build::package()Use the layout of the board that [package.metadata.nanoflash] names in the Cargo.toml in CARGO_MANIFEST_DIR.
Build::memory(name, origin, length)Add a memory region that is not a partition, such as the RAM, and write the whole memory.x. Repeatable.
Build::generate()Write the files to OUT_DIR, print cargo:rerun-if-changed for every input, and add OUT_DIR to the linker search path.
Build::generate_into(package_directory, output_directory)Write the files to output_directory, without the environment and without printing.

generate fails the build with the same errors as layout check. BuildError prints the same text with Debug and Display, so a build script that unwraps the error shows the message of nanoflash layout check.

Generated files

FileContent
nanoflash_layout.rsThe Rust constants, to include! from the firmware.
nanoflash_memory.xThe MEMORY regions of the layout, for a memory.x that includes it.
memory.xWith memory: one MEMORY block, the regions of nanoflash_memory.x, then the regions given. It ends with __nanoflash_memory_x = 1;.
nanoflash_memory_guard.xWith memory: a linker script that fails the link when another memory.x was linked. generate prints cargo:rustc-link-arg-bins=-T<this file>.

generate prints cargo:rerun-if-changed for the layout. With Build::package(), it also prints it for the Cargo.toml of the package and for the board manifest. When memory is not called, generate removes the memory.x and the guard that an earlier build left in OUT_DIR.

Constants

#![allow(unused)]
fn main() {
// src/main.rs
include!(concat!(env!("OUT_DIR"), "/nanoflash_layout.rs"));
}

The constants are u32 when every value fits, else u64. For a fixed layout:

#![allow(unused)]
fn main() {
pub const FLASH_SIZE: u32 = 0x0010_0000;
pub const FLASH_BASE_ADDRESS: u32 = 0x0000_0000;
pub mod application {
    pub const OFFSET: u32 = 0x0001_0000;
    pub const SIZE: u32 = 0x000E_0000;
    pub const ADDRESS: u32 = 0x0001_0000;
}
}

Each partition is a module named after it, in lower case, with every character that a Rust identifier cannot hold replaced by _. A name that starts with a digit gets the prefix partition_, self, super and crate get the suffix _partition, and other keywords become raw identifiers (r#type).

With size = "detect", the files describe what the firmware can count on with any flash, so they are written for the minimum flash of the layout:

  • FLASH_MINIMUM_SIZE replaces FLASH_SIZE.
  • A partition that grows with the flash (a remaining or { grow } size in the last segment) has MINIMUM_SIZE instead of SIZE: its size on the minimum flash, which is the least that it has on any device. Its linker region has that length.
  • A partition that moves with the flash has no OFFSET, no ADDRESS and no linker region. A firmware that uses them fails to compile or to link instead of writing at the wrong place.
  • A partition that does both has MINIMUM_SIZE only.
  • The other partitions keep OFFSET, SIZE and ADDRESS.

See Growable partitions.

Linker regions

The region of a partition is its linker.region attribute, else FLASH for the firmware partition, else its name in upper case with every character other than ASCII letters, digits and _ replaced by _.

A region given to memory must have a valid name (ASCII letters, digits and _, not starting with a digit), must be given once, and must not have the name of a region of the layout. Otherwise the build fails and names the region (TableError::InvalidRegionName, TableError::RepeatedRegion, TableError::DuplicateRegion).

With memory, generate refuses a memory.x in the workspace root or in the package directory (BuildError::MemoryScriptShadowed). How the generated memory.x is protected explains the checks.

Browser API

The npm package nanoflash exports a TypeScript API with no runtime dependency, and nanoflash/button registers the <nanoflash-button> element. Use the browser package shows how to use them.

Functions

ExportRole
isSupported(): booleanWhether the browser has Web Serial.
prepare(manifestUrl): Promise<Prepared>Reads the manifest and starts to load the WebAssembly module. Call it before the click.
detect({ protocol, port?, onProgress? }): Promise<ChipInformation>Tells what chip the device on a port is. Without port, asks the user to choose one.
checkLayout(text, images, name?, options?): Promise<LayoutReport>Checks a layout. images is a list of { partition, size }.
writeLayout(text, format, name?, options?): Promise<Uint8Array>Writes a table: "espressif", "mbr", "linker" or "constants".
loadBackend(protocol): Promise<BackendModule>Imports the WebAssembly module of a protocol.
NanoflashErrorThe class of every failure.
camelize, fromWasmHelpers that turn the values of the library into the types of the package.

protocol is "espressif", "samba", "stk500v1", "stk500v2" or "avr109". The three AVR protocols share the avr module.

Prepared

MemberValue
manifestUrlThe URL of the manifest. Paths in the manifest are resolved against it.
protocolsThe protocols of the boards.
filtersFilters for requestPort: the devices of the boards. Empty when any board lists none.
bootloaderFiltersThe devices of the boards in their bootloader (bootloader-devices).
promptEraseWhether to offer to erase the whole flash (prompt-erase, new_install_prompt_erase).
flash(options?): Promise<FlashReport>Asks the user to choose a port, filtered by the devices of the manifest, before its first await, then flashes.

FlashOptions

OptionValue
portThe port to use. Without it, the user is asked to choose one.
boardIdentifierThe board of the manifest to flash. Without it, the board that the chip is.
eraseAllErase the whole flash first.
verifyRead back and check what was written. Default true.
baudRateThe baud rate to flash at. USB-Serial-JTAG boards and the ESP32-C2 stay at 115200 baud (Espressif).
onProgress(event)Receives a ProgressEvent: stage (connecting, erasing, writing, verifying, resetting), offset, done and total in bytes.
onMessage(text)Receives the notes of the library, and the warnings about the flash size.

FlashReport

FieldValue
boardThe identifier of the board.
chipThe ChipInformation.
imagesThe images written: label, offset, size.
verifiedWhether the flash was read back and checked.
warningsA list of warnings, each with a kind and the message to show.

Warning kinds and their fields:

KindFields
partition-table-differspartition
partition-table-not-checkedpartition
not-verified-in-secure-download-mode
erases-to-endfrom, to, partitions
partitions-grewflashSize, minimumFlashSize, partitions (each name, sizeAtMinimum, size), protocol
partitions-movedflashSize, minimumFlashSize, partitions (each name, offsetAtMinimum, offset)
flash-size-not-detectedminimumFlashSize

See Errors and warnings for their meaning.

ChipInformation

FieldValue
protocolThe protocol.
chipThe chip, such as esp32-s3.
flashSizeThe flash size in bytes, or null when the chip does not tell.
secureDownloadModeWhether an Espressif chip is in secure download mode.
usb{ vendor, product, serialNumber }, or null.
writableFromThe lowest offset that the bootloader writes, when it protects the flash below it: 0x10000 on the Nano 33 BLE, 0x2000 on the SAMD21 boards. Nothing below it is written or erased.
writableToThe end of the flash that the bootloader writes, where an AVR bootloader starts: 0x7e00 on an Uno. Nothing at or above it is written.
erasesToEndWhether the bootloader erases from an offset to the end of flash (SAMD21).

LayoutReport

FieldValue
flashSizeThe flash size that the layout is resolved for.
minimumFlashSizeThe minimum of a layout with size = "detect", else null.
unallocatedThe bytes that no partition uses.
partitionsA list of PartitionReport.

PartitionReport has name, role, offset, end, size, imageSize, headroom, headroomPercent, and for a detect layout growsWithFlash and movesWithFlash (its size or offset depends on the chip), minimumSize (the minimum that the layout declares, 0 for remaining) and growth (the bytes above it).

LayoutOptions is the last argument of checkLayout and writeLayout. flashSize, a number of bytes or a text such as "16 MiB", resolves a layout with size = "detect" for that flash instead of its minimum. On a layout with a fixed size it is a layout error, and a size that does not parse is an invalid-argument error. checkLayout still checks the images against the partitions on the minimum flash. For a size above the minimum, writeLayout fails with a table error for linker and constants.

NanoflashError

FieldValue
kindWhat failed, such as no-sync, verification-failed, not-granted, disconnected.
errorClassinput, device or verification.
messageThe message to show.
detailsThe fields of the library, in camelCase.
duringWhat the library was doing, for errors of the port.
rawThe object that the library threw, as it was.

See Errors and warnings for every kind.

<nanoflash-button>

<script type="module">import "nanoflash/button";</script>
<nanoflash-button manifest="firmware/manifest.json" label="Install"></nanoflash-button>

Importing nanoflash does not register the element. The manifest is a nanoflash or an esp-web-tools manifest, in JSON.

AttributeValue
manifestThe URL of the manifest.
labelThe text of the button. Default Install.
erase-allErase the whole flash first. Without it, the element offers a checkbox when the manifest asks for it.

The element asks for the port inside the click. It shows the progress, the notes of the library, the result with what was not verified and every warning, and the errors. A broken module asks the user to reload the page. In a browser without Web Serial, it says so and points to the nanoflash command. When the board comes back in its bootloader under another USB identity, it shows a second button, “Select the board in bootloader mode”, which asks for that port. Install stays available beside it, to start over. A manifest with boards of several protocols works too: the chosen port picks the board.

ItemValues
data-stateunsupported, loading, ready, connecting, erasing, writing, verifying, resetting, done, error, bootloader-permission.
Events (bubbling, composed)nanoflash-progress (detail: the progress event), nanoflash-done (the report), nanoflash-error (the error).
CSS custom properties--nanoflash-button-background, --nanoflash-button-color, --nanoflash-button-radius, --nanoflash-progress-color, --nanoflash-font.
Partsbutton, erase, progress, message, bootloader-button.

Bundlers

The WebAssembly modules ship in dist/wasm and are loaded relative to the module that imports them (new URL("...wasm", import.meta.url)). Each module (espressif, samba, and avr for the three AVR protocols) is a separate dynamic import, so a bundler loads only the module of the board that is flashed. If your bundler does not copy .wasm files that it finds this way, copy node_modules/nanoflash/dist/wasm next to the chunk.

Release archives

Each release of the command (the tag nanoflash-cli-vX.Y.Z) has three assets for each of six targets. Install nanoflash shows how to download and check them.

Targets

TargetSystemArchive
x86_64-unknown-linux-muslLinux, Intel or AMD 64-bitnanoflash-x86_64-unknown-linux-musl.tar.gz
aarch64-unknown-linux-muslLinux, Arm 64-bitnanoflash-aarch64-unknown-linux-musl.tar.gz
x86_64-apple-darwinmacOS, Intelnanoflash-x86_64-apple-darwin.tar.gz
aarch64-apple-darwinmacOS, Apple siliconnanoflash-aarch64-apple-darwin.tar.gz
x86_64-pc-windows-msvcWindows, Intel or AMD 64-bitnanoflash-x86_64-pc-windows-msvc.zip
aarch64-pc-windows-msvcWindows, Arm 64-bitnanoflash-aarch64-pc-windows-msvc.zip

The Linux binaries are static: they run on every distribution. The Windows binaries need no Visual C++ redistributable. The macOS binaries are not signed and not notarised: that needs a paid Apple Developer account.

Assets

For each target <target>:

AssetContent
nanoflash-<target>.tar.gz (.zip on Windows)One directory, nanoflash-<target>, with every binary of nanoflash-cli (nanoflash and cargo-nanoflash), README.md, LICENSE-MIT and LICENSE-APACHE.
nanoflash-<target>.sha256The SHA-256 checksum of the archive, in lower case.
nanoflash-<target>.cdx.jsonThe CycloneDX 1.5 software bill of materials (SBOM, JSON) of nanoflash-cli for that target.

The SBOM lists the crates of the dependency graph for that target, without the build dependencies of build scripts. The list is larger than what the binary links: Cargo merges the features of the whole workspace, so the crates of the web feature (wasm-bindgen, js-sys, wasm-bindgen-futures) and the procedural macro crates are in it too.

Each archive has a build provenance attestation, which gh attestation verify checks.

URLs

The archive names have no version. This URL always gives the archive of the latest release of the command:

https://github.com/AlixANNERAUD/nanoflash/releases/latest/download/nanoflash-<target>.tar.gz

For a given version, replace latest/download with download/nanoflash-cli-vX.Y.Z.

[package.metadata.binstall] in crates/nanoflash-cli/Cargo.toml names these archives, so that cargo binstall nanoflash-cli downloads them. The crate nanoflash-cli is on crates.io since version 0.1.0. The workflow publish.yml publishes it (see Release and publish).

How nanoflash works

Every microcontroller family ships its own flashing tool (esptool or espflash, dfu-util, bossac, avrdude, picotool, probe-rs), each with its own partition format. Web flashing exists only per vendor. nanoflash lays out flash and writes firmware for boards of any vendor through one API, natively (a Rust library and a command) and in the browser (WebAssembly, an npm package and a web component).

nanoflash is project-agnostic. It knows nothing about an operating system or a signing scheme. It reads the image formats that flashing needs (binary, Intel HEX and ELF) and nothing else. Callers bring signing and other formats through hooks.

Two input files

  • A layout file (TOML) describes the flash of a board: its size and its named partitions, each with a role. nanoflash computes the offsets, checks alignment, overlap and size, reports the headroom of every partition, and writes the table that each family needs. See Layout file.
  • A board manifest (TOML or JSON) lists the boards of a project: protocol, chip, layout, images, reset sequence and optional SHA-256 digests. An esp-web-tools manifest is accepted as it is. See Board manifest.

One engine per protocol

Each protocol has one asynchronous engine, a backend. The same code runs natively and in the browser, over a transport trait:

  • The native transport wraps the blocking calls of the serialport crate in async fns. The command runs one flash at a time on a single-threaded executor, where this is harmless. A program that embeds nanoflash in a multi-threaded runtime runs it on a dedicated thread.
  • The browser transport speaks Web Serial through hand-written wasm-bindgen bindings.
  • The test transports replay and record transcripts.

Futures are not Send: browser APIs are single-threaded, so every trait is designed for a single-threaded executor. The library has no clock: every read takes a timeout, so a no_std backend needs no timer of its own. See Library for the traits.

The backends are:

BackendBoards
Espressif ROM loaderESP32, ESP32-S2, ESP32-S3, ESP32-C2, ESP32-C3, ESP32-C5, ESP32-C6, ESP32-H2, ESP32-P4
SAM-BA, with the Arduino extensions of bossacArduino Nano 33 BLE (nRF52840), Arduino SAMD21 boards
STK500v1Arduino Uno, Nano, Pro Mini (Optiboot, ATmegaBOOT)
STK500v2Arduino Mega 2560 (the wiring bootloader)
AVR109Arduino Leonardo, Micro, Pro Micro (Caterina)

USB DFU, UF2, CMSIS-DAP and Nordic serial DFU come later. See Design decisions for the order.

What a flash does

  1. Select the board. The protocol comes from the manifest. See Choosing a backend before detection.
  2. Prepare the images. nanoflash reads every image, checks its SHA-256 digest, calls the verifier of the caller, decodes Intel HEX and ELF files, and places each image at its offset. It generates the partition table from the layout.
  3. Check the plan. Alignment, overlap, partition sizes, flash size and the address range of the protocol are checked before connecting.
  4. Connect. The backend resets the board into its bootloader and detects the chip. It reports the flash size and the part of the flash that the bootloader writes.
  5. Check again. With a layout whose flash size is detected, the layout is resolved again for the reported flash. Every image and erase entry must fit what the chip reports, and the backend checks the order of the whole flash.
  6. Erase, write and verify. Verification uses MD5 on Espressif, CRC-16 through the Z command on SAM-BA, and a read-back on AVR.
  7. Reset the board into its application.

Nothing is erased before steps 2 to 5 pass. Checks before the first erase explains why and what each bootloader erases.

Choosing a backend before detection

  • The protocol comes from the manifest. One manifest may mix protocols, for example an ESP32-S3 and an nRF52840 variant of the same product. The USB identity of the selected port, matched against the application-devices and bootloader-devices of each board, picks the board first. Chip detection then picks among the boards of that protocol.
  • A port that identifies nothing (a USB to UART bridge such as CP210x or CH34x) is matched against the boards whose reset sequence fits a bridge (espressif-classic). When several protocols remain, flash stops with an error that lists them, and --board-identifier settles it.
  • detect without a manifest uses a built-in table of known USB identities to pick the backend: the Arduino AVR boards of Arduino’s boards.txt first, then the vendor 0x303a (Espressif) and the vendor 0x2341 (Arduino, SAM-BA). Otherwise it requires --protocol. It never probes several protocols on the same port, because each probe resets the board differently.
  • Arduino’s AVR boards share the vendors of its SAM-BA boards, so the table lists their products before the vendor rule. A Nano or a Pro Mini sits behind a serial bridge (FTDI, CH340) that tells nothing: the board of the manifest without devices, or --protocol, decides. USB identities that detect knows lists the identities.
  • In the browser, only the module of the chosen backend is loaded, for detect too.

The crates

Three crates in one workspace, plus the npm package. Fewer crates means one version to release, no glue between crates, and features instead of crate boundaries for what a firmware or a web page leaves out.

CrateRole
nanoflash (crates/nanoflash)The library, no_std with alloc. Every feature only adds code. See Library.
nanoflash-cli (crates/nanoflash-cli)The nanoflash command and its twin cargo-nanoflash. Both binaries call main_with of the library of the crate, which holds all the code. It is #[doc(hidden)]: the command is the interface.
nanoflash-web (crates/nanoflash-web)The wasm-bindgen bindings, built once per backend into separate WebAssembly modules. It is not published.

The npm package (web/) holds the TypeScript API, the backend loader and the <nanoflash-button> web component. See Browser API.

The web layer

  • nanoflash-web builds one WebAssembly module per backend with wasm-bindgen-cli: core (layouts), espressif, samba, and avr for the three AVR protocols. Each flashing module contains the core and its backend only.
  • The npm package exposes prepare(manifestUrl), whose flash(options) asks for the port inside the click, detect(), the layout functions, and loadBackend(protocol), which imports the right module dynamically once the board is known.
  • <nanoflash-button manifest="manifest.json"> is a custom element with progress, error and unsupported-browser states, styled through CSS custom properties and parts.
  • Every module is at most 256000 bytes once compressed with gzip -9. CI measures each module and fails above it.
  • The flasher page is a page around <nanoflash-button>. See Browser support and security.

Checks before the first erase

A flash that stops halfway leaves a board that does not boot. Most failures come from the inputs: an image that is too large, a wrong offset, a partition that overlaps another, a file that is not the expected one. nanoflash therefore reads and checks every input before it erases a byte. A mistake in a manifest costs an error message, not a board in its bootloader.

The order of the checks

  1. Before connecting, when the board is known: every image and erase entry is read and checked. The checks are the digest, the alignment, the overlap, the partition, the layout and the address range of the protocol.
  2. After connect, before the first erase: everything is checked again against the flash that the chip reports. Every image and erase entry must start at or after writable_from and end at or before writable_to. When the bootloader erases to the end of flash, every erase entry must end at the end of flash. The backend’s check_plan must accept the whole flash in the order in which it is sent (the erase order of the Mega 2560).

Every error message names the partitions and the addresses involved. Addresses print as 0x hexadecimal. See Errors and warnings.

What flash writes

  • It writes exactly the images that the manifest lists, plus the partition table generated from the layout when the layout has a partition-table partition and no manifest image targets it.
  • A manifest image that targets that partition wins, and layout check warns when it differs from the generated table. In a layout whose partitions grow or move with the flash, such an image is refused (partition-table-image-for-detected-flash): no fixed table fits every chip.
  • It does not initialise otadata and does not patch the Espressif bootloader header (flash size, mode, frequency). Both are image formats, which nanoflash leaves to the caller. A manifest that wants otadata reset lists an image for it, or an erase entry for its partition.

What flash erases

It erases only the regions that it writes, rounded to the erase unit, except on the SAMD21 (see below). --erase-all (and eraseAll: true in the browser API) erases the flash first, from the lowest offset that the bootloader writes (writable_from, which connect reports) to the end. A bootloader that the chip protects, such as SAM-BA’s, is never erased. Data partitions such as NVS or storage are not touched unless an image or an erase entry targets them, again except on the SAMD21.

SAM-BA

Arduino’s X command depends on the chip:

  • nRF52840 (Nano 33 BLE): X erases nothing. Each write erases the 4 KiB pages that it programs. An erase entry or --erase-all writes 0xFF over its pages.
  • SAMD21: X erases from its address to the end of flash. A write erases from the lowest written address to the end of flash, so everything stored after the lowest image is gone, data partitions included. nanoflash says so in its progress messages and adds an erases-to-end warning to the report, which names the partitions of the layout that it erased and that no image is written to. Erase entries must end at the end of flash, and images are written in order of offset.

AVR

The STK500v1, STK500v2 and AVR109 bootloaders have no usable chip erase: Optiboot ignores it, and Arduino never sends it. On AVR, “erased” means “programmed with 0xFF”.

  • Optiboot, ATmegaBOOT and Caterina erase each page as they program it. An erase entry or --erase-all programs 0xFF over its pages.
  • The bootloader sits at the top of the flash, which connect reports as writable_to (0x7E00 on an Uno with Optiboot). Nothing at or above it is written. --erase-all stops at writable_to, or at the bootloader partition of the layout above the application when that partition starts lower. The layout of the Nano keeps 2 KiB for the old bootloader, while Optiboot takes 512 bytes.
  • The wiring bootloader of the Mega 2560 (STK500v2) erases one page per page programmed. Its erase address starts at 0x0 and moves on by one page each time, wherever the programmed page goes. It erases nothing from its APP_END, 0x3C000 (16 KiB under the end of flash, twice its 8 KiB). So writable_to is 0x3C000. Before the first erase or write, the backend replays that address over the whole flash (--erase-all, the erase entries, then the images in order of offset). Images must start at 0x0 and follow each other, and an erase entry must start at 0x0, unless --erase-all erased every page first. A flash that breaks the order is refused before anything is written.

Layouts that detect the flash size

A layout with size = "detect" describes partitions that grow or move with the flash of the chip. Growable partitions explains the rules. For flashing, they add these steps:

  • Resolution at connect. Before connecting, the layout is resolved for its minimum, and every input is checked against it, image sizes included. An image larger than its partition on the minimum is refused, even for a chip with more flash. Every prepared image remembers how it was placed (by partition, by offset, or the generated table), and every erase entry the partition that it names. Right after connect, before any check against the chip and any erase, the layout is resolved again for the flash that the chip reports:

    • a chip below the minimum fails with flash-too-small;
    • a chip that reports no size (secure download mode, an unknown flash identifier) keeps the minimum with a flash-size-not-detected warning;
    • a chip of exactly the minimum changes nothing;
    • a larger chip moves the images and erase entries that name a partition to where it now is, generates the partition table again for that size, and runs the checks of the plan again.

    Then come the checks against the chip (writable_from, writable_to, erases to the end of flash) and the backend’s check_plan, on the new places.

  • Inputs tied to an offset. An image or an erase entry given by offset, an Intel HEX image, an ELF image decoded into flat segments and a manifest image of the partition table cannot follow the chip. The addresses of Intel HEX and ELF images are in the file, even when the manifest names their partition. Such an input may not overlap a partition that moves with the flash (fixed-offset-on-moving-partition): it would stay where the partition was on the minimum. This is checked before connecting against the minimum, and again after the resolution for the chip, because a partition that moves by a whole step can cover what was the unallocated end of the flash on the minimum. Images and erase entries that name a partition follow it.

  • Warnings. partitions-grew names each partition that is larger than on the minimum, with both sizes. On the Espressif protocol it adds that the bootloader image must be built for that flash size or with flash size detection, because ESP-IDF applications use the flash size of the bootloader header, which nanoflash does not patch. The chip refuses a bootloader header that names more flash than it has. partitions-moved names each partition that starts elsewhere than on the minimum: data that a firmware wrote for another flash size is not where the layout now puts it. flash-size-not-detected says that the minimum was kept. Each warning is also sent as a progress message when it happens. The report lists the warnings of the image preparation, then these, then erases-to-end, then not-verified-in-secure-download-mode.

  • The bootloaders. The layout describes the whole flash that the chip reports. On AVR that size includes the bootloader at the top, so a partition that grows to the end of the flash covers it. An erase entry or an image that reaches into it is refused by the writable_to check, before any erase. On the SAMD21, erase entries must end at the end of flash. A partition that grows in steps or up to a maximum may stop short of it on a larger chip, and an erase entry for it is then refused before any erase. A lone remaining partition at the end of the layout fills to the end of the flash on every chip.

Growable partitions

One product often ships with flash chips of several sizes. A fixed layout wastes the extra flash of the larger chips, and one layout per flash size multiplies the files to keep in step. A layout can therefore take the flash size from the chip (size = "detect") and let some partitions grow with it. This page explains how nanoflash places these partitions. The keys are in Layout file.

Resolution

Resolution keeps the file order. Partitions with a fixed offset stay where they are. The others go at the first offset after the previous partition that satisfies their alignment. Partitions place first at their minimum size. The free space is then shared by these rules:

  • R1 Segments. Every partition with a fixed offset starts a segment of the file order. A segment ends where the next one starts, and the last one ends at the end of the flash. Growth only fills the free space at the end of its own segment, so only the last segment depends on the flash size. In a detect layout, fixed offsets ascend in file order, so that no partition lies above the last segment as it grows. A layout with a fixed flash size keeps any order.
  • R2 Steps. The share of a { grow } partition is a multiple of the largest of its alignment and the alignments of the partitions after it in its segment. These partitions then move by whole multiples of their alignment and need no new padding.
  • R3 remaining grows in steps of the largest alignment of the partitions after it, or of one byte when it is the last of its segment. Alone at the end of a segment, it fills to the byte.
  • R4 Sharing. The free space is shared by weight, and each share is rounded down to its step. A maximum holds a share, and what it leaves goes to the others. The rounding remainder stays unallocated. Several remaining partitions share like { grow = 1 }. The partitions after a growing one are pushed towards the end of its segment. Every layout that was valid before growing sizes existed resolves exactly as before.
  • R5 Roles. firmware and update partitions never take the table form, because their images are built for a size. They may be remaining where that size does not depend on the device: a fixed flash size, or a segment that ends at a fixed offset. In a detect layout, a bootloader, partition-table, firmware or update partition whose offset would move with the flash is refused.
  • R6 Dependence. In a detect layout, a partition grows with the flash when it is remaining or { grow } in the last segment, unless its maximum keeps it below one step above its minimum. It moves with the flash when it is in the last segment, has no fixed offset and comes after a partition that grows with the flash.

Resolution fails, and names the partitions and the addresses involved, on:

  • duplicate names and zero sizes;
  • misaligned fixed offsets, overlaps, and partitions that exceed the flash size;
  • a remaining partition left without space;
  • fixed offsets that descend in a detect layout;
  • a maximum below its minimum;
  • a growing firmware or update partition;
  • a partition whose role needs a fixed offset placed after one that grows with the flash;
  • a flash below the minimum of the layout;
  • roles that a writer cannot express.

Offline outputs use the minimum

layout check, layout write, the build feature and image build without --flash-size do not know the chip. They resolve the layout for its minimum flash size. The constants and linker regions state what holds on every device, so both writers need the layout resolved for its minimum and refuse another (NotAtMinimum). Only the values written decide between u32 and u64.

  • R7 Constants. FLASH_SIZE becomes FLASH_MINIMUM_SIZE. A partition that grows with the flash gets MINIMUM_SIZE instead of SIZE: its size on the minimum flash, the least that it has on any device, because shares never shrink when the flash grows. That size is at least the minimum that the layout declares. The minimum_size of the report is the declared minimum, and MINIMUM_SIZE is the size on the minimum flash. A partition that moves with the flash gets no OFFSET and no ADDRESS, so a firmware that uses them fails to compile instead of writing at the wrong place. A partition that does both has MINIMUM_SIZE and no OFFSET: moving wins for placement, growing for size. The other partitions keep SIZE, so the constants of a fixed layout do not change.
  • R8 Linker regions. A partition that grows with the flash keeps a region of its size on the minimum flash, after a comment. Every byte of that region belongs to the partition on every device, and the linker never places anything past it. A partition that moves with the flash gets no region, and a comment says so: no fixed ORIGIN is right on every device, and a missing region fails the link.

Flashing resolves again

flash checks every input at the minimum before it connects, then resolves the layout again for the flash that the chip reports, before any erase. Images and erase entries that name a partition follow it. Inputs tied to an offset may not touch a partition that moves. Checks before the first erase describes these steps and the warnings partitions-grew, partitions-moved and flash-size-not-detected.

The report

For each partition, the report gives its offset, end and size. When images are known, it gives the image size and the headroom left, in bytes and in percent, plus the unallocated flash. For a layout whose flash size is detected, the report also gives minimum_flash_size, and each partition gives its minimum_size (the minimum that the layout declares, 0 for remaining), its growth (the bytes above it), and whether it grows_with_flash or moves_with_flash. An image larger than its partition is an error. The human output is a table, and --json gives the same data.

How the generated memory.x is protected

The build feature can write the whole memory.x of a firmware from its layout. A second memory.x that the linker finds first would silently replace it, and the firmware would link against regions that the layout does not describe. This page explains why that can happen and how nanoflash detects it. The steps to use the feature are in Generate memory.x and layout constants.

Why the file must be named memory.x

The linker writer produces nanoflash_memory.x, the MEMORY block of the layout. The link.x of cortex-m-rt starts with INCLUDE memory.x and uses the regions FLASH and RAM. A -Tnanoflash_memory.x argument therefore cannot replace the memory.x of the firmware: the file must be named memory.x and be on the linker search path.

Build::memory(name, origin, length) adds a region that is not a partition (the RAM). generate then writes the whole memory.x (the regions of the layout, then the regions given) to OUT_DIR, which generate puts on the search path.

Three checks and one limit

1. A memory.x in the working directory of the linker. The linker looks first in its working directory. Cargo runs rustc, and so the linker, from the workspace root for a package under it (path_args in Cargo), and from the package directory otherwise. A memory.x in the workspace root would win over the generated file. generate refuses a memory.x in the workspace root and in the package directory when memory was called (BuildError::MemoryScriptShadowed). It finds the workspace root with the walk of the cargo module (workspace_root: a [workspace] table in the Cargo.toml itself, package.workspace, or the nearest ancestor with a [workspace] table), without a cargo metadata process. Without memory, a memory.x that includes nanoflash_memory.x works as before.

2. A memory.x added after a build. The first check runs only when the build script runs. A build script that prints rerun-if-changed runs again only when a listed path changes. A path that does not exist counts as changed on every build, and a directory is scanned with target/ in it. So the script cannot list the two memory.x paths or the directories without rebuilding the firmware on every build. Instead:

  • generate writes nanoflash_memory_guard.x to OUT_DIR when memory was called, and prints cargo:rustc-link-arg-bins=-T<that file>.
  • The memory.x of nanoflash ends with __nanoflash_memory_x = 1;. The guard is ASSERT(__nanoflash_memory_x == 1, "...").
  • The guard reads the marker and does not test DEFINED(__nanoflash_memory_x). rust-lld evaluates DEFINED in the order of the scripts on the command line, and the build script of a firmware prints -Tlink.x after generate, so DEFINED fails a correct link. A read of the marker gives the same result in every order, in rust-lld (measured with the link.x of cortex-m-rt 0.7, without flip-link) and in GNU ld (measured on test scripts).
  • When another memory.x was linked, the marker does not exist. Both linkers then fail and name the symbol and the line of the guard, not the message of the assertion. rust-lld reports nanoflash_memory_guard.x:5: symbol not found: __nanoflash_memory_x, and GNU ld reports the same symbol as unresolved in an expression. The message and a comment in the guard explain the symbol.
  • The link runs again only when the package changes. A memory.x added after a build therefore fails the next link, not the next cargo build without a change.
  • Build::package() prints rerun-if-changed for the Cargo.toml of the package too, so a change of board = runs the script again. Build::layout(path) lists only the layout file.
  • A package that does not call memory gets neither the marker nor the guard, and generate removes a guard and a memory.x that an earlier build left in OUT_DIR.
  • cargo:rustc-link-arg-bins reaches every binary of the package. memory therefore requires that every binary links the generated memory.x, through the link.x of cortex-m-rt or a script that includes it. A binary for the host in the same package, or a runtime whose script does not include memory.x, fails to link and names the marker. Such a binary belongs in another package.

3. Invalid region names. A region given to memory is refused when its name is not valid (TableError::InvalidRegionName, the rule of the linker.region attribute), when an earlier region given has the same name (TableError::RepeatedRegion), or when it has the name of a region of the layout (TableError::DuplicateRegion).

The limit: another memory.x on the search path is not checked. HAL crates with a memory-x feature (embassy-stm32, stm32-metapac) write one to their own output directory, and the order of the search directories decides which file wins. Turn that feature off when you call memory.

The serial monitor and defmt

nanoflash monitor shows what the application of a board writes to its serial port, and sends what the user types. nanoflash run uses the same monitor after it flashes. This page explains the choices behind it. The options are in Command line.

Why the monitor is in the command

The monitor is in nanoflash-cli, not in the library. It needs a clock, a terminal and threads, and it must not reach the WebAssembly modules.

Signals after the port opens

After it opens a port, the monitor sets DTR and RTS:

  • both cleared for an Espressif board and for a port whose USB identity is Espressif or unknown, because a UART bridge may drive the reset and boot pins of an ESP32;
  • DTR set for the others (a known AVR or SAM-BA identity), because Arduino sketches wait for DTR before they print.

A port that refuses the lines (a pseudo-terminal) only gets a note.

--baud-rate 1200 is refused for a board whose reset is a 1200-baud touch, because that rate makes the sketch restart into its bootloader.

Devices that leave and come back

A reset, or a sketch that restarts its USB device, makes the device leave. The monitor then waits up to 30 s for the same device and opens it again. “The same device” is the application-devices of the board, else the exact USB identity of the port, else the same path. If it does not come back, the exit code is 2.

The defmt decoder

monitor --elf <file> decodes the defmt frames among the text of the port, with defmt-decoder, a dependency of the command only. The decoder (monitor/defmt.rs) reads the table of the .defmt section and the locations of the DWARF information.

  • Framing. The decoder accepts the rzcobs encoding only. A frame in rzcobs never contains a 00 byte, so a frame can be found in a byte stream. The framing is the one of esp-println: the bytes ff 00, the frame, and the byte 00. A plain stream of frames (defmt-serial) is not supported. Every other byte is text.
  • State machine. The decoder is a state machine over the bytes, so a frame may span several reads, and the pieces do not depend on how the reads split the bytes (a property test checks it). A byte ff at the end of a read is kept until the next read decides.
  • Isolation. Each frame is decoded by a new stream decoder, under catch_unwind (guard.rs): a panic or an error gives a malformed frame.
  • End of stream. When the device leaves or the monitor ends, the decoder ends its stream (finish). The kept byte is text, and an unfinished frame is malformed, so half a frame of the old connection does not hide the text of the new one.
  • Order. With --json, the unfinished line is emitted before a frame, so the order of the output is kept.
  • run decodes by itself. run decodes the frames when its image is an ELF file with a defmt table. A table that it cannot use gives a note, not an error, because the user did not ask for decoding. monitor --elf with a file that has no table is an input error.

Limits of the decoder

The limits that change what the user sees (a ff 00 in plain text, the frame size of 4096 bytes, the end of the process and the terminal in raw mode) are in Decode defmt logs. This section gives their causes.

  • The framing cannot tell a ff 00 in plain text from the start of a real frame.
  • The limit of 4096 bytes bounds the nesting of the formats in a frame, which defmt-decoder decodes recursively without a depth limit. A frame of more than 64 bytes is decoded on a thread with a stack of 64 MiB (the system fills it only when it is used), because a frame of 4096 bytes can nest about 3000 levels and overflows a smaller stack in a build without optimisation. If the thread cannot start, the frame is malformed.
  • defmt-decoder 1.2.0 can still end the process. It reads the count of a {=[?]} argument from the frame and allocates the memory for that count before it reads an element. A count of 0xffffffff fails the allocation, and Rust ends the process: catch_unwind does not catch it. A pre-parser of the frame would be needed to prevent it. The end skips the Drop of the console that restores the terminal.
  • The tests do not cover the file, line and module of a frame: they need DWARF information in the fixture, and a hand-written one is long. The conversion is a copy of the fields of defmt-decoder.

Browser support and security

Which browsers flash

The browser package flashes over Web Serial. Only Chromium-based browsers implement it (Chrome, Edge, Opera), and only on a secure origin (https: or localhost). WebUSB, which later protocols will need, has the same limits. Firefox and Safari do not implement either. In those browsers, use the nanoflash command, which flashes the same manifests.

isSupported() tells whether the browser has Web Serial. The <nanoflash-button> element shows an unsupported state and points to the command line.

Why the port is asked for inside the click

A browser shows the port chooser only during a user gesture, and an await may end the gesture. prepare reads the manifest and starts to load the WebAssembly module before the click. prepared.flash asks for the port before its first await, so call it straight from the click handler.

Why a second button appears

The touch reset of SAM-BA and AVR109 boards makes the bootloader appear as another USB device. The page has no permission for that device the first time, and the browser does not let a page reach a device that it was not granted without a new user gesture. The component asks for the application and bootloader identities in one filter list. When the bootloader device was never granted, it shows a second button, “Select the board in bootloader mode”. The browser keeps the grant, so the next flash finds the bootloader by itself. See Use the browser package.

Why a broken module stays broken

A WebAssembly trap (a bug of nanoflash) is fatal for its module, which cannot be instantiated again. A layout call runs synchronously and sees the trap at once. flash and detect run in microtasks, where a trap is an uncaught exception that would leave their promise pending. While they run, the package listens for uncaught WebAssembly.RuntimeErrors (the error event of the page, uncaughtExceptionMonitor in Node) and rejects the call when one comes. Either way, the call rejects with kind module-broken (class device), its port is closed, and every later call that needs the module fails at once with the same error. The page must be reloaded.

The flasher page

The flasher page (https://alixanneraud.github.io/nanoflash/flasher/) flashes a board from a manifest that the visitor gives as an https: URL or as files on the computer. It writes firmware to hardware, so it treats every manifest as untrusted until the visitor confirms where it comes from.

  • The site hosts no firmware and no manifest. The visitor brings both.
  • A manifest of another origin needs a tick in a checkbox. The label shows the whole manifest URL, not only its origin: one origin, such as raw.githubusercontent.com, serves the files of many publishers. The page also shows the boards and the other origins that the manifest loads files from, and the label names them. The page gives the manifest to the button only after the tick.
  • The manifest is downloaded once. The button receives the manifest that the page fetched, as a blob: URL with every path resolved against the manifest URL. The button writes the text that the page showed, not a second download that could differ.
  • Cross-origin reads must be allowed. The server of the manifest and of its files must send Access-Control-Allow-Origin. A redirect to another origin is refused.
  • Files on the computer need no tick when every path of the manifest names a selected file. A manifest on the computer that names a URL needs the same tick, and the label names every origin of those URLs.
  • The page refuses to run inside a frame. Other sites can frame the page: GitHub Pages sends no frame-ancestors header, and a policy in a meta element cannot set it. start.ts therefore checks window.top and refuses to start inside a frame. This check is a second defence: the browser still asks the visitor to choose the serial port.
  • A Content Security Policy in a meta element of index.html contains the SHA-256 hash of the import map. flasher.test.mjs fails when the hash is wrong.
  • The footer shows the version and the commit that the site was built from (site.json), so a visitor can tell which code runs.

Use the flasher page gives the steps for visitors and for publishers of manifests.

How nanoflash is tested

A flashing tool fails on hardware, where tests are slow and boards are few. nanoflash therefore tests every device session without a board first, then checks the same paths against emulators and real boards.

Transcripts

A transcript is a text file with one event per line:

PrefixEvent
>Bytes from the host, in hexadecimal.
<Bytes from the device, in hexadecimal.
!Line changes, baud rate changes, waits, re-enumerations.
#A comment.

The testing feature provides a replay transport that fails on any divergence, and a recording transport behind the hidden --record <file> flag of the command. The transcripts of the library are in crates/nanoflash/tests/transcripts. The transcripts of nanoflash monitor and nanoflash run are in crates/nanoflash-cli/tests/transcripts.

Sources of transcripts

  • Espressif’s QEMU (ESP32 and ESP32-C3 in download mode), in CI.
  • arduino/BOSSA’s SAM-BA emulator, for SAM-BA.
  • simavr (GPL-3.0, installed or downloaded at test time, never committed or distributed) running Optiboot, ATmegaBOOT and the wiring bootloader of the Mega 2560 from ArduinoCore-avr.
  • Recordings from real boards, added as they are made.
  • Hand-written transcripts for error paths: timeouts, bad checksums, a wrong chip.

Run the hardware tests describes each emulator and the boards.

Property tests

proptest checks that resolution never yields overlap or misalignment and keeps fixed offsets. Every writer round-trips through a parser: esp-idf-part and ESP-IDF’s gen_esp32part.py in CI for the Espressif table, mbrman and sfdisk --dump for the MBR.

WebAssembly

The backends and the library build for wasm32-unknown-unknown in CI. Replay tests run the WebAssembly modules in Node against a Web Serial mock that a transcript drives. The check in a real browser is manual: see Run the hardware tests.

Hardware in the loop

hardware/ describes the boards attached to a runner. mise run test-hardware flashes, verifies and checks that the board booted (a known string on its serial port). The tests are #[ignore]d unless NANOFLASH_HARDWARE is set. A workflow_dispatch job targets a self-hosted runner with the nanoflash-hardware label.

Design decisions

This page records what nanoflash aims for, what it leaves out, and the approaches that were considered. Prior art and licences has the survey of existing tools behind these choices.

Goals

  • One vendor-neutral TOML layout file per board: flash size and named partitions with a role. nanoflash resolves offsets, checks them, reports headroom and writes the table of each family.
  • One vendor-neutral board manifest: protocol, chip, layout, images, reset sequence, digests. The esp-web-tools manifest is accepted as it is.
  • One asynchronous code path for every backend, running natively and in WebAssembly over a transport trait.
  • Backends, in order: Espressif ROM loader, SAM-BA (with the Arduino dialect of bossac), the STK500v1, STK500v2 and AVR109 bootloaders of Arduino’s AVR boards, USB DFU, UF2, then CMSIS-DAP (in the command only) and Nordic serial DFU.
  • Binary, Intel HEX and ELF images for every backend.
  • A build feature, so that the build.rs of a firmware reads the same layout file: one source of truth.
  • A command line for CI: clear errors, --json, no prompts.

Non-goals

  • Building firmware, or vendor image formats beyond what flashing needs.
  • Signing, encryption and secure boot provisioning. Verification is a hook of the caller.
  • A debugger.
  • Browsers without Web Serial or WebUSB (Firefox, Safari). The command line is the alternative.

Anti-goals

These would make nanoflash a failure even if it worked:

  • Two engines per protocol (one native, one in the browser) that drift apart.
  • A WebAssembly bundle that ships every backend to flash one board.
  • Code ported from a copyleft implementation (esptool is GPL-2.0-or-later).
  • Interactive prompts or ambiguous output in CI.

Constraints

  • Stable Rust, edition 2024, minimum supported version 1.95. The library is no_std with alloc.
  • Licence MIT OR Apache-2.0 for every crate. No code is ported from implementations under other licences. They serve as behaviour references only.
  • Identifiers, documentation and messages spell words out (device, directory, configuration) unless an external API forces otherwise.
  • Conventional commits. The tooling is the same as in the author’s other crates: mise, mbx (mr-boxington), release-plz, cargo-deny, codecov, a pull request title check and the nanobom SBOM upload.
  • Web Serial and WebUSB exist in Chromium-based browsers only.
  • Futures are not Send: browser APIs are single-threaded, so every trait is designed for a single-threaded executor.
  • The library never panics on an input or a device answer, bounds every wait on a device, and forbids unsafe code. Invariants lists these rules.
  • Distribution channels: git tags and GitHub releases first (archives of the command, with a checksum, a software bill of materials and a build provenance attestation for each target, see Release archives), then crates.io and npm. release-plz publishes nothing to a registry. The workflow publish.yml publishes a release to crates.io by hand, after the hardware check. It only stages the npm package, through npm trusted publishing with no token, and a maintainer approves the staged version with two-factor authentication. The crates and the npm package are published since version 0.1.0. The archives hold every binary of nanoflash-cli and have no version in their names, so one URL always gives the latest command. cargo binstall reads [package.metadata.binstall] of nanoflash-cli and downloads the same archives. The macOS binaries are not signed. There is no container image.

Approaches considered

For the backends, the choice was between reusing existing tools and writing new code.

ApproachTrade-offOutcome
A. Reuse protocol libraries where they run asynchronously over our transport; write the missing loopOne engine per protocol on both platforms; some code of our own (Espressif loop, SAM-BA, AVR)Chosen
B. Wrap the existing tool per platform (espflash natively, esptool-js in the browser; bossac natively)Least code, but two engines per protocol, tests cover only one, no SAM-BA in the browserRejected (anti-goal)
B’. For SAM-BA, BOSSA everywhere (cxx natively, BOSSA compiled to WebAssembly with Chromium’s JSPI in the browser)Reuses BOSSA, but needs a C++ toolchain, a second WebAssembly module with JavaScript glue, and makes the crate BSD-3-ClauseRejected in favour of our own code
C. Make the upstream tools asynchronous first (espflash, probe-rs), then build on themBest for the ecosystem, but blocked on the major-version decisions of their maintainersDeferred for espflash. Closed for probe-rs, see below

For each backend, the choice favours the smallest codebase, simplicity and portability. Dependencies count as code: they weigh on the WebAssembly bundle and on no_std.

Backend or writerReusedOurs
Espressif ROM loaderminiz_oxide (compression), md-5SLIP framing, commands, a chip table of about 40 lines copied from espflash (MIT OR Apache-2.0, attributed), the asynchronous loop, reset sequences, orchestration. No flasher stub: the ROM already supports compressed writes and MD5, and the stub is only a speed-up. The ESP32 is written uncompressed: its ROM programs a whole 32 KiB inflate window after every compressed image (seen in Espressif’s QEMU).
SAM-BAnone usable in the browserOur own code, written from the protocol (Microchip’s SAM-BA documentation, observed bootloader behaviour). BOSSA (BSD-3-Clause) is a behaviour reference only. No code is ported.
STK500v1, STK500v2, AVR109none: no crate is no_std, asynchronous over our transport and permissively licensedOur own code, written from Atmel’s application notes AVR061, AVR068 and AVR109 and from observing the bootloaders. avrdude, Optiboot, ATmegaBOOT, the wiring bootloader and Caterina (GPL) are behaviour references only. No code is ported.
Intel HEXihex as a test-only dependency, to read the fixture backA decoder of about 300 lines: ihex needs std.
Espressif partition tablemd-5About 100 lines: 32-byte entries and the MD5 row. esp-idf-part (needs std, regex, deku) is a test-only dependency that reads the output back.
MBRnoneAbout 50 lines: four 16-byte entries and the signature. mbrman is a test-only dependency.
USB DFU (later)dfu-core (no_std, sans-I/O)Glue to the USB transport, DfuSe.
UF2 (later)none (the format is a 32-byte header)Encoder, family identifiers, drive handling.
CMSIS-DAP (later)probe-rs natively; none in the browserGlue in the command.

espflash as a dependency was considered: it builds for WebAssembly without its serial feature. But it would bring regex, deku, object and esp-idf-part into the bundle for about 40 lines of constants, so the constants are copied instead.

The command line is the exception, for one task only. It uses image_format of espflash 4.7 (without its serial port code) to build the ESP-IDF application image of an ELF file (crates/nanoflash-cli/src/espressif_image.rs). The library and the WebAssembly modules do not depend on espflash. The command line writes a temporary partition table with esp-idf-part and passes its path to espflash, which takes it as a file. With no bootloader path, espflash reads the header of its bundled bootloader for the flash mode and frequency of the application header. The command line therefore links all the bundled bootloaders, about 750 KB. nanoflash never writes them to a device.

CMSIS-DAP is planned for the command only, through the probe-rs crate. On 2026-11-30 the browser route through probe-rs was judged a dead end: its WebAssembly build is several MB, over the limit of 256000 bytes of a module, and upstream did not take the proposed changes. DAPjs in the browser would be a second engine next to probe-rs, which is an anti-goal.

Transports

The original brief asked for one transport trait with USB control requests too. USB devices get their own trait (control and bulk transfers, over nusb natively and in the browser) with the first USB backend, DFU. No device is both a serial port and a raw USB device. A PortProvider was added because the touch reset makes the bootloader appear as a new device. Timeouts are part of read, so no_std backends need no timer of their own.

In the browser, a device that comes back under another USB identity is reachable without a user gesture only if permission was granted earlier. The web component asks for the application and bootloader identities of the board in one requestPort filter list. When the bootloader device was never granted, it shows a second button (“Select the board in bootloader mode”) instead of failing.

The facade dispatches over an enum of the enabled backends, because async fn in traits is not object-safe.

Roles and table writers

The roles are bootloader, partition-table, firmware, update, storage, crash-record and custom. partition-table was added to the roles of the brief, because table writers need to know where their table goes. Per-family attributes live in a table named after the family and override what the role implies.

A GPT writer (protective MBR, primary and backup GPT, with gpt_disk_types, type GUIDs from attributes and deterministic GUIDs from a seed for reproducible images) comes later. So does a FileSystemImageWriter trait that builds a FAT (fatfs) or LittleFS (littlefs2, native only) image of a given size from a list of files. Nothing depends on it: a manifest image may target a storage partition with an image that the caller supplies, which is checked to fit.

The monitor is not in the library

nanoflash monitor is in nanoflash-cli and not in the library, because it needs a clock, a terminal and threads, and it must not reach the WebAssembly modules. The serial monitor and defmt explains how it works.

Roadmap

The work came in stacked deliverables, one pull request each:

  1. The design, the prior art report, the licence files.
  2. Workspace and tooling; the layout model, resolution, checks, manifest model and traits; the Espressif, MBR and linker writers; the build feature; layout check and layout write.
  3. Transports (native and web); the Espressif backend; flash, detect and image build; the npm package and web component for Espressif.
  4. The SAM-BA backend for the Arduino Nano 33 BLE. Arduino’s SAMD bootloaders speak the same dialect (X, Y, Z), so their family data came along, tested against transcripts only.
  5. The AVR backend (STK500v1, STK500v2, AVR109) for the Arduino Uno, Nano, Mega 2560 and Leonardo, with Intel HEX images for every protocol and an avr WebAssembly module, tested against transcripts and simavr.
  6. The Rust toolchain: ELF images, nanoflash monitor, nanoflash run, the board in [package.metadata.nanoflash], cargo nanoflash, the build feature writing a whole memory.x, and the example firmware examples/nano33ble.
  7. Release binaries: release-plz in git-only mode, and the archives, checksums, SBOMs and provenance of the command on its GitHub release. Tested by dry runs of binaries.yml. The first real release has not happened yet.

Next, in this order unless the order changes: the GPT writer and file system images, USB DFU, UF2, CMSIS-DAP, Nordic serial DFU. UF2 in the browser will write through the File System Access API: the user picks the drive of the board once.

Prior art and licences

What already exists for flashing and partitioning microcontrollers, natively and in the browser, and what nanoflash reuses, contributes to or writes itself. Surveyed on 2026-11-22; versions and licences come from crates.io, npm and the projects’ repositories on that date.

Summary

  • No Rust or WebAssembly project unifies several bootloader protocols behind one API, and none unifies partition layouts across vendors. The closest, probe-rs, only drives debug probes.
  • Every web flasher covers one vendor or one protocol (esptool-js, esp-web-tools, webdfu, DAPjs).
  • The building blocks exist and are permissively licensed: espflash (without its serial port layer), dfu-core, nusb (now with a WebUSB backend), mbrman, gpt_disk_types, esp-idf-part, uf2_block.
  • Some protocols have no reusable Rust implementation: the Espressif ROM loader over an asynchronous transport, SAM-BA, and the STK500v1, STK500v2 and AVR109 bootloaders of Arduino’s AVR boards. nanoflash writes those, using espflash, BOSSA and avrdude as references. See Design decisions for the choices that follow from this survey.

Multi-protocol flashers

ProjectScopeLicenceNotes
probe-rs 0.32.0Debug probes: CMSIS-DAP, ST-Link, J-Link, ESP USB-JTAG, WCH-LinkMIT OR Apache-2.0No ROM serial loaders, SAM-BA, DFU or UF2. Synchronous. Its WebAssembly build is several MB, far above the limit of 256000 bytes of a nanoflash module, and the proposed changes for asynchronous probes (pull request #2958) were not taken upstream. The CMSIS-DAP layer is not a separate crate.
esptool-js 0.7.1Espressif ROM loader over Web Serial (and WebUSB for CH34x bridges)Apache-2.0Espressif only.
esp-web-tools 10.5.2Install button and manifest on top of esptool-jsApache-2.0Espressif only. Its manifest format is accepted by nanoflash.
Adafruit WebSerial ESPToolEspressif over Web SerialMITEspressif only.
webdfuUSB DFU over WebUSBISCUnmaintained since 2021.
DAPjsCMSIS-DAP over WebUSBMITJavaScript.
Arduino Cloud AgentNative helper that runs bossac, avrdude… for the browserAGPL-3.0Not a web flasher; not reused.
espflash-wasmExperiment running espflash in the browserMIT OR Apache-2.0Last change in 2023.
ESP32 Bit Pirate web toolsesptool-js, STM32 AN3155, avrdude in WebAssemblyvariousSeveral separate tools on one page, not one API.

Per protocol

Espressif ROM serial bootloader

  • espflash 4.7.0, MIT OR Apache-2.0 (relicensed in #224). Supports ESP32, C2, C3, C5, C6, C61, H2, H21, H4, P4, S2, S3 and S31.
    • Its Connection and Flasher are synchronous and bound to the concrete serialport types; they only exist behind the serialport feature. There is no custom transport and Web Serial is asynchronous only, so they cannot run in the browser.
    • Without that feature the crate still provides the command module (encoding of every loader command), target::Chip (chip detection values, register addresses, write sizes, eFuse fields) and the flasher stubs. We built it for wasm32-unknown-unknown with default-features = false: it compiles. Its dependencies (regex, deku, object, esp-idf-part) weigh on the WebAssembly bundle; this is measured before committing to it.
    • Issue #1091 asks for user-supplied serial ports; the maintainer put it on hold but would consider a contribution for a future major version. PR #834 (no_std with embedded-io) is open and inactive since 2025-07.
  • esptool 5.6.0 (Python) is GPL-2.0-or-later: nanoflash does not port from it.
  • esp-flasher-stub is Apache-2.0 OR MIT; the stubs can be redistributed.
  • The protocol is documented by Espressif: serial protocol.

Decision: write our own asynchronous loader over nanoflash’s transport trait: SLIP framing, commands, reset sequences, orchestration, written from Espressif’s protocol documentation with espflash and esptool-js as references. Copy the few chip constants we need (detection values, about 40 lines) from espflash with attribution (MIT OR Apache-2.0) rather than depending on it: its dependency tree would dominate the WebAssembly bundle for those few lines. Use the ROM loader without a flasher stub at first (the ROM supports compressed writes and MD5); the stub is a later speed-up. Offer the transport design upstream on #1091 once it has proven itself.

The nanoflash command uses one more part of espflash 4.7: image_format, to turn an ELF file into an ESP-IDF application image. That code is large and changes with each chip, and it needs no transport, so it is reused natively and not rewritten. The library and the browser package do not use it.

SAM-BA and the bossac dialect

  • BOSSA 1.9.1 and the active arduino/BOSSA fork (1.9.1-arduino6): BSD-3-Clause. The reference implementation is Samba.cpp: ASCII commands N#, V#, O/o/W/w/S/R/G, plus the Arduino extensions advertised as [Arduino:XYZ...] in the version string: X (erase), Y (write buffer to flash), Z (CRC), I (identify chip), K (reset). arduino/BOSSA ships a SAM-BA emulator in its tests.
  • The SAMD bootloader of ArduinoCore-samd is LGPL-2.1 (device side; not vendored).
  • Arduino Nano 33 BLE (ArduinoCore-mbed boards.txt): upload.tool=bossac, use_1200bps_touch=true, wait_for_upload_port=true, VID 0x2341, PIDs 0x005a, 0x805a, 0x015a, 0x025a; upload command bossac -U -i -e -w file.bin -R. arduino/BOSSA identifies nRF52840-QIAA through I. The bootloader itself is distributed as a binary only (issue #90).
  • Rust: only bossa, C++ bindings through cxx, native only, last changed in 2023.

Decision: write our own SAM-BA implementation in Rust from the protocol (the command set with the Arduino extensions, the nRF52 and SAMD families of Arduino’s bootloaders, and the 1200-baud touch), with BOSSA as a behaviour reference only: no code is ported, so the crate stays MIT OR Apache-2.0. A binding to BOSSA works natively only: its serial I/O is blocking C++ with exceptions, so running it in the browser would need a separate C++ to WebAssembly build and Chromium’s JSPI to suspend on Web Serial. That would mean a second toolchain and module to replace about 700 lines of Rust.

STK500 and AVR109 (Arduino’s AVR boards)

Surveyed on 2026-11-23. Arduino’s boards.txt (ArduinoCore-avr) uploads every AVR board with avrdude: upload.protocol=arduino (STK500v1: Optiboot on the Uno, ATmegaBOOT on the old Nano and Pro Mini), wiring (STK500v2: the Mega 2560’s bootloader) or avr109 (Caterina on the Leonardo, Micro and other ATmega32U4 boards, after a 1200-baud touch).

  • The protocols are documented by Atmel: application notes AVR061 (STK500 communication protocol), AVR068 (STK500v2) and AVR109 (self-programming).
  • avrdude: GPL-2.0-or-later, C, the reference uploader. nanoflash does not port from it.
  • Rust crates: none fits. ravedude 0.3.0 (MIT OR Apache-2.0, avr-hal) runs the avrdude binary; avrisp 0.3.1 (BSD-2-Clause, no_std) holds the SPI instructions of in-system programming, not the bootloaders’ serial protocols; avr-boot 0.3.2 (MIT) is for firmware that programs its own flash. Nothing speaks STK500v1, STK500v2 or AVR109 over an asynchronous transport, natively or in the browser.
  • The bootloaders run on the board and are behaviour references only: Optiboot (GPL-2.0), ATmegaBOOT and the wiring bootloader of the Mega 2560 (GPL-2.0-or-later, stk500boot.c in ArduinoCore-avr), and Caterina, derived from LUFA’s CDC bootloader. The wiring bootloader erases one page per page programmed, in order from 0x0, and never from 0x3C000 (its APP_END): nanoflash follows that order.
  • simavr: GPL-3.0, an AVR simulator; it runs the bootloaders from ArduinoCore-avr in mise run test-simavr, as a test tool installed or downloaded at test time, never committed or distributed with nanoflash.
  • Intel HEX, the format of Arduino’s images: ihex 3.0.0 (MIT OR Apache-2.0) needs std; nanoflash decodes it itself (no_std, fallible allocation) and uses ihex in its tests.

Decision: write the three protocols in Rust from Atmel’s application notes and from observing the bootloaders (and avrdude) on simavr and on boards, sharing the 1200-baud touch with SAM-BA: no code is ported from avrdude, Optiboot, ATmegaBOOT, the wiring bootloader, Caterina or simavr, and each file of src/avr/ says so in its first comment.

USB DFU

  • dfu-core 0.11.1: MIT OR Apache-2.0, #![no_std], sans-I/O (DfuIo trait), synchronous and async modes, DfuSe memory layouts.
  • dfu-nusb 0.2.0 (async, on nusb 0.2) and dfu-libusb 0.6.2: same licence.
  • webdfu: ISC, JavaScript, unmaintained.

Decision: reuse dfu-core over nanoflash’s USB transport (nusb natively and in the browser).

UF2

Decision: encode blocks ourselves (a 32-byte header and a 476-byte payload; about 50 lines); native writes copy the file onto the mounted drive, the browser writes through the File System Access API (a directory picker on the board’s drive).

CMSIS-DAP and Nordic serial DFU (later)

  • The probe-rs crate, in the command only. There is no CMSIS-DAP route in the browser: on 2026-11-30 the browser route through probe-rs was judged a dead end, because its WebAssembly build is several MB, over the limit of 256000 bytes of a module, and upstream did not take the proposed changes. DAPjs (MIT, JavaScript) would be a second engine, which is an anti-goal.
  • Nordic serial DFU: no Rust implementation surveyed in depth; to be revisited when the backend is scheduled.

Partition tables and file system images

NeedCrateLicenceno_std
Espressif partition tableesp-idf-part 0.6.0MIT OR Apache-2.0no (CSV, regex, deku)
MBRmbrman 0.7.0MIT OR Apache-2.0yes (new in 0.7)
GPTgpt_disk_types 0.16.1MIT OR Apache-2.0yes
GPT (reading, tests)gpt 4.1.0MITno
FAT imagefatfs 0.3.6MIT0.4 (unreleased)
LittleFS imagelittlefs2 0.8.1MIT OR Apache-2.0yes, but wraps C (littlefs2-sys)

esp-idf-part needs std, and both the Espressif table (32-byte entries plus an MD5 row) and the MBR (four 16-byte entries) are small fixed formats, so nanoflash writes them itself, no_std, and uses esp-idf-part, mbrman, ESP-IDF’s gen_esp32part.py and sfdisk in tests to read its output back. LittleFS image building stays native only (C toolchain); the browser accepts an image built elsewhere.

Transports

NeedNativeBrowser
Serialserialport 4.10.1 (MPL-2.0, used as a dependency, never copied)web-sys Web Serial (behind web_sys_unstable_apis); no maintained wrapper crate, so nanoflash writes a thin one. serialport’s Web Serial work (#165, PR #224 closed) did not land.
USBnusb 0.2.9 (Apache-2.0 OR MIT)nusb’s WebUSB backend (#199, since 0.2.6, async API only, --cfg=web_sys_unstable_apis)
Mass storage (UF2)std::fsFile System Access API

Web Serial and WebUSB are implemented by Chromium-based browsers only; the command line is the fallback everywhere else.

esp-web-tools manifest

Documented at esphome.github.io/esp-web-tools, types in src/const.ts:

  • top level: name, version, home_assistant_domain?, funding_url?, new_install_prompt_erase?, new_install_skip_erase? (deprecated), new_install_improv_wait_time?, builds[];
  • build: chipFamily (ESP32, ESP32-C2, ESP32-C3, ESP32-C5, ESP32-C6, ESP32-C61, ESP32-H2, ESP32-P4, ESP32-S2, ESP32-S3, ESP8266), parts[] with path (relative to the manifest, or a URL) and offset, and serialType? (cdc or uart, in the code only).

Licences of reference implementations

ReferenceLicenceHow nanoflash uses it
espflashMIT OR Apache-2.0reference for the loader; chip constants copied with attribution
esptool-jsApache-2.0reference for reset sequences in the browser
esptool (Python)GPL-2.0-or-laternot used
esp-flasher-stubApache-2.0 OR MITstubs, later
BOSSA, arduino/BOSSABSD-3-Clausebehaviour reference, no code ported
ArduinoCore-samd bootloaderLGPL-2.1protocol reference only, not vendored
avrdudeGPL-2.0-or-laterbehaviour reference only, no code ported
OptibootGPL-2.0behaviour reference only (on the board), no code ported
ATmegaBOOT, the wiring bootloader (ArduinoCore-avr)GPL-2.0-or-laterbehaviour reference only (on the board), no code ported
Caterina (ArduinoCore-avr)derived from LUFAbehaviour reference only (on the board), no code ported
simavrGPL-3.0test tool only, installed or downloaded at test time, never distributed
ihexMIT OR Apache-2.0test-only dependency
dfu-coreMIT OR Apache-2.0dependency
microsoft/uf2MITspecification and family identifiers
pico-sdkBSD-3-Clausefamily identifiers (cross-check)
probe-rsMIT OR Apache-2.0dependency (later)
DAPjsMITnot used
serialportMPL-2.0dependency only
Arduino Cloud AgentAGPL-3.0not used

nanoflash itself is licensed MIT OR Apache-2.0.

What could go upstream

  • espflash: an asynchronous transport trait (issue #1091), once nanoflash’s loop has run on hardware. This would let espflash itself run in the browser.
  • probe-rs: nothing. The route through asynchronous probes for WebUSB (#2958) is closed.
  • esp-idf-part: no_std support, so the Espressif writer can move next to the others.