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

如何去除Symbol Li2208条码扫描器输出的不可见字符?

解决条码扫描器数据首尾附加STX/ETX字符的问题

ChrW(2)是STX(文本起始符),ChrW(3)是ETX(文本结束符),属于串口通信中常见的帧标识。既然扫描器无法通过设置关闭输出这两个字符,直接在软件层面移除即可,以下是具体修改方案:

方案1:使用Trim方法快速移除首尾指定字符

在拼接完DataStringRxd后,添加Trim操作,精准移除首尾的STX和ETX:

Private Sub SerialPort1_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    
    Dim ErrorReturn As Short = 0 'Used by error handler to store error number
    Dim ErrorText As String 'Used by error handler to store error message
    Dim DataRxd(4096) As Byte 'raw data from serial port
    Dim ReadLength As Short 'length of the data that came in
    Dim WaitTime As Short 'stores how long we wait for all data to get here
    Dim idx As Short 'misc used for loops
    Dim DataStringRxd As String = "" 'stores string of data we get from serial port

ErrorRetry:
    Try
        'do the waiting
        Sleep(300)

        ReadLength = SerialPort1.BytesToRead

        '修正:Byte数组从0索引开始读取,原代码从1开始会漏掉第一个字节;读取长度用实际的ReadLength而非固定值
        SerialPort1.Read(DataRxd, 0, ReadLength)

        DataStringRxd = ""
        For idx = 0 To ReadLength - 1
            DataStringRxd = DataStringRxd & System.Char.ConvertFromUtf32(DataRxd(idx))
        Next idx

        ' 移除首尾的STX(ChrW(2))和ETX(ChrW(3))
        DataStringRxd = DataStringRxd.Trim(ChrW(2), ChrW(3))

        'Debug.Print(DataStringRxd)

        DecodeBarCode(DataStringRxd)

方案2:手动检查并截取有效数据

如果担心Trim会误删中间可能出现的相同字符(概率极低),可以手动判断首尾字符后截取:

' 替换方案1中的Trim代码为以下内容
If DataStringRxd.StartsWith(ChrW(2)) Then
    DataStringRxd = DataStringRxd.Substring(1)
End If
If DataStringRxd.EndsWith(ChrW(3)) Then
    DataStringRxd = DataStringRxd.Substring(0, DataStringRxd.Length - 1)
End If

额外说明:修正串口读取的索引问题

原代码中SerialPort1.Read(DataRxd, 1, 4096)存在两处逻辑问题:

  1. Byte数组的索引从0开始,从1读取会漏掉第一个字节;
  2. 读取长度固定为4096,应该用实际的ReadLength,避免读取多余的空字节。
    修改为SerialPort1.Read(DataRxd, 0, ReadLength)即可解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 02:35:15