You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Raspberry Pi Pico W含温感与网络逻辑的程序无法自启动求助

Raspberry Pi Pico W 自启动失败排查与解决(含网络/传感器代码)

我在给Raspberry Pi Pico W实现程序自启动功能时遇到问题:仅包含LED闪烁逻辑的main.py能正常开机自启,但加入温度传感器(LM35)和网络相关代码后,程序无法开机自动运行。在Thonny中点击运行程序一切正常,代码仍在开发阶段,无需关注整洁度,相关代码如下:

import network
import urequests
import machine
import utime
import gc   # Import the garbage collector
 
# Connect to network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
 
led = machine.Pin("LED", machine.Pin.OUT)
 
# Fill in your network name (SSID) and password here:
ssid = 'SuperHot'
password = '(pass)'
while not wlan.isconnected():
    wlan.connect(ssid, password)
    utime.sleep(2)  # Wait for 2 seconds before retrying
 
url = "http://192.168.4.23:8000/data"
headers = {
    "Content-Type": "text/plain"
}
 
LM35 = machine.ADC(0)  #setup analog reading on ADC
Cal_Offset = 5050      #Calibration offset value
                       #Determined from practical testing
 
def Compute_Temp(Avg_A):
    LM35_A = Avg_A + Cal_Offset           #Add Calibration Adjustment
    LM35_V = LM35_A * .00005              #Convert analog reading to volts
    Tmp_C  = round((LM35_V * 100),1)      #Convert volts to temp celcius
    Tmp_F  = round((Tmp_C * 1.8 + 32),1)  #Convert Tmp_C to Tmp_F
    return Tmp_C, Tmp_F                   #Return Temps
 
 
Samples = 0            #Variable holds all samples
Num_Samples = 1        #Counter for num samples collected
while True:
    led.on()
    utime.sleep(.5)
    led.off()
    utime.sleep(.25)
    if Num_Samples <= 10:            #storing a total of 10 samples
        LM35_A = LM35.read_u16()     #Read the ADC port to get sensor data
        Samples = Samples + LM35_A   #Add current reading to sample batch
        Num_Samples += 1             #Increment counter
    else:
        Avg_A = Samples / 10             #Get the average of samples
        Samples = 0                      #Reset Samples variable to zero
        Num_Samples = 1                  #Reset counter to one
        T_c, T_f = Compute_Temp(Avg_A)   #Fetch the temps from the function
        data = "Celcius=" + str(T_c) + "  Fahrenheit=" + str(T_f)
        response = urequests.put(url, data=data, headers=headers)
 
        gc.collect()   # Invoke the garbage collector here
 
    utime.sleep(.1)  #slow the loop down

排查与解决方法

1. 网络连接无限阻塞导致启动卡死

代码中无限循环等待WiFi连接的逻辑是核心问题:Pico W开机时WiFi模块尚未完全初始化,或环境中WiFi信号不可用,这个循环会一直阻塞,导致后续代码无法执行,系统可能判定程序启动失败。

修改方案:给网络连接添加重试次数限制,避免无限阻塞:

max_retries = 5
retry_count = 0
wlan.active(True)
network_connected = False

while retry_count < max_retries:
    wlan.connect(ssid, password)
    utime.sleep(2)
    if wlan.isconnected():
        network_connected = True
        break
    retry_count += 1

后续发送网络请求时,先判断连接状态:

# 原代码中发送请求的部分修改为:
if network_connected:
    response = urequests.put(url, data=data, headers=headers)
    response.close()  # 必须关闭响应释放内存

2. 电源供电不足

加入WiFi和传感器后,Pico W功耗上升,劣质USB线或低功率电源会导致开机时电压不稳,程序无法正常初始化。

解决:更换优质屏蔽USB线,使用5V/2A及以上规格的电源供电。

3. 文件系统损坏或main.py读取异常

异常断电可能导致Pico W的文件系统损坏,开机无法读取main.py。

解决:在Thonny的Shell中执行以下命令格式化文件系统(先备份重要文件):

import os
os.VfsFat.mkfs(machine.SD())

之后重新上传main.py。

4. 内存不足导致启动崩溃

开机时系统内存紧张,网络请求和传感器采样可能占用过多内存引发崩溃。

优化:

  • 在初始化网络前提前调用垃圾回收:
    gc.collect()
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    
  • 务必在urequests请求后关闭响应,避免内存泄漏:
    response = urequests.put(url, data=data, headers=headers)
    response.close()
    

5. 查看启动日志定位问题

通过串口查看启动日志,能直接看到程序启动时的错误信息:

  • 连接Pico W到电脑,打开Thonny的Shell窗口
  • 或使用串口工具(如PuTTY),设置波特率115200,开机时即可看到系统输出的日志,定位具体报错原因。

内容的提问来源于stack exchange,提问作者Alexis Baker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 18:23:20