A MicroPython error rarely tells you which layer is broken. Thonny can't find the port, a script stops with a one-line traceback, or the board just resets in a loop. The cause could be a USB cable, a driver, the firmware, a missing file, a wiring fault, the Wi-Fi network, or simply running out of RAM.
The fastest way through is to work from the bottom layer up: USB and port, then the REPL, then imports, then one peripheral at a time, then the network, then memory. This guide is organised by symptom, so you can find the exact message you're seeing, confirm the cause with a short test, and apply the smallest fix. Examples use ESP32 and Raspberry Pi Pico boards. Exact messages and error numbers can differ between ports and firmware versions, so treat them as a pointer to the layer that is failing.
Find Your Error Fast
| What you see | Likely cause | First thing to try | Section |
|---|---|---|---|
| No port in Thonny's interpreter menu | Charge-only cable or missing USB driver | Swap to a data cable, check Device Manager | Thonny |
Device is busy or does not respond | A program is running, or another app holds the port | Press Ctrl+C, close other serial tools | Thonny |
| Board resets over and over | Crashing main.py or a brownout | Interrupt right after reset, use a better supply | Boot loops |
ImportError: no module named 'x' | Module not on the board, or wrong path | Copy it to /lib, or install it with mip | ImportError |
OSError: [Errno 19] ENODEV | I²C device not responding | Run i2c.scan() | OSError |
OSError: [Errno 2] ENOENT | File or folder not found | List files with os.listdir() | OSError |
OSError: [Errno 28] ENOSPC | Flash filesystem is full | Check free space with os.statvfs('/') | OSError |
| Wi-Fi never connects | Wrong password, 5GHz-only network, weak signal | Print wlan.status() | Wi-Fi |
MemoryError: memory allocation failed | Heap exhausted or fragmented | gc.collect(), then use smaller buffers | MemoryError |
Before You Change Anything: Collect Evidence
Reflashing firmware or rewriting a whole project before you understand the error can erase useful files and hide the original cause. Spend two minutes collecting facts first.
Run this in the REPL to record exactly what is on the board:
import sys, os
print(sys.implementation)
print(os.uname())Write down the board model, your operating system, the Thonny version, the full error text, and what you did just before it appeared. If a sensor or display is involved, note its exact model and wiring. Never paste Wi-Fi passwords or API keys into screenshots or forum posts.
Back up your files first. In Thonny, open View → Files, right-click a file on the board, and choose Download to. With mpremote you can copy a file to your computer with mpremote fs cp :main.py main_backup.py. Erasing flash or reflashing firmware can remove main.py, drivers and config files.
Then shrink the problem. Test the REPL with print("hello"), then one peripheral at a time, and change only one thing between attempts. That separates a code problem from a cable, firmware or power problem.
Thonny Cannot Find or Open the Port
No port appears in the interpreter menu. Start with the cable. Many USB cables are charge-only and power the board without carrying data. Try a known data cable, another USB port, and avoid unpowered hubs. Then check that your computer sees a serial device at all:
- Windows: open Device Manager and look under Ports (COM & LPT). An unknown device or a yellow warning icon means a missing driver.
- Linux: run
ls /dev/ttyUSB* /dev/ttyACM*. If the port exists but Thonny reports permission denied, add yourself to the serial group withsudo usermod -aG dialout $USER, then log out and back in. - macOS: look for
/dev/cu.usbserial*or/dev/cu.usbmodem*.
The driver you need depends on how the board talks USB:
| USB interface | Typical boards | Driver |
|---|---|---|
| CP210x bridge chip | Many ESP32 dev boards | Silicon Labs CP210x driver |
| CH340 / CH9102 bridge chip | Many low-cost ESP32 and ESP8266 boards | WCH driver |
| Native USB | Raspberry Pi Pico, ESP32-S2, S3 and C3 boards | Usually none on current Windows, macOS and Linux |
The port appears but won't open. An error such as could not open port 'COM3': PermissionError(13, 'Access is denied.') means something else is holding the port. Close other Thonny windows, serial monitors and terminals, unplug and reconnect the board, then select the port again. Pick the device that is currently listed rather than an old COM number from a tutorial.
"Device is busy or does not respond." Thonny shows this when the board is running a program or isn't answering. Press Ctrl+C in the shell to interrupt, press the board's reset button, and try another cable before assuming the firmware is damaged.
Connected, but no >>> prompt. Check Tools → Options → Interpreter. It must be set to MicroPython for your board (for example MicroPython (ESP32) or MicroPython (Raspberry Pi Pico)), not Local Python 3. If a script prints continuously, the prompt can be buried in the output, so press Ctrl+C.
The board has no MicroPython yet. A Pico in BOOTSEL mode appears as a drive named RPI-RP2 (RP2350 on a Pico 2), and Thonny can install MicroPython from the interpreter settings; the full steps are in installing MicroPython on the ESP32 and on the Pico W and Pico 2 W. For ESP32 boards, esptool errors such as Failed to connect to ESP32: Wrong boot mode detected or Timed out waiting for packet header usually mean the board isn't in download mode. Hold the BOOT button while the tool starts connecting, then release it.
REPL Frozen or Board Stuck in a Boot Loop
On boot, MicroPython runs boot.py and then main.py. If main.py crashes, loops forever or resets the board, you never get a usable prompt. Work through these in order.
1. Interrupt it. Press Ctrl+C in the shell. In Thonny you can also use Run → Stop/Restart backend (Ctrl+F2). Ctrl+D in the REPL performs a soft reboot, but a saved main.py will simply run again. If Ctrl+C has no effect, the program is probably blocked inside a long call, such as a network connect with no timeout, so reset the board.
2. Remove the bad startup file. Connect right after a reset and delete or rename main.py:
mpremote fs rm :main.pyYou can also delete it from the View → Files panel in Thonny. MicroPython has no universal "safe mode" like CircuitPython does, so the exact recovery steps depend on your board and port.
3. Give yourself a way back in. While you develop, keep main.py tiny and add a short grace period before your real program starts:
# main.py
import time
print("Starting in 3 seconds... press Ctrl+C to cancel")
time.sleep(3)
import app # your real program lives in app.pyPressing Ctrl+C during the delay drops you straight to the REPL.
4. Rule out a brownout. If the shell shows Brownout detector was triggered before each reset, the board isn't getting enough power. Wi-Fi transmit bursts, motors, servos and LED strips all cause current spikes. Try a shorter, thicker USB cable, a powered USB port, or a separate supply for the load with a common ground.
5. Wipe and reflash only as a last resort. Back up your files first. On an ESP32, esptool erase-flash (esptool.py erase_flash on esptool 4.x) removes everything. On a Pico, a flash-erase UF2 from Raspberry Pi does the same. Reflashing is rarely the answer to an ordinary Python exception.
ImportError: Missing Modules
When a module can't be loaded, MicroPython raises ImportError: no module named 'ssd1306'. (MicroPython doesn't use CPython's ModuleNotFoundError.) A library installed in desktop Python is not available on the microcontroller, so the usual causes are:
- The module isn't built into your firmware.
- The
.pyfile is on your computer but not on the board. - The file is in the wrong place or the name doesn't match, and filenames are case-sensitive.
- Your own file shadows a built-in module, for example a script named
network.pyormachine.py.
Check what the board can actually see:
import sys, os
print(sys.path) # usually includes '' and '/lib'
print(os.listdir()) # files in the current folder
print(os.listdir('/lib')) # installed librariesPut drivers in /lib or next to your script. Then install missing packages from micropython-lib. On recent firmware use mip, either on the board over Wi-Fi or from your computer over USB:
import mip
mip.install("umqtt.simple") # needs a Wi-Fi connection on the boardmpremote mip install umqtt.simpleOlder firmware used upip instead. In Thonny you can also use Tools → Manage packages. Some libraries depend on native modules that aren't in your firmware, and copying the Python file won't fix that. Pick a compatible implementation instead.
Two more cases are worth knowing. ImportError: can't import name usually means the library version doesn't match the API your code expects. A MemoryError during import means the board ran out of RAM while compiling a large file. Compile it to .mpy with mpy-cross, or freeze it into the firmware.
OSError: Read the Errno, Not Just the Word
OSError covers many different failures: a missing file, a full filesystem, a sensor that didn't answer, a dropped connection. The useful part is the error name and number. Numbers can differ between ports, so compare against names from the errno module in your code.
| Error | Typical meaning |
|---|---|
ENOENT (Errno 2) | File or folder not found. Check the path and spelling. |
EIO (Errno 5) | I/O failure. On a Pico this is a common I²C "no acknowledge" result. |
ENOMEM (Errno 12) | Out of memory in the system or network stack. See the MemoryError section. |
EBUSY (Errno 16) | Resource already in use, such as a bus or pin another part of your program holds. |
ENODEV (Errno 19) | No such device. On an ESP32 this is the usual I²C "nothing answered" error. |
ENOSPC (Errno 28) | No space left on the filesystem. |
ETIMEDOUT | Operation timed out: a sensor, a socket or a Wi-Fi call. |
Catch it and print the name instead of hiding the failure with an empty except:
import errno
try:
do_something()
except OSError as e:
print("OSError:", e.errno, errno.errorcode.get(e.errno, "unknown"))I²C sensors and displays. Scan the bus as a separate test before blaming the driver:
from machine import I2C, Pin
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000) # ESP32 default pins
# i2c = I2C(0, scl=Pin(9), sda=Pin(8)) # Pico: GP9 = SCL, GP8 = SDA
print([hex(a) for a in i2c.scan()])An empty list means the sensor isn't answering, and no driver can fix that. Check power (most modules want 3.3V), ground, SDA and SCL not swapped, pull-up resistors, and the device address. If the address shows up but reads fail, check the exact sensor model and the driver's API.
DHT sensors. OSError: [Errno 110] ETIMEDOUT (or a similar timeout) from dht.DHT22(...).measure() means the sensor never answered. Check wiring, 3.3V power, a 4.7kΩ to 10kΩ pull-up on the data line, and wait at least two seconds between DHT22 reads.
Filesystem errors. ENOENT means the path is wrong, so print os.listdir() to see what exists. ENOSPC means flash is full. Check free space like this:
import os
s = os.statvfs('/')
print("Free KB:", s[0] * s[3] // 1024)Delete old logs and large unused files, and avoid writing logs to flash in a fast loop. If you need lots of storage, use an SD card.
Wi-Fi Fails to Connect
Start with the basics: ESP32, ESP8266 and Pico W only support 2.4GHz Wi-Fi. A network that is 5GHz-only will never appear, and a router that merges both bands under one name can steer devices wrongly. WPA2, or mixed WPA2/WPA3, is the safest security mode. Also confirm that your board actually has Wi-Fi, because not every board does.
Use a bounded wait so a missing network doesn't hang your program, and print the status code when it fails:
import network, time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("YOUR_WIFI_NAME", "YOUR_WIFI_PASSWORD")
deadline = time.ticks_add(time.ticks_ms(), 15000)
while not wlan.isconnected() and time.ticks_diff(deadline, time.ticks_ms()) > 0:
time.sleep_ms(250)
if wlan.isconnected():
print("IP:", wlan.ifconfig()[0])
else:
print("Failed, status:", wlan.status())Compare that status with the constants on the network module:
| Status | What it usually means |
|---|---|
network.STAT_NO_AP_FOUND | The SSID wasn't seen: typo, 5GHz-only network, or out of range |
network.STAT_WRONG_PASSWORD | The password is wrong |
network.STAT_CONNECTING | Still trying: wait longer or move closer to the router |
To see what the board can hear, run wlan.scan(). It lists nearby networks with their channel and signal strength. A very weak signal is a common reason for flaky connections.
If you get OSError: Wifi Internal Error on an ESP32, the Wi-Fi interface is in a bad state. Turn it off and on again before reconnecting: wlan.active(False), wait a moment, then wlan.active(True).
Other causes to rule out: router client isolation, MAC filtering, and captive-portal networks (hotels, campuses) that need a browser login and can't be used by a microcontroller. Wi-Fi also draws current spikes when it connects, so a weak USB supply can reset the board right at that moment, which looks like a Wi-Fi bug but is a power problem.
A connected board doesn't prove the internet works. Test DNS separately with socket.getaddrinfo("example.com", 80), and reconnect with a delay rather than retrying in a tight loop. Keep credentials in a separate secrets.py file that you never publish. For a complete connect, status-code and auto-reconnect setup, see Connect an ESP32 to Wi-Fi with MicroPython.
MQTT and Socket Connection Problems
If the MQTT library imports fine but won't connect, separate client problems from network and broker problems. Test the plain connection first:
from umqtt.simple import MQTTClient
import machine, ubinascii
client_id = b"esp32-" + ubinascii.hexlify(machine.unique_id())
client = MQTTClient(client_id, "192.168.1.50", port=1883, keepalive=60)
client.connect()
client.publish(b"test/hello", b"hi")
client.disconnect()localhostis the board itself. Use your computer's LAN IP address for a local broker, notlocalhostor127.0.0.1.- A local Mosquitto broker may only listen on localhost. Mosquitto 2.x does this by default. Add a
listener 1883line and an authentication setup to its config before other devices can reach it. ECONNREFUSEDmeans nothing is listening on that port (1883 is plain MQTT, 8883 is TLS).ETIMEDOUTpoints to a wrong IP address, routing or a firewall.MQTTException: 5means the broker rejected your credentials or access rules. Code 4 means a bad username or password.- Connection drops every minute or so.
umqtt.simpledoesn't send keep-alive pings by itself. Callclient.ping()regularly orclient.check_msg()in your loop, and give each device a unique client ID, because two clients with the same ID keep kicking each other off. - A subscriber receives nothing. Topic names are case-sensitive, so check the exact spelling.
Never expose an unauthenticated broker or a raw microcontroller web server to the public internet. Use unique credentials and topic permissions, and TLS where your setup supports it. For how brokers, topics and QoS fit together, see MQTT Explained; for a working publish-and-subscribe example, see MicroPython MQTT with umqtt on the ESP32.
MemoryError and Heap Problems
A typical message is MemoryError: memory allocation failed, allocating 8192 bytes. It tells you the size of the allocation that failed. The surprise is that your board can have plenty of free RAM in total and still fail, because MicroPython needs one contiguous block. After many small allocations the heap fragments into gaps, and a large buffer no longer fits.
Measure before changing anything:
import gc, micropython
gc.collect()
print("Free:", gc.mem_free(), "Used:", gc.mem_alloc())
micropython.mem_info() # heap summary
micropython.mem_info(1) # also prints a map of the heapgc.collect() frees objects nothing refers to any more. It can't free memory your program still holds, and it can't fix code that keeps allocating more.
Practical fixes, roughly in order of payoff:
- Allocate big buffers once, early. Create
bytearraybuffers at startup and reuse them instead of building new ones in a loop. - Don't build strings with
+=in a loop. Each step creates a new object. Use"".join(...)or format into a preallocated buffer. - Process data in chunks. Read files and network data in small pieces, and don't collect unlimited samples in a list.
- Slice with
memoryview. It avoids copying large buffers. - Call
gc.collect()right before a big allocation. - Do HTTPS and TLS work early. TLS needs a large contiguous block, so connect soon after boot and run
gc.collect()first. Failures often show up asOSError: [Errno 12] ENOMEM. - Precompile large modules to
.mpywithmpy-crossso importing them needs less RAM.
A 128×64 monochrome display buffer is about 1KB, but the driver, Python objects, Wi-Fi, TLS and your own data add up fast. Camera frames, big JSON payloads and colour displays need far more. If a project truly needs more room, move to a board with more RAM, such as an ESP32 module with PSRAM (using a matching firmware build) or a Pico 2. A successful import doesn't guarantee enough memory is left for the library's full runtime workload.
GPIO and Hardware Behaving Strangely
An invalid pin raises ValueError: invalid pin. On an ESP32, Pin(34, Pin.OUT) fails with ValueError: pin can only be input, because GPIO34 to GPIO39 are input-only. Some pins are reserved for flash (GPIO6 to GPIO11 on a classic ESP32), and some affect boot behaviour. Board labels aren't always the same as GPIO numbers, so check your board's pinout, such as the ESP32 pinout guide, the Pico W pinout guide or the Pico 2 pinout guide. Start with a known-safe output and an LED through a resistor.
If a button reads the opposite of what you expect, check how it is wired. A button between the pin and ground needs the internal pull-up:
from machine import Pin
button = Pin(14, Pin.IN, Pin.PULL_UP)
# button between GPIO14 and GND
print(button.value())
# 1 = released, 0 = pressedOn a Pico 2, prefer this pull-up wiring: early RP2350 chips have an erratum (E9) that can leave an input with the internal pull-down stuck reading HIGH.
Mechanical contacts bounce, so one press can produce several transitions unless you debounce it in software.
If a motor, relay or servo makes the board reset, disconnect it and test the microcontroller alone. GPIO pins carry logic signals, not load current. Use a driver or transistor, a separate supply sized for the load, and a common ground. Never rewire a powered circuit where a short across the supply rails is possible.
A Repeatable Recovery Checklist
When an error persists, go back to a known baseline and rebuild upward:
- Back up your files and note the firmware version.
- Confirm the interpreter and port, and run
print(1 + 1)in the REPL. - Run a minimal script that does nothing else.
- Test each peripheral on its own.
- Add Wi-Fi, then MQTT or HTTP, only after the layer below works.
- Check memory with
gc.mem_free()once everything is running together. - Write down the cause and how you confirmed the fix.
Reflash firmware only when the evidence points there: os.uname() shows the wrong build, the filesystem is corrupted so every file operation fails, or the REPL is unreachable even after a clean boot. Use the official MicroPython documentation for your port, your board's pinout and the peripheral datasheet as primary references. Forum snippets are useful clues, but APIs change and similar-looking boards can have different pins.
Quick Answers to Common MicroPython Error Questions
Why does Thonny say the device is busy? Either a program is still running or another application holds the serial port. Press Ctrl+C, close other serial tools, and reconnect the board.
Is ImportError the same as ModuleNotFoundError? MicroPython raises ImportError: no module named 'x' and doesn't have ModuleNotFoundError. The fix is the same: get the module onto the board, in /lib or next to your script.
Can I use pip on a microcontroller? No. Use mip (or upip on older firmware), mpremote mip install, or copy the library file to the board.
Why does my ESP32 keep rebooting when Wi-Fi connects? Often a brownout. Check for Brownout detector was triggered in the shell and try a better cable or power supply.
Why do I get a MemoryError when RAM shows as free? Fragmentation. Free memory exists but not in one large enough block. Allocate large buffers early, reuse them, and run gc.collect() before big allocations.
Does reflashing delete my files? Erasing flash does. Some flashing methods leave the filesystem alone, but don't rely on that, so back up first.
How do I check free flash space? Use os.statvfs('/') as shown in the OSError section.
Where to Go From Here
Once you treat each error as a clue to one layer, most MicroPython problems take minutes instead of hours. A good habit is to keep a tiny, known-good test script for each layer, such as a REPL check, an i2c.scan(), a Wi-Fi connect and a memory printout, so you can prove what works before you debug what doesn't. When your board connects reliably, the next step is publishing sensor data, which MQTT Explained walks through. To save battery between readings, see MicroPython deep sleep and wake sources.




