Session 1: Wi-Fi Basics in MicroPython
Synopsis
Covers station mode setup, connecting to wireless networks, IP configuration, and the practical constraints of networking on a microcontroller.
Session Content
Session 1: Wi-Fi Basics in MicroPython
Session Overview
Duration: ~45 minutes
Audience: Python developers with basic programming knowledge
Platform: Raspberry Pi Pico 2 W
IDE: Thonny
Language: MicroPython
Learning Outcomes
By the end of this session, learners will be able to: - Set up Thonny for MicroPython development on the Pico 2 W - Connect the Pico 2 W to a Wi-Fi network - Retrieve and display network information - Understand the basics of Wi-Fi-related MicroPython APIs - Write a simple script that checks Wi-Fi connection status
Prerequisites
- Raspberry Pi Pico 2 W
- USB cable for power and data
- Wi-Fi network name (SSID) and password
- Thonny installed on a computer
- MicroPython firmware for Raspberry Pi Pico 2 W
Development Environment Setup
1) Install Thonny
- Download and install Thonny from: https://thonny.org
- Launch Thonny
2) Install MicroPython firmware on the Pico 2 W
- Hold BOOTSEL while connecting the Pico 2 W to USB.
- Copy the appropriate MicroPython UF2 firmware to the Pico drive.
- The board will reboot automatically.
3) Configure Thonny
- Open Tools > Options > Interpreter
- Select:
- Interpreter: MicroPython (Raspberry Pi Pico)
- Port: Auto-detect or the Pico 2 W serial port
- Click OK
4) Verify connection
In the Thonny shell, run:
print("Hello, Pico 2 W!")
Expected output:
Hello, Pico 2 W!
Theory: Wi-Fi on the Pico 2 W
What is Wi-Fi in MicroPython?
The Pico 2 W includes wireless networking hardware that can be controlled using the network module in MicroPython. This module lets you:
- Enable the wireless interface
- Connect to a local access point
- Check connection status
- Read network configuration such as IP address
Key Concepts
- Station mode (
STA_IF): The Pico connects to an existing Wi-Fi network. - Access point mode (
AP_IF): The Pico creates its own Wi-Fi network. - DHCP: The router typically assigns the Pico an IP address automatically.
- SSID: The Wi-Fi network name.
- Password: Network security credential.
Common Wi-Fi tasks
- Activating Wi-Fi
- Scanning for available networks
- Connecting to a router
- Waiting for connection
- Checking IP configuration
Hands-On Exercise 1: Connect to Wi-Fi
Goal
Connect the Pico 2 W to a Wi-Fi network and display the assigned IP address.
Code
Create a new file in Thonny and save it as main.py on the Pico.
import network
import time
# Replace these with your Wi-Fi credentials
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
# Create a station interface (connect to an existing Wi-Fi network)
wlan = network.WLAN(network.STA_IF)
# Activate the Wi-Fi interface
wlan.active(True)
print("Connecting to Wi-Fi...")
# Start the connection process
wlan.connect(SSID, PASSWORD)
# Wait for the connection to complete
timeout = 15
start_time = time.time()
while not wlan.isconnected():
if time.time() - start_time > timeout:
print("Connection timed out.")
break
print("Waiting for connection...")
time.sleep(1)
# Show network details if connected
if wlan.isconnected():
print("Connected successfully!")
print("Network config:", wlan.ifconfig())
else:
print("Not connected.")
Expected Output
Connecting to Wi-Fi...
Waiting for connection...
Waiting for connection...
Connected successfully!
Network config: ('192.168.1.42', '255.255.255.0', '192.168.1.1', '192.168.1.1')
Notes
- Replace
YOUR_WIFI_NAMEandYOUR_WIFI_PASSWORDwith your actual credentials. - If the connection fails, verify the SSID/password and ensure the Pico 2 W is within range.
Hands-On Exercise 2: Scan for Nearby Networks
Goal
List nearby Wi-Fi networks and their signal strengths.
Code
import network
# Enable station interface
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Scanning for networks...")
# Scan returns a list of tuples with network details
networks = wlan.scan()
for net in networks:
ssid = net[0].decode("utf-8")
bssid = ":".join("{:02x}".format(b) for b in net[1])
channel = net[2]
rssi = net[3]
security = net[4]
hidden = net[5]
print("SSID:", ssid)
print(" BSSID:", bssid)
print(" Channel:", channel)
print(" Signal (RSSI):", rssi)
print(" Security:", security)
print(" Hidden:", hidden)
print("-" * 30)
Expected Output
Scanning for networks...
SSID: HomeWiFi
BSSID: 12:34:56:78:9a:bc
Channel: 6
Signal (RSSI): -48
Security: 3
Hidden: False
------------------------------
Hands-On Exercise 3: Check Connection Status Repeatedly
Goal
Create a script that checks whether the Pico remains connected to Wi-Fi.
Code
import network
import time
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
print("Monitoring Wi-Fi connection...")
for i in range(10):
if wlan.isconnected():
print("Check", i + 1, ": Connected")
print("IP:", wlan.ifconfig()[0])
else:
print("Check", i + 1, ": Not connected")
time.sleep(2)
Expected Output
Monitoring Wi-Fi connection...
Check 1 : Connected
IP: 192.168.1.42
Check 2 : Connected
IP: 192.168.1.42
...
Mini-Challenge: Build a Wi-Fi Status Script
Modify the connection script so that it:
- Prints "Wi-Fi OK" when connected
- Prints "Wi-Fi disconnected" when not connected
- Retries connection every 5 seconds if disconnected
Starter Template
import network
import time
SSID = "YOUR_WIFI_NAME"
PASSWORD = "YOUR_WIFI_PASSWORD"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
while True:
if not wlan.isconnected():
print("Trying to connect...")
wlan.connect(SSID, PASSWORD)
time.sleep(5)
else:
print("Wi-Fi OK | IP:", wlan.ifconfig()[0])
time.sleep(5)
Common Issues and Troubleshooting
1) Wrong SSID or password
- Double-check spelling and case sensitivity
- Ensure the router is broadcasting the correct network name
2) Weak signal
- Move the Pico closer to the router
- Reduce interference from walls or devices
3) Unsupported Wi-Fi settings
- Some networks use settings that may not work well with embedded devices
- Prefer standard WPA/WPA2 networks
4) No serial output in Thonny
- Check the correct interpreter is selected
- Reconnect the board and restart Thonny
Key Takeaways
- The
networkmodule is the main MicroPython interface for Wi-Fi - Use
network.WLAN(network.STA_IF)to join a Wi-Fi network wlan.active(True)enables the radiowlan.connect(ssid, password)starts the connectionwlan.isconnected()confirms connection statuswlan.ifconfig()shows IP and network settings
Review Questions
- What does
STA_IFmean? - Why do we call
wlan.active(True)before connecting? - What information does
ifconfig()return? - How can you tell if the Pico is connected to Wi-Fi?
- What should you check if the connection fails?
Suggested Next Step
In the next session, use this Wi-Fi connection setup to make HTTP requests and connect the Pico 2 W to internet services.