树莓派5运行GPIO代码报错lgpio.error 'gpio busy'求助
解决树莓派GPIO busy错误的方案
问题分析
lgpio.error 'gpio busy'错误说明引脚17或18被其他进程或系统资源锁定,即便重启也未解决,大概率是残留的GPIO资源锁定、后台服务占用导致的。
分步解决方案
1. 定位占用引脚的进程
先找出哪个进程在占用目标引脚:
sudo lsof /dev/gpiomem
或者用gpio工具查看引脚状态:
sudo gpiodetect sudo gpioinfo
找到对应进程后,用kill -9 <进程ID>强制终止。
2. 切换GPIOZero后端
GPIOZero默认使用lgpio后端,可尝试切换到RPi.GPIO后端规避锁定问题,修改代码如下:
from gpiozero.pins.rpigpio import RPiGPIOFactory from gpiozero import Device, LED, Button import time # 切换到RPi.GPIO后端 Device.pin_factory = RPiGPIOFactory() led = LED(17) # BCM编号定义LED引脚 button = Button(18) # BCM编号定义按键引脚 def onButtonPressed(): led.toggle() print("Led turned on >>>" if led.is_lit else "Led turned off <<<") def loop(): button.when_pressed = onButtonPressed while True: time.sleep(1) def destroy(): led.close() button.close() if __name__ == '__main__': print('Program is starting...') try: loop() except KeyboardInterrupt: destroy() print("Ending program")
3. 强制重置GPIO资源
若上述方法无效,执行以下命令重建GPIO设备文件:
sudo rm /dev/gpiomem sudo mknod /dev/gpiomem c 244 0 sudo chmod 666 /dev/gpiomem
执行后重启树莓派:
sudo reboot
4. 关闭后台GPIO服务
部分后台服务(如pigpiod)会占用GPIO资源,停止并禁用这类服务:
sudo systemctl stop pigpiod sudo systemctl disable pigpiod
预防措施
- 确保程序通过Ctrl+C正常退出,触发
destroy()释放资源 - 避免同时运行多个GPIO相关程序
- 优先使用GPIOZero的上下文管理器写法,自动处理资源释放:
from gpiozero import LED, Button import time with LED(17) as led, Button(18) as button: def onButtonPressed(): led.toggle() print("Led turned on >>>" if led.is_lit else "Led turned off <<<") button.when_pressed = onButtonPressed while True: time.sleep(1)
内容的提问来源于stack exchange,提问作者George Guise
相关产品推荐
相关产品推荐

