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

ESP8266外接多按键与16x2 LCD时触发TypeError错误求助

问题排查与修复

错误原因

报错TypeError: function takes 1 positional arguments but 2 were given的核心原因是:

  • MicroPython中,Timer的回调函数会被自动传入一个Timer实例作为参数,但你的debounce_callback()方法没有定义参数接收这个值;
  • 同时,Pin的中断处理函数interrupt_handler()也会被传入触发中断的Pin对象,当前代码同样未处理这个参数,后续也可能引发同类错误。

修改后的代码

只需调整Button类中的两个回调方法,添加对应的参数即可:

import time
from machine import I2C, Pin, Timer
from i2c_lcd import I2cLcd

DEFAULT_I2C_ADDR = 0x27


class Button:
    def __init__(self, pin, callback):
        self.pin = Pin(pin, Pin.IN, Pin.PULL_UP)
        self.callback = callback
        self.debounce_timer = Timer(-1)
        self.state = False

    def init(self):
        self.pin.irq(trigger=Pin.IRQ_FALLING, handler=self.interrupt_handler)
        print('Button initialized')

    # 新增pin参数,接收触发中断的Pin对象
    def interrupt_handler(self, pin):
        if not self.state:
            self.debounce_timer.init(period=50, mode=Timer.ONE_SHOT, callback=self.debounce_callback)       

    # 新增timer参数,接收触发回调的Timer对象
    def debounce_callback(self, timer):
        if not self.state and self.pin.value() == 0:
            self.callback()
        self.state = False


class Counter:
    def __init__(self, lcd):
        self.lcd = lcd
        self.count = 0

    def increment(self):
        print('Increment start')
        self.count += 1
        print('About to call update display')
        self.update_display()
        

    def decrement(self):
        self.count -= 1
        self.update_display()

    def update_display(self):
        print('Update display')
        self.lcd.move_to(11, 1)
        self.lcd.putstr("     ")
        self.lcd.move_to(11, 1)
        self.lcd.putstr(str(self.count))

i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)

# Initialize counter
counter = Counter(lcd)

# Create a list of buttons
buttons = []

   
# Initialize buttons with their pins and callback functions (if any)
buttons.append(Button(13, counter.increment))  # Increment button
buttons.append(Button(14, counter.decrement))  # Decrement button


# Start all buttons
for button in buttons:
    button.init()
    
lcd.clear()
lcd.move_to(11, 0)
lcd.putstr("COUNT")

补充说明

MicroPython的硬件相关回调(包括Pin中断、Timer定时回调)都会自动传递对应的硬件实例作为第一个参数,这是框架的固定行为。即使你在逻辑中不需要使用这个参数,也必须在函数定义中声明它,否则会触发参数数量不匹配的类型错误。

内容的提问来源于stack exchange,提问作者Waqar Ahmad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 20:23:09