树莓派4红外遥控器按键检测及LCD显示切换方案咨询
红外遥控器检测与LCD显示实现方案
可用的红外遥控处理工具/库
- LIRC(Linux Infrared Remote Control):Linux平台通用的红外控制工具,支持绝大多数红外遥控器,能把按键事件转为系统输入,也能通过Python调用。
- 安装:
sudo apt-get install lirc - 配置后用
irw命令可实时查看按键码,Python中可通过python-lirc包简化处理。
- 安装:
- python-lirc:LIRC的Python封装,方便在脚本里监听红外按键事件。
- 安装:
pip install python-lirc
- 安装:
- pigpio:树莓派专用GPIO库,支持直接解码红外信号,适合直连红外接收头的场景。
- 安装:
sudo apt-get install pigpio,启动服务sudo pigpiod,再装Python包pip install pigpio
- 安装:
- 手动解码:如果不想依赖库,也能用
RPi.GPIO监听红外接收头电平变化,自己实现NEC等常见红外协议的解码,但比较繁琐。
示例实现(Python + LIRC + 1602 LCD)
假设你用树莓派和1602 LCD,LCD控制用RPLCD库,红外用python-lirc:
先配置LIRC
- 修改
/etc/lirc/lirc_options.conf:设置driver = default,device = /dev/lirc0 - 用
irrecord命令录制你的遥控器按键,生成配置文件后放到/etc/lirc/lircd.conf.d/目录下
编写Python脚本
import time import threading from RPLCD import CharLCD import lirc # 初始化LCD(引脚根据实际接线调整) lcd = CharLCD(cols=16, rows=2, pin_rs=25, pin_e=24, pins_data=[23, 17, 21, 22]) # 初始化LIRC sockid = lirc.init('my_remote', blocking=False) triggered = False # 标记是否触发红外按键 def display_cycle(): global triggered while not triggered: # 显示第一帧 lcd.clear() lcd.write_string("Hello StackOverflow!") time.sleep(5) if triggered: break # 切换到第二帧 lcd.clear() lcd.write_string("HI!") time.sleep(5) def ir_watcher(): global triggered while not triggered: codes = lirc.nextcode() if codes: # 检测到任意按键 triggered = True # 执行触发后的显示逻辑 lcd.clear() lcd.write_string("Hello StackOverflow!") time.sleep(2) lcd.clear() lcd.write_string("See you soon!") time.sleep(3) exit() # 启动线程 display_thread = threading.Thread(target=display_cycle) ir_thread = threading.Thread(target=ir_watcher) display_thread.start() ir_thread.start() display_thread.join() ir_thread.join()
注意事项
- 硬件接线要对应:红外接收头的VCC接5V/3.3V,GND接GND,信号脚接指定GPIO。
- 如果用pigpio替代LIRC,可参考其红外解码示例直接监听GPIO脉冲,不需要LIRC的系统配置。
- 测试时先用
irw命令确认LIRC能正确接收按键,再调试Python脚本。
内容的提问来源于stack exchange,提问作者AnonimF
相关产品推荐
相关产品推荐

