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

Python中Honeywell ASCII条码扫描器无需回车直接写入PLC的问题

解决Honeywell条码扫描器触发后自动写入PLC(无需手动回车)

你的问题核心在于input()函数需要等待回车确认才能读取数据,而条码扫描器默认可能未配置自动发送回车后缀,或者代码没有实时读取输入的逻辑。以下是两种可行的解决方法:

方案一:修改扫描器输出设置(最简单高效)

Honeywell绝大多数ASCII扫描器支持配置扫描后自动追加回车(CR)字符。开启这个设置后,扫描器完成条码识别会自动发送扫描数据+回车,input()函数会直接获取到完整数据,无需手动按回车。

操作步骤:

  • 找到对应型号的Honeywell扫描器用户手册,定位到「追加回车后缀」(Append CR)的设置条码。
  • 用扫描器直接扫描该设置条码,完成配置。

方案二:Python代码实时读取输入(无需修改扫描器)

如果无法修改扫描器设置,可通过第三方库直接读取键盘输入,无需等待回车确认。以下是两种实现方式:

方式1:使用pynput库

首先安装依赖:

pip install pynput

修改后的代码:

from pynput import keyboard
from pylogix import PLC

ipAddress = '192.168.0.50'
tagName = 'RTA_Read'
scan_data = []

def on_press(key):
    global scan_data
    try:
        # 收集扫描的字符
        scan_data.append(key.char)
    except AttributeError:
        # 检测到回车则停止收集(扫描完成)
        if key == keyboard.Key.enter:
            return False

while True:
    scan_data = []
    print("Ready to scan...")
    # 启动键盘监听
    with keyboard.Listener(on_press=on_press) as listener:
        listener.join()
    # 拼接完整扫描数据
    scan = ''.join(scan_data)
    if scan:
        with PLC(ipAddress) as comm:
            ret = comm.Write(tagName, scan)
            print(f"Tag requested is: {ret.TagName}")
            print(f"Write Status is: {ret.Status}")
            print(f"The tag value written is: {ret.Value}")

方式2:使用getch库(轻量)

安装依赖:

pip install getch

修改后的代码:

from getch import getch
from pylogix import PLC

ipAddress = '192.168.0.50'
tagName = 'RTA_Read'

while True:
    print("Ready to scan...")
    scan_data = []
    while True:
        char = getch()
        # 检测回车字符(ASCII码13),结束收集
        if ord(char) == 13:
            break
        scan_data.append(char)
    scan = ''.join(scan_data)
    with PLC(ipAddress) as comm:
        ret = comm.Write(tagName, scan)
        print(f"Tag requested is: {ret.TagName}")
        print(f"Write Status is: {ret.Status}")
        print(f"The tag value written is: {ret.Value}")

额外注意

  • 如果扫描器是通过串口连接(而非键盘模拟),需改用pyserial库读取串口数据,逻辑类似但数据源替换为串口。
  • 确保PLC标签RTA_Read为字符串类型,且长度足够容纳条码数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:15:15