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

Raspberry Pi Pico W代码报TypeError:缺少必需位置参数求助

问题排查与解决方案

错误原因分析

报错TypeError: function missing 1 required positional arguments指向debounce协程,核心原因是协程调用时未传入定义要求的全部参数——比如debounce协程需要引脚、回调函数两个必传参数,但原代码启动协程时只传了部分,或者参数数量/顺序不匹配,导致触发参数缺失错误。

修复后完整代码

import network
import ntplib
import time
import machine
import uasyncio as asyncio

# WiFi配置
SSID = "你的WiFi名称"
PASSWORD = "你的WiFi密码"

# 硬件初始化
led = machine.Pin("LED", machine.Pin.OUT)
btn_reset = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
btn_add = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
count = 0

# WiFi连接逻辑
def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print("连接WiFi中...")
        wlan.connect(SSID, PASSWORD)
        while not wlan.isconnected():
            time.sleep(0.5)
            led.toggle()
    print("WiFi已连接,IP:", wlan.ifconfig()[0])
    led.off()

# NTP时间获取与格式化
def get_ntp_time():
    try:
        ntp_client = ntplib.NTPClient()
        response = ntp_client.request('pool.ntp.org', version=3)
        # 转换为UTC+8本地时间
        local_time = response.tx_time + 8 * 3600
        time_struct = time.localtime(local_time)
        # 格式化为dd/mm/yyyy HH:MM:SS
        return "{:02d}/{:02d}/{:04d} {:02d}:{:02d}:{:02d}".format(
            time_struct[2], time_struct[1], time_struct[0],
            time_struct[3], time_struct[4], time_struct[5]
        )
    except Exception as e:
        print("NTP时间获取失败:", e)
        return "时间获取失败"

# 异步防抖协程(解决按键抖动+并行监测)
async def debounce(pin, callback, debounce_delay=50):
    last_state = pin.value()
    while True:
        current_state = pin.value()
        # 检测按键按下(上拉输入,低电平触发)
        if current_state != last_state:
            await asyncio.sleep_ms(debounce_delay)
            # 二次确认状态,避免抖动误触
            if pin.value() == current_state:
                callback()
        last_state = current_state
        await asyncio.sleep_ms(10)

# 按键回调函数
def reset_count():
    global count
    count = 0
    print(f"Count已重置: {count}")
    print("当前时间:", get_ntp_time())

def add_count():
    global count
    count += 1
    print(f"Count已加1: {count}")
    print("当前时间:", get_ntp_time())

# LED闪烁协程(异步执行,不阻塞按键监测)
async def led_blink():
    global count
    while True:
        if count > 0:
            # 按当前count值闪烁
            for _ in range(count):
                led.on()
                await asyncio.sleep(0.5)
                led.off()
                await asyncio.sleep(0.5)
            await asyncio.sleep(2)
        else:
            led.off()
            await asyncio.sleep(0.5)

# 主协程(统筹所有异步任务)
async def main():
    connect_wifi()
    # 启动两个按键的防抖监测任务
    asyncio.create_task(debounce(btn_reset, reset_count))
    asyncio.create_task(debounce(btn_add, add_count))
    # 启动LED闪烁任务
    await led_blink()

# 启动程序
asyncio.run(main())

关键修复与说明

  1. 协程参数匹配:debounce协程明确要求pin和callback两个必传参数,启动时通过asyncio.create_task完整传入,直接解决参数缺失的TypeError。
  2. 异步并行机制:用uasyncio将按键监测、LED拆分为独立任务,保证按键操作不受LED闪烁的阻塞影响,符合需求中的并行要求。
  3. 防抖逻辑优化:加入延时二次确认,避免硬件按键抖动导致的误触发。
  4. 时间格式化:将NTP获取的UTC时间转换为UTC+8本地时间,并按要求格式输出。

使用注意事项

  • 替换代码中的SSID和PASSWORD为你的实际WiFi信息。
  • 按键需采用“引脚+上拉电阻”接法:按键一端接对应引脚,另一端接地,按下时引脚为低电平触发。
  • 若NTP连接失败,可尝试更换国内NTP服务器,比如cn.pool.ntp.org。

内容的提问来源于stack exchange,提问作者Thomas Mill

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 19:58:15