Wi-Fi connection in MicroPython is the connection of the board to a wireless network using the network module.
So far, our programs lived isolated within the chip. The interesting part of the ESP32 and ESP8266 is their Wi-Fi radio. Thanks to it, we can send data to the cloud, control relays from a mobile phone, or synchronize the time with the internet.
In MicroPython, everything related to networking is handled through the standard module network.
Before writing code, it’s important to understand that our board can operate in two modes (and even both at the same time):
- Station (
IF_STA): The board behaves like your mobile phone or laptop. It connects to an existing Wi-Fi router to access the internet or local network. This is the most common mode. - Access Point (
IF_AP): The board behaves like a router. It creates its own Wi-Fi network, and other devices (your mobile phone or another board) connect to it. This is useful for initial configuration or in areas without coverage.
Station Mode: Connecting to the Router
This is the mode you will use 99% of the time for IoT projects. We want our board to connect to the home Wi-Fi to send data.
The process always follows these steps:
- Activate the station interface (
network.WLAN.IF_STA). - Connect using SSID (network name) and password.
- Wait for the router to assign us an IP (DHCP).
Connection Function with Timeout
Simply issuing the connection command is not enough; we must verify it was successful. You can include this reusable function in your boot.py.
import network
import time
def conectar_wifi(ssid, password):
# Create the station interface object
wlan = network.WLAN(network.WLAN.IF_STA)
# If already connected, do nothing
if not wlan.isconnected():
print('Connecting to network...')
# Activate the interface
wlan.active(True)
# Start the connection
wlan.connect(ssid, password)
# Wait until connected or 10 seconds pass
max_wait = 10
while not wlan.isconnected() and max_wait > 0:
print(f"Waiting for connection... {max_wait}")
time.sleep(1)
max_wait -= 1
# Final check
if wlan.isconnected():
print('Connection established!')
print('Network data (IP, mask, gateway, DNS):', wlan.ifconfig())
else:
print('Connection failed. Check password or range.')
# Function usage
conectar_wifi("MyHome_WiFi", "SuperSecretPassword")
The .ifconfig() method is very useful. It returns a tuple with 4 values: (IP, Subnet Mask, Gateway, DNS).
Disable the Default AP Mode
A curious (and sometimes annoying) detail is that many ESP32/ESP8266 boards come with the Access Point mode activated by default. This means that, even if you connect to your router, your board continues to broadcast an open network called “MicroPython-xxxx”.
To save power and improve security, it’s good practice to turn it off if you don’t use it:
ap = network.WLAN(network.WLAN.IF_AP)
ap.active(False) # Turn off the AP
Access Point Mode: Creating Your Own Network
Imagine you want to control a robot in the middle of a field where there are no routers. Or you have created a commercial product and need the user to enter their Wi-Fi password the first time.
That’s when we use AP mode. The board creates its own Wi-Fi network.
Creating the Access Point
import network
def crear_punto_acceso(ap_name, ap_password):
ap = network.WLAN(network.WLAN.IF_AP)
# Activate the interface
ap.active(True)
# Configure the AP
# security=3 corresponds to WPA2-PSK
ap.config(ssid=ap_name, key=ap_password, security=3)
print(f"Wi-Fi network created: {ap_name}")
print("AP IP address:", ap.ifconfig()[0])
# Usage
crear_punto_acceso("My_ESP32_Project", "12345678")
By default, the ESP32’s IP in AP mode is usually 192.168.4.1. If you connect your mobile phone to that network and open that IP in a browser, you will be “talking” to your board.
Password Length If you use WPA/WPA2 security (which you should), the password must be at least 8 characters long. If you use fewer, the AP will not start or will give an error.
Hybrid Mode (STA + AP)
The great thing about the ESP32/ESP8266 hardware is that it can keep both interfaces active simultaneously.
You can be connected to your home Wi-Fi to upload data to the cloud (STA) and, at the same time, create your own network (AP) so a technician can connect to configure parameters without needing access to the home network.
import network
# Instantiate both
sta = network.WLAN(network.WLAN.IF_STA)
ap = network.WLAN(network.WLAN.IF_AP)
# Activate both
sta.active(True)
ap.active(True)
# Configure independently...
sta.connect("HomeRouter", "password")
ap.config(ssid="Maintenance_Bot", key="admin123", security=3)
Security Best Practices
Do Not Write Passwords in main.py
Uploading your code to GitHub with your home keys hardcoded is a classic mistake.
It is recommended to create a separate file called secrets.py (and add it to .gitignore if you use git).
File secrets.py:
WIFI_SSID = "MyHome"
WIFI_PASS = "123456"
File main.py:
import secrets
from wifi_manager import conectar_wifi # Assuming you saved the function
conectar_wifi(secrets.WIFI_SSID, secrets.WIFI_PASS)
With this, we have opened the door to the world. In the next sections, we will use this connection to create web servers and send MQTT messages.