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

BeagleBone Black外接USB扫码枪读取乱码,如何解析条码内容?

解决BeagleBone Black上USB扫码枪的条码解析问题

为什么直接cat /dev/input/event1会得到乱码

/dev/input/event*设备输出的不是明文字符串,而是Linux输入事件结构体(包含按键按下/释放事件、键码等二进制数据),直接cat显示乱码是正常现象,你的处理方式不对,得用专门工具或代码解析这些事件。

快速获取条码的方法

方法1:用evtest工具解析事件

  1. 安装evtest:
    sudo apt update && sudo apt install evtest
    
  2. 运行工具并指定设备:
    sudo evtest /dev/input/event1
    
  3. 扫描条码,会看到类似输出(以数字7为例):

    Event: time 1620000000.123456, type 1 (EV_KEY), code 16 (KEY_7), value 1 (KEY_DOWN)
    Event: time 1620000000.123457, type 1 (EV_KEY), code 16 (KEY_7), value 0 (KEY_UP)
    这些KEY_*就是对应按键,扫码枪本质是模拟键盘输入,把这些键码映射成字符就能得到条码。

方法2:用input-events工具(更简洁)

  1. 安装input-tools:
    sudo apt install input-tools
    
  2. 运行命令:
    sudo input-events 1
    
    扫描后会直接显示对应的按键字符,比evtest更直观。

方法3:编写Python脚本自动转换为字符串

如果需要自动输出条码字符串,可使用evdev库:

  1. 安装evdev:
    sudo pip install evdev
    
  2. 编写解析脚本(比如barcode_reader.py):
    from evdev import InputDevice, categorize, ecodes
    
    device = InputDevice('/dev/input/event1')
    barcode = ''
    key_map = {
        ecodes.KEY_0: '0', ecodes.KEY_1: '1', ecodes.KEY_2: '2',
        ecodes.KEY_3: '3', ecodes.KEY_4: '4', ecodes.KEY_5: '5',
        ecodes.KEY_6: '6', ecodes.KEY_7: '7', ecodes.KEY_8: '8',
        ecodes.KEY_9: '9', ecodes.KEY_ENTER: '\n'  # 扫码枪通常以回车结束
    }
    
    for event in device.read_loop():
        if event.type == ecodes.EV_KEY and event.value == 1:  # 只处理按键按下事件
            if event.code in key_map:
                char = key_map[event.code]
                if char == '\n':
                    print(f"扫描到条码:{barcode}")
                    barcode = ''
                else:
                    barcode += char
    
  3. 运行脚本:
    sudo python barcode_reader.py
    
    扫描条码后会直接输出解析好的字符串。

额外提示

  • 部分扫码枪可通过设置切换输出模式(比如从HID键盘模式切换到串口模式),如果你的模块支持,查说明书改成串口输出,直接读串口就能拿到明文,更简单。
  • 解决设备权限问题:普通用户可能无法访问/dev/input/event1,可将用户加入input组:
    sudo usermod -aG input $USER
    
    注销再登录后就无需每次加sudo。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:12:17