Skip to content

Guide

boot.py vs main.py in MicroPython: Startup Order, What Goes Where, Recovery

Understand the difference between boot.py and main.py in MicroPython, startup order, Wi-Fi setup, project structure, and recovery from boot errors.

  • 5 min read
  • Updated November 7, 2026
boot.py vs main.py in MicroPython: Startup Order, What Goes Where, Recovery

Every MicroPython board, whether an ESP32, ESP8266, Raspberry Pi Pico or Pico W, looks for two files when it starts: boot.py and main.py. Knowing which one runs when, and what belongs in each, is the difference between a board that starts your project reliably on its own and one you can't get back into.

Quick answer: after every reset, MicroPython runs boot.py first, then main.py, then opens the REPL if main.py finishes. Put your program in main.py. Keep boot.py short, or leave it with its default contents: it's for low-level setup such as WebREPL. Never put an endless loop in boot.py, because main.py would never start. To run code automatically, save it on the board as main.py; pressing Run in Thonny doesn't do that.

Below: the exact startup order, what to put in each file, a project layout, how to tell why the board reset, and how to recover a board whose main.py won't let you in.

MicroPython startup order: reset, filesystem mount, boot.py, main.py, then the REPL; Ctrl+D runs boot.py and main.py again

The Startup Order

  1. Reset: power-on, the reset button, machine.reset() or waking from deep sleep.
  2. The firmware starts and mounts the board's flash filesystem. On the ESP32 and ESP8266, a built-in script (_boot.py) does this, and creates a default boot.py the first time if none exists.
  3. boot.py runs, if it's present.
  4. main.py runs, if it's present.
  5. The REPL starts (>>>) once main.py returns, raises an uncaught exception or is stopped with Ctrl+C.

A soft reset (Ctrl+D in the REPL, or Thonny's Stop/Restart) restarts the interpreter and runs boot.py and main.py again, but doesn't reset the hardware: Wi-Fi may stay connected and pins keep their state. A hard reset (the button, unplugging, machine.reset()) starts everything from scratch.

Two details that matter in practice:

  • An exception in boot.py doesn't stop main.py. The error is printed and startup carries on. What blocks main.py is code in boot.py that never finishes: an endless loop or a Wi-Fi wait with no timeout.
  • Thonny interrupts main.py when it connects. Opening Thonny, or clicking Stop, sends Ctrl+C, so a main.py that seems not to start may simply have been stopped by the IDE. To test real autostart, unplug the board from the computer and power it from a USB charger or battery.

What Goes in boot.py

Most projects never need to edit it. Use it only for setup that must happen before anything else, and that always finishes quickly:

main.py
# boot.py: runs first on every reset
import esp
esp.osdebug(None)          # ESP32/ESP8266: silence low-level debug output on the serial port

import machine
machine.freq(160_000_000)  # ESP32: run at 160 MHz to save a little power (default is 240 MHz)

# import webrepl
# webrepl.start()           # browser-based REPL over Wi-Fi; needs a network connection first

Good in boot.py: WebREPL, the CPU clock, turning off debug output, mounting an SD card that main.py needs, setting outputs that must be in a safe state immediately (a relay pin held off).

Not in boot.py: your main loop, waiting for Wi-Fi without a timeout, anything that sleeps for long, or imports of large libraries that might fail. If you're unsure, put it in main.py.

What Goes in main.py

main.py is your program. It can run once and finish, or loop forever; both are fine. As a project grows, keep main.py short and move the work into modules:

main.py
# main.py
import time
import wifi        # your wifi.py: defines connect(), doesn't connect on import
import sensors     # your sensors.py

online = wifi.connect(timeout_ms=15000)
print("online" if online else "offline, running locally")

while True:
    reading = sensors.read()
    print(reading)
    time.sleep(5)

A connect function with a timeout, status codes and auto-reconnect is in ESP32 Wi-Fi with MicroPython; the same wifi.py works on the Pico W.

Modules shouldn't do things when imported. Define functions in wifi.py and sensors.py, and let main.py call them. A module that connects to Wi-Fi or starts a loop at import time makes startup unpredictable and is hard to test from the REPL.

Prove the Order on Your Board

Save these two files to the device (in Thonny: File → Save as… → MicroPython device):

main.py
# boot.py
print("1. boot.py")
main.py
# main.py
print("2. main.py")

Press Ctrl+D in the Shell. You'll see 1. boot.py, then 2. main.py, then >>>. If only one line appears, check the file names in the Files panel (they're case-sensitive, and Main.py won't run) and that they're on the device, not your computer. Then restore boot.py to what it was.

Blink on Boot: A Complete Example

Save as main.py on the board, unplug it from the computer, and power it from a USB charger. The LED starts blinking on its own.

main.py
from machine import Pin
from time import sleep

# ESP32 DevKit V1: blue LED on GPIO 2. Pico / Pico W: use Pin("LED").
led = Pin(2, Pin.OUT)

while True:
    led.toggle()
    sleep(0.5)

The official ESP32 DevKitC has no user LED; wire one to GPIO 2 through a 220 Ω resistor. The endless loop is fine here because it's in main.py.

Know Why the Board Started

main.py runs after every kind of reset, so it often needs to know which one it was. A battery sensor, for example, should take a reading and sleep again after a deep-sleep wake, but print a welcome message after a power-on:

main.py
import machine

cause = machine.reset_cause()
if cause == machine.DEEPSLEEP_RESET:
    print("Woke from deep sleep")
elif cause == machine.PWRON_RESET:
    print("Power-on")
elif cause == machine.WDT_RESET:
    print("Watchdog reset: the program hung last time")
else:
    print("Reset cause:", cause)

Deep sleep and wake sources are covered in MicroPython deep sleep on the ESP32.

Build In a Way Back

A main.py that starts straight into a tight loop or a long sleep can make it hard to reach the REPL. Two cheap habits prevent that.

A short delay before your program starts, so Ctrl+C has a window:

main.py
# main.py
import time
print("Starting in 3 s, press Ctrl+C to cancel")
time.sleep(3)
import app        # your real program lives in app.py

A safe-mode jumper. Check a spare pin at startup; if it's connected to GND, skip the application:

main.py
# main.py
from machine import Pin

if Pin(13, Pin.IN, Pin.PULL_UP).value() == 0:   # jumper from GPIO 13 to GND
    print("Safe mode: app not started")
else:
    import app

Avoid the ESP32's BOOT button (GPIO 0) for this: holding it during reset puts the chip into firmware download mode instead.

Recovering a Board That Won't Let You In

Work down this list; most boards are back after step 1 or 2.

  1. Interrupt it. Click in Thonny's Shell, press the board's reset button, then press Ctrl+C several times straight away.
  2. Remove the file. Once you have >>>, rename it so it no longer runs: import os; os.rename("main.py", "main_off.py"). From a terminal, mpremote fs rm :main.py does the same.
  3. Check boot.py. If the problem is there, rename it the same way. MicroPython starts fine without one.
  4. Erase and reflash, as a last resort. On the ESP32 erase the flash with esptool; on a Pico, copy Raspberry Pi's flash_nuke.uf2 in BOOTSEL mode. This deletes every file, so it's the final option. Steps are in installing MicroPython on the ESP32 and on the Pico.

Common Mistakes

MistakeWhat happensFix
Code saved on the computer, not the boardRuns from Thonny, not on its ownSave as main.py on the MicroPython device
File named Main.py or main.py.pyNever runsRename to exactly main.py
Main loop in boot.pymain.py never runs; REPL hard to reachMove the loop to main.py
Wi-Fi wait with no timeoutBoard hangs at startup when the router is offUse a timeout and continue offline
Testing autostart while Thonny is connectedmain.py seems not to runThonny stopped it; power the board from a charger
A module named network.py or machine.pyImports breakDon't reuse built-in module names
Program crashes and stops silentlyNo way to see the error after unpluggingWrap the main loop in try/except and log errors to a file

For specific error messages, see MicroPython troubleshooting.

A Project Layout That Scales

Output
/                 (board filesystem)
├── boot.py       default, or a few lines of setup
├── main.py       starts the application
├── app.py        main loop (optional, for the safe-start pattern)
├── config.py     Wi-Fi name and password: keep out of Git
├── wifi.py       connect() with a timeout
├── sensors.py    read() functions
└── lib/          third-party libraries (installed with mip)

A beginner's LED blink needs only main.py. A Wi-Fi sensor node grows into the layout above without changing how it starts.

FAQ

What's the difference between boot.py and main.py? Both run automatically on every reset, boot.py first. boot.py is for brief setup; main.py is your program.

Do I need a boot.py? No. If it's missing, MicroPython goes straight to main.py. The ESP32 and ESP8266 create a default one that's almost empty.

How do I make my code run automatically? Save it on the board as main.py, then reset or power-cycle.

How do I stop main.py from running? Press Ctrl+C in the REPL. To stop it running at all, rename or delete the file.

Does Ctrl+D run boot.py again? Yes. A soft reset runs boot.py and main.py again.

Is this the same on the Raspberry Pi Pico? Yes. The Pico runs boot.py then main.py from its filesystem in the same way.

Does CircuitPython use the same files? No. CircuitPython uses code.py (or main.py) and boot.py with different rules, including a USB safe mode.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.