Connecting an ESP32 to WiFi in MicroPython takes about five lines. Keeping that connection alive through a wrong password, a router reboot or a weak signal takes a little more, and that is where most beginner scripts fail: they work once from Thonny, then sit silent when the board boots on its own.
Quick answer: import network, create network.WLAN(network.STA_IF), call active(True), then connect(ssid, password) and wait until isconnected() is true.
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("YOUR_WIFI_NAME", "YOUR_WIFI_PASSWORD")
while not wlan.isconnected():
time.sleep(0.5)
print(wlan.ifconfig()) # (ip, subnet, gateway, dns)That version waits forever if anything is wrong, so the rest of this guide upgrades it step by step. You will scan for networks, connect with a timeout, read the status code that says why a connection failed, keep credentials in a separate file, set a hostname or static IP, check signal strength and reconnect in the background with asyncio while your sensors keep running. Everything works on standard MicroPython for the ESP32, ESP32-S2, S3, C3 and C6 with no extra libraries, and the same network.WLAN code runs on the ESP8266 and the Raspberry Pi Pico W. If you prefer Arduino, the same journey is in the Arduino IDE WiFi tutorial.
What You Need
- An ESP32 board running MicroPython (if you have not flashed it yet, follow the MicroPython install guide for Thonny and esptool)
- A USB data cable and Thonny, or another serial REPL tool
- The name and password of a 2.4 GHz WiFi network
Every ESP32 variant is 2.4 GHz only, including the ESP32-C6 (its Wi-Fi 6 support is still 2.4 GHz). If your router has separate 2.4 GHz and 5 GHz names, use the 2.4 GHz one.
Before touching WiFi, confirm that MicroPython is really running. Type this in the Shell:
import network, os
print(os.uname())You should see the MicroPython release and your board name. If import network raises an ImportError, the board is not running a MicroPython firmware built for your chip, so fix that first (see MicroPython troubleshooting). The same network API also drives the Raspberry Pi Pico W, covered in the MicroPython ESP32 and Pico W guide.
Station Mode vs Access Point Mode
The ESP32 has two WiFi interfaces, and you pick one with a constant:
| Mode | Constant | What it does | Typical use |
|---|---|---|---|
| Station | network.STA_IF | Joins your existing router like a phone | Sensors, web servers, MQTT, cloud APIs |
| Access point | network.AP_IF | Creates its own network that others join | Setup pages, projects with no router |
Almost everything uses station mode, and that is what this guide builds. For completeness, this is a minimal access point:
import network
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid="ESP32-Setup", password="12345678", authmode=network.AUTH_WPA2_PSK)
print(ap.ifconfig()) # the board is usually reachable at 192.168.4.1The password must be at least 8 characters. Both interfaces can run at the same time, but for a first test use station mode only, so a problem is easier to place.
Scan for Nearby Networks
A scan answers the most useful debugging question: can the ESP32 even see my router?
import network
AUTH = {0: "open", 1: "WEP", 2: "WPA-PSK", 3: "WPA2-PSK", 4: "WPA/WPA2-PSK"}
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
networks = wlan.scan()
# blocks for a few seconds
networks.sort(key=lambda n: n[3], reverse=True)
# strongest first
for ssid, bssid, channel, rssi, auth, hidden in networks:
name = ssid.decode("utf-8", "ignore") or "<hidden>"
print("{:<28} ch {:>2} {:>4} dBm {}".format(name, channel, rssi, AUTH.get(auth, auth)))Each result is a tuple of name, BSSID, channel, signal strength in dBm, security mode and a hidden flag. Newer firmware builds report extra security values (for example WPA3), which the script prints as a plain number when it is not in the table.
If your network is missing from the list, the ESP32 cannot connect to it. The usual causes are a 5 GHz-only network, a hidden name, or a board that is simply too far away. A scan takes a few seconds and can briefly disturb an active connection, so run it while debugging, not in a loop.
Connect With a Timeout and Read the Status
A production script must give up after a set time and tell you why it failed. wlan.status() returns a code for that:
import network
import time
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
STATUS_TEXT = {
network.STAT_IDLE: "idle",
network.STAT_CONNECTING: "still connecting",
network.STAT_GOT_IP: "connected",
network.STAT_WRONG_PASSWORD: "wrong password",
network.STAT_NO_AP_FOUND: "network not found",
}
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < 15000:
# 15 second limit
status = wlan.status()
if status == network.STAT_GOT_IP:
break
if status in (network.STAT_WRONG_PASSWORD, network.STAT_NO_AP_FOUND):
break
# waiting longer will not help
time.sleep_ms(250)
status = wlan.status()
print("Result:", STATUS_TEXT.get(status, status))
if wlan.isconnected():
ip, subnet, gateway, dns = wlan.ifconfig()
print("IP:", ip, " gateway:", gateway, " DNS:", dns)Use time.ticks_ms() and time.ticks_diff() for timing, because they stay correct when the tick counter wraps around.
| Status | Meaning | What to check |
|---|---|---|
STAT_GOT_IP (1010) | Connected and has an address | Nothing, you are online on the local network |
STAT_CONNECTING (1001) | Still trying | Weak signal or a slow router, wait or raise the timeout |
STAT_NO_AP_FOUND (201) | The network name was not seen | Wrong name, 5 GHz only, out of range (run the scan) |
STAT_WRONG_PASSWORD (202) | Authentication failed | Recheck the password, try WPA2 instead of WPA3-only |
STAT_IDLE (1000) | Nothing in progress | connect() was never called or the interface is off |
Other codes exist on some builds, for example 200 (beacon timeout, signal lost), 203 and 204 (association or handshake failed). They match the reason codes in our ESP32 WiFi troubleshooting guide.
A WiFi link is not the same as internet. A valid IP address only proves the board joined the router. Test name lookup separately:
import socket
print(socket.getaddrinfo("micropython.org", 80)[0][-1]) # raises OSError if DNS or internet is downA Reusable wifi.py Module (and Why Credentials Live Elsewhere)
Do not paste your password into every script. Put it in one small file, and keep the connect logic in a module you import everywhere.
# config.py (never commit this file)
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"# wifi.py
import network
import time
import config
wlan = network.WLAN(network.STA_IF)
def connect(timeout_ms=15000):
"""Connect to WiFi. Returns True when connected, False on failure or timeout."""
wlan.active(True)
if wlan.isconnected():
return True
try:
wlan.connect(config.SSID, config.PASSWORD)
except OSError as e:
print("WiFi connect error:", e)
return False
start = time.ticks_ms()
while not wlan.isconnected():
if time.ticks_diff(time.ticks_ms(), start) > timeout_ms:
print("WiFi timeout, status:", wlan.status())
wlan.disconnect()
return False
time.sleep_ms(250)
print("WiFi connected:", wlan.ifconfig())
return True# main.py
import wifi
if wifi.connect():
print("Online, start the web server or MQTT client here")
else:
print("Running offline")Upload all three files to the board (in Thonny, right-click each file and choose Upload to /). main.py runs automatically after every reset, which is why the board now connects on its own at power-up. If you are unsure how the two startup files differ, read boot.py vs main.py.
Checking Signal Strength (RSSI)
Once connected, wlan.status("rssi") returns the current signal strength in dBm. It is negative, and closer to zero is better:
print("Signal:", wlan.status("rssi"), "dBm")| RSSI | Quality | What to expect |
|---|---|---|
| -30 to -50 dBm | Excellent | Fast and stable |
| -50 to -60 dBm | Good | Reliable for most projects |
| -60 to -70 dBm | Fair | Fine for small data |
| -70 to -80 dBm | Weak | Frequent drops, slow responses |
| Below -80 dBm | Very poor | Expect disconnects |
If the board drops often and the RSSI is worse than about -75 dBm, no code will fix it. Move the board or the router, or use a board with an external antenna connector.
Hostname, Static IP and MAC Address
Hostname. A name like esp32-garage is far easier to spot in your router's device list than a default one. Set it before connecting:
network.hostname("esp32-garage") # MicroPython 1.23 and later
# older builds: wlan.config(dhcp_hostname="esp32-garage")MAC address. You need it for router MAC filtering and DHCP reservations:
import ubinascii
print(ubinascii.hexlify(wlan.config("mac"), ":").decode())Static IP. Other devices, dashboards and Home Assistant work better when the board always has the same address. Set it before connect():
wlan.active(True)
wlan.ifconfig(("192.168.1.50", "255.255.255.0", "192.168.1.1", "192.168.1.1"))
# order: IP, subnet mask, gateway, DNS server
wlan.connect(SSID, PASSWORD)On MicroPython 1.24 and later, ifconfig() still works but the newer interface is ipconfig():
print(wlan.ipconfig("addr4")) # ('192.168.1.50', '255.255.255.0')
wlan.ipconfig(addr4="192.168.1.50/24", gw4="192.168.1.1")
network.ipconfig(dns="192.168.1.1")Pick an address outside your router's DHCP pool, and always give a real DNS server (the router's address works), because a static setup without DNS is the classic reason that IP addresses work but names do not. A DHCP reservation on the router achieves the same result with no code on the board, and the router steps are in the static IP guide.
Reconnect Automatically Without Blocking Your Code
Routers reboot, signals dip and leases expire. A script that connects once at boot will eventually stay offline for good. The cleanest fix is a background task that watches the link and retries with a growing delay, while your sensor code keeps running. MicroPython's asyncio makes that simple:
import network
try:
import asyncio
except ImportError:
import uasyncio as asyncio
# older MicroPython builds
import config
wlan = network.WLAN(network.STA_IF)
async def keep_wifi_alive(check_ms=5000, max_backoff_ms=60000):
backoff = 5000
while True:
if not wlan.isconnected():
print("WiFi down, connecting...")
wlan.active(True)
wlan.connect(config.SSID, config.PASSWORD)
for _ in range(60):
# up to 15 s, without blocking other tasks
if wlan.isconnected():
break
await asyncio.sleep_ms(250)
if wlan.isconnected():
print("Connected:", wlan.ifconfig())
backoff = 5000
# healthy again, reset the delay
else:
print("Failed, status", wlan.status(), "retry in", backoff // 1000, "s")
wlan.disconnect()
await asyncio.sleep_ms(backoff)
backoff = min(backoff * 2, max_backoff_ms)
# 5, 10, 20, 40, 60, 60...
await asyncio.sleep_ms(check_ms)
async def sensor_task():
while True:
print("reading sensor...")
# replace with your real measurement
await asyncio.sleep(2)
async def main():
asyncio.create_task(keep_wifi_alive())
await sensor_task()
asyncio.run(main())Three details make this reliable. The retry delay doubles up to a cap, so a router that is rebooting is not hammered with connection attempts. wlan.disconnect() before a retry clears a half-finished attempt, which avoids the OSError: Wifi Internal Error that appears when connect() is called while the driver is still busy. And every wait uses await asyncio.sleep_ms(), so the sensor task never stops while WiFi recovers.
On mains-powered boards that need steady response times, you can also turn off WiFi power saving with wlan.config(pm=network.WLAN.PM_NONE) on builds that support it. Do not use it on battery projects, where deep sleep is the better tool.
Keep Sensors and Outputs Safe When WiFi Fails
A common design mistake is making the whole program depend on WiFi. If a blocking connection loop runs before the first sensor reading, the device stops collecting data whenever the router is off.
A better structure is to read the sensor, check the value, show or store it locally, and then send it only if the network is up. If every reading matters, use a small bounded queue or write to a file, and decide what happens when memory fills up, because a microcontroller cannot buffer data forever.
If the board controls a relay, heater or motor, define a safe output state for network loss, for example "relay off". Never let a WiFi connection be the only safeguard against a hazardous output.
Turn Wi-Fi off when you don't need it. The radio is the biggest power draw on the board. A battery logger that sends data every few minutes should connect, send, then call wlan.active(False) (or go into deep sleep), not stay connected between readings.
Finally, test the failure path before you deploy: switch the router off, confirm the device reports offline and keeps its local work running, switch it back on, and confirm it reconnects without a power cycle. Also test a wrong password and a full reboot with the script saved on the board, not just pressing Run in Thonny.
Credentials and Security
- Keep
config.pyout of public repositories by adding it to.gitignore. If a password was ever committed, changing the password is the only real fix, because deleting the file does not remove it from history. - Do not print the password in logs or screenshots.
- WPA2 or WPA2/WPA3 mixed mode is the safest setting the ESP32 handles reliably. Avoid WEP and open networks for anything that matters.
- A WiFi password protects the radio link only. For sensitive data use TLS and keep certificate checking on. Disabling it just to make a connection work removes the protection you wanted.
- For a fleet of devices, plan how credentials can change without reflashing each board, for example a setup access point or a config file you can replace over USB.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Scan does not list your network | 5 GHz only, hidden name, too far | Use the 2.4 GHz network and move closer |
Status 201 (STAT_NO_AP_FOUND) | The name was not seen | Check spelling and case, run the scan |
Status 202 (STAT_WRONG_PASSWORD) | Wrong password or WPA3-only router | Retype the password (watch for trailing spaces), use WPA2 or mixed mode |
OSError: Wifi Not Started | The interface is not active | Call wlan.active(True) before connect() |
OSError: Wifi Internal Error | connect() called while busy | Call wlan.disconnect() first and add a retry delay |
| Works in Thonny, not after power-up | Script not saved as main.py, or a weak USB supply | Save it on the board and test with a short cable and a good charger |
| Connects, then drops every few minutes | Weak signal or an unstable supply | Check RSSI (worse than -75 dBm is trouble) and the power source |
| IP works but names fail | DNS missing, often a static IP without DNS | Add a DNS server to ifconfig() |
A very useful experiment is to try your phone's hotspot. If the ESP32 connects there but not to your router, your code and board are fine and the problem is a router setting such as WPA3-only mode, MAC filtering or band steering. On an iPhone, turn on Maximize Compatibility so the hotspot uses 2.4 GHz.
The causes and fixes are explained in much more depth in the ESP32 WiFi troubleshooting guide, which applies equally to MicroPython.
Frequently Asked Questions
Can MicroPython on the ESP32 use 5 GHz WiFi? No. The standard ESP32, ESP32-S3 and ESP32-C3 are 2.4 GHz only.
Do I need a library to connect to WiFi? No. The network module is built into the firmware.
Can I connect to a hidden network? Yes. Call wlan.connect(ssid, password) with the exact name. It will not show up cleanly in a scan, so type it carefully.
Why does isconnected() return False right after connect()? connect() only starts the attempt and returns at once. The link takes a second or more to come up, so always wait with a timeout as shown above.
Do I have to reconnect after deep sleep? Yes. Deep sleep powers the radio down and the program restarts from boot.py on wake, so call your wifi.connect() again. A static IP shortens the reconnect because the board skips DHCP.
How do I change the Wi-Fi password without reflashing? Keep the credentials in config.py and replace just that file over USB, or build a small setup access point that writes a new config.py from a web form.
How do I get the correct time after connecting? Call ntptime.settime() once the board is online. It sets the clock in UTC.
What should I build next? Serve a page with the MicroPython web server, send readings over MQTT with umqtt, or compare the two languages in MicroPython vs Arduino on ESP32.




