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

Angular使用ngx-serial读取串口消息后发指令报错求助

问题描述

在Angular项目中使用ngx-serial库时,读取串口返回结果后尝试向串口发送数据,出现报错。
报错截图

相关代码如下:

dataHandler(data: string) {
    console.log("From serial port -> " + data);
    this.myResult = data.replace(/\r/g, '');;
    console.log('myResult: ', this.myResult);
    this.readMyStream(this.myResult);
}

readMyStream(data: string) {
    setTimeout(() => {
      const words = data.split(' ');
      if (words[0] === '**' && words[3] === '****') {
        this.serial.sendData(`*** ** ****\n`);
        console.log('hhihih'); // Alternatively, display message in template
      }
    }, 9000)
}
解决建议
  • 检查串口连接状态:调用sendData前先确认串口是否处于打开状态,避免因连接断开导致报错:
    if (this.serial.isOpen) {
      this.serial.sendData(`*** ** ****\n`);
    } else {
      console.error('串口未打开,无法发送数据');
    }
    
  • 移除不必要的延迟:9秒的setTimeout毫无必要,延迟期间串口可能意外断开,直接处理返回数据即可:
    readMyStream(data: string) {
      const words = data.split(' ');
      if (words.length >= 4 && words[0] === '**' && words[3] === '****') {
        if (this.serial.isOpen) {
          this.serial.sendData(`*** ** ****\n`);
          console.log('hhihih');
        }
      }
    }
    
  • 处理数据格式异常:增加数组长度判断,防止因返回数据格式不符合预期导致数组越界报错:
    if (words.length >= 4 && words[0] === '**' && words[3] === '****') {
      // 执行发送逻辑
    }
    
  • 验证发送数据格式:确认sendData的参数格式是否符合设备要求,部分串口设备需要\r\n作为换行符,而非单独的\n。

内容的提问来源于stack exchange,提问作者Katerina Maria Gerakianaki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 16:12:33