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

使用Node Serial Port读取气体分析仪出现乱码的排查与解决

Node Serial Port读取气体分析仪数据出现乱码(????)的排查与解决方法

我用Node Serial Port读取气体分析仪数据时,返回结果里出现了????这类意外字符,具体情况如下:

接收的数据:

T-0 0.05 1.20  5799.35719.52    0    0-23.3@????

预期的数据:

T-0 0.05 1.20  5799.35719.52    0    0-23.301020305

代码示例:

port = new SerialPort({
  path: portName,
  baudRate: baudRate,
  dataBits: 8,
  stopBits: 1,
  parity: parity,
  timeout: 100,
});

// Open the port
port.open(function (err) {
  const parser = port.pipe(new InterByteTimeoutParser({ interval: 5 }));
  // const parser = port.pipe(new ByteLengthParser({length:254}));
  parser.on("data", function (data) {
    console.log("Data received from port: ", data.toString());
    console.log("Data received from port: ", data.toString("hex"));
    console.log("Data received from port: ", data);
  });
});

排查与解决步骤

1. 严格匹配串口参数

气体分析仪的串口参数必须和代码设置完全一致,参数不匹配是乱码的常见原因:

  • 查阅设备手册,确认官方指定的波特率、数据位、停止位、校验位,比如parity可能是none/even/odd,不能凭经验填写;
  • 逐一核对代码中baudRate、dataBits、stopBits、parity四个参数,确保和设备参数无偏差。

2. 调整字符编码解析

data.toString()默认使用UTF-8编码,但工业设备常使用ASCII、Latin1等编码,UTF-8解析非兼容字符会出现????:

  • 尝试用ASCII编码解析:
    console.log("Data received from port: ", data.toString("ascii"));
    
  • 若ASCII无效,改用Latin1(可映射所有字节为字符)查看原始内容:
    console.log("Data received from port: ", data.toString("latin1"));
    

3. 验证数据解析器的合理性

当前使用的InterByteTimeoutParser依赖超时判断数据包边界,若设备数据包间隔不稳定,会导致数据截断/合并:

  • 先禁用解析器,直接监听串口原始数据流,查看完整字节:
    port.on("data", function (data) {
      console.log("Raw hex data: ", data.toString("hex"));
    });
    
  • 若设备数据包长度固定,启用ByteLengthParser并设置正确的长度值(需确认设备手册中的数据包长度,而非默认的254)。

4. 排查硬件连接问题

  • 确认串口线类型(交叉线/直连线)符合设备要求,工业设备可能需要特定线缆;
  • 更换串口转USB适配器(若使用),劣质适配器易导致数据丢包或乱码;
  • 尝试更换电脑串口或设备端口,排除硬件故障。

5. 分析原始十六进制数据

从data.toString("hex")的输出中对比异常部分:

  • 预期的01020305对应十六进制为3031303230333035,若实际收到的字节值不符,说明传输丢包或设备发送异常;
  • 若十六进制值正确但转字符串乱码,可确定是编码解析问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:52:34