WiFi on Raspberry Pi Pico W

WiFi on Raspberry Pi Pico W

Connect to a network, make HTTP requests, and host a simple web server.

WiFi on the Pico W

The Pico W's WiFi is controlled via the network module in MicroPython. The CYW43439 chip provides 2.4 GHz 802.11n with WPA2.

Connecting to WiFi (Station Mode)

import network
import time

wlan = network.WLAN(network.STA_IF)   # Station interface
wlan.active(True)
wlan.connect("YourSSID", "YourPassword")

# Wait until connected
max_wait = 10
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    print("Waiting for connection...")
    time.sleep(1)

if wlan.status() != 3:
    raise RuntimeError("Network connection failed, status:", wlan.status())

print("Connected! IP:", wlan.ifconfig()[0])

WiFi Status Codes

Status Meaning
0 Idle
1 Connecting
2 Wrong password
3 Connected
-1 Connection failed
-2 No AP found
-3 Handshake failed

Network Interface Info

# Returns (ip, subnet, gateway, dns)
ip, subnet, gateway, dns = wlan.ifconfig()
print("IP:", ip)
print("Gateway:", gateway)

Making an HTTP GET Request

import urequests

response = urequests.get("http://worldtimeapi.org/api/ip")
print(response.status_code)
print(response.text)
response.close()   # Always close to free memory

For HTTPS use https:// ߀” the Pico W supports SSL natively.

Posting JSON Data

import urequests, ujson

data = {"temperature": 22.5, "humidity": 60}
headers = {"Content-Type": "application/json"}

response = urequests.post(
    "https://httpbin.org/post",
    data=ujson.dumps(data),
    headers=headers
)
print(response.json())
response.close()

Simple Web Server

import network, socket, time

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID", "Password")
while wlan.status() != 3:
    time.sleep(0.5)

print("IP:", wlan.ifconfig()[0])

addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)

while True:
    conn, addr = s.accept()
    request = conn.recv(1024)
    response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<h1>Pico W Server</h1>"
    conn.send(response)
    conn.close()

Access Point Mode

Create a WiFi hotspot from the Pico W:

ap = network.WLAN(network.AP_IF)
ap.config(essid="PicoW-AP", password="password123", security=4)  # 4 = WPA2
ap.active(True)
print("AP IP:", ap.ifconfig()[0])  # Usually 192.168.4.1

Storing WiFi Credentials

Instead of hardcoding credentials, store them in a secrets.py file on the Pico W:

# secrets.py
SSID = "YourNetworkName"
PASSWORD = "YourPassword"
# main.py
from secrets import SSID, PASSWORD
wlan.connect(SSID, PASSWORD)

This keeps credentials out of code shared on GitHub.