树莓派 Pico W WiFi 编程例程 — MicroPython + MQTT + Web Server

知识库
知识库文档
/firmware/开发板/树莓派 Pico W (Raspberry Pi Pico W)/树莓派 Pico W WiFi 编程例程 — MicroPython + MQTT + Web Server.md

文档

树莓派 Pico W WiFi 编程例程


示例 1:MicroPython — WiFi 连接 + 闪烁 LED

"""Pico W WiFi 连接 + 板载 LED"""
import network
import time
from machine import Pin

led = Pin("LED", Pin.OUT)  # Pico W 板载 LED 用 "LED" 字符串

ssid = "你的WiFi名"
password = "你的WiFi密码"

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)

print("连接中...")
max_wait = 20
while max_wait > 0:
    if wlan.status() < 0 or wlan.status() >= 3:
        break
    max_wait -= 1
    led.toggle()
    time.sleep(0.5)

if wlan.status() == 3:
    led.on()
    print(f"✅ 已连接!IP: {wlan.ifconfig()[0]}")
else:
    led.off()
    print(f"❌ 连接失败,状态码: {wlan.status()}")

示例 2:MicroPython — HTTP GET 请求(获取天气)

"""Pico W HTTP GET 获取网络时间"""
import network
import urequests
import time

# 先连接 WiFi(参考示例 1)

response = urequests.get("http://worldtimeapi.org/api/timezone/Asia/Shanghai")
if response.status_code == 200:
    data = response.json()
    print(f"北京时间: {data['datetime']}")
else:
    print(f"请求失败: {response.status_code}")
response.close()

示例 3:MicroPython — MQTT 温湿度上报

"""Pico W + DHT22 → MQTT 上报温湿度"""
from machine import Pin
import network, time
from umqtt.simple import MQTTClient
import dht

# ----- WiFi 连接 -----
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("SSID", "PASSWORD")
while not wlan.isconnected():
    time.sleep(0.5)
print(f"IP: {wlan.ifconfig()[0]}")

# ----- MQTT -----
MQTT_BROKER = "broker.emqx.io"
TOPIC = b"pico-w/sensors"
client = MQTTClient("pico-w-001", MQTT_BROKER)
client.connect()
print("MQTT 已连接")

# ----- DHT22 -----
sensor = dht.DHT22(Pin(4))  # GP4

while True:
    try:
        sensor.measure()
        t = sensor.temperature()
        h = sensor.humidity()
        payload = f'{{"temp":{t:.1f},"humidity":{h:.1f}}}'
        client.publish(TOPIC, payload)
        print(f"上报: {payload}")
    except Exception as e:
        print(f"错误: {e}")

    time.sleep(30)

示例 4:MicroPython — 简易 Web Server(GPIO 控制)

"""Pico W Web Server — 网页控制 LED"""
import network, socket
from machine import Pin
import time

led = Pin("LED", Pin.OUT)

# WiFi 连接(略)

# HTML 页面
html = """<!DOCTYPE html>
<html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pico W</title></head>
<body>
<h1>Pico W LED 控制</h1>
<p><a href="/on"><button>LED ON</button></a></p>
<p><a href="/off"><button>LED OFF</button></a></p>
</body></html>"""

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print(f"Web Server: http://{wlan.ifconfig()[0]}")

while True:
    cl, addr = s.accept()
    request = cl.recv(1024).decode()
    print(f"请求: {request.split(chr(10))[0]}")

    if '/on' in request:
        led.on()
    elif '/off' in request:
        led.off()

    cl.send('HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n')
    cl.send(html)
    cl.close()

示例 5:MicroPython — BLE 外设(温度服务)

"""Pico W BLE 温度外设 — 手机可扫描并读取"""
import bluetooth
import struct
from machine import ADC
import time

# 环境温度服务 UUID (标准)
ENV_SENSE_UUID = bluetooth.UUID(0x181A)
TEMP_CHAR_UUID = bluetooth.UUID(0x2A6E)

class BLE_Temp:
    def __init__(self):
        self._ble = bluetooth.BLE()
        self._ble.active(True)
        self._ble.irq(self._irq)
        self._register()
        self._advertise()

    def _register(self):
        temp_char = (TEMP_CHAR_UUID, bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY)
        service = (ENV_SENSE_UUID, (temp_char,))
        ((self._handle,),) = self._ble.gatts_register_services((service,))

    def _advertise(self):
        name = b"PicoW-Temp"
        self._ble.gap_advertise(100000, b'\x02\x01\x06' +
            struct.pack('BB', len(name)+1, 0x09) + name)

    def _irq(self, event, data):
        pass

    def update_temp(self, temp_c):
        """更新温度值(单位: 0.01°C)"""
        self._ble.gatts_write(self._handle,
            struct.pack('<h', int(temp_c * 100)))

ble = BLE_Temp()
adc = ADC(4)  # RP2040 内部温度传感器 (ADC4)

while True:
    # RP2040 内部温度传感器粗略读取
    raw = adc.read_u16()
    voltage = raw * 3.3 / 65535
    temp = 27 - (voltage - 0.706) / 0.001721
    ble.update_temp(temp)
    print(f"温度: {temp:.1f}°C")
    time.sleep(2)

示例 6:MicroPython — WiFi + 看门狗(防死锁)

"""Pico W WiFi 看门狗自动重连"""
from machine import WDT, Pin
import network, time

wdt = WDT(timeout=8000)  # 8 秒看门狗

led = Pin("LED", Pin.OUT)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)

def connect_wifi():
    wlan.connect("SSID", "PASSWORD")
    for _ in range(20):
        if wlan.isconnected():
            return True
        time.sleep(0.5)
    return False

while True:
    if not wlan.isconnected():
        print("WiFi 断开,重连中...")
        if connect_wifi():
            print(f"重连成功 {wlan.ifconfig()[0]}")
        else:
            print("重连失败,30秒后重试")
            time.sleep(30)
    else:
        led.toggle()
        wdt.feed()  # 喂狗
        time.sleep(1)

⚠️ Pico W 编程要点

  1. 板载 LED 访问:MicroPython 用 Pin("LED", Pin.OUT),C SDK 用 CYW43_WL_GPIO_LED_PIN
  2. WiFi 和 BLE 不能同时使用:CYW43439 限制,需分时复用。
  3. MicroPython 内存紧张:264KB SRAM — 固件 ~100KB + WiFi 栈 ~60KB ≈ 仅剩 ~100KB 给用户代码。
  4. urequests 内存消耗大:大 JSON 响应可能导致 OOM,建议用 ujson 流式解析或缩小响应数据。
  5. OTA 更新:可用 ota 模块通过 WiFi 下载并烧写新的 .uf2 或 MicroPython 脚本。

信息

路径
/firmware/开发板/树莓派 Pico W (Raspberry Pi Pico W)/树莓派 Pico W WiFi 编程例程 — MicroPython + MQTT + Web Server.md
更新时间
2026/5/26