TypeError:serialport.parsers.readline不是函数错误

问题描述 投票:0回答:3

嗨,我是 NodeJs 的新手。我从下面的代码中遇到了

TypeError: serialport.parsers.readline is not a function error

    var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
    var device_id = "########################"; //  DEVICE ID
    var device_token = "#####################"; // DEVICE TOKEN

   // require websocket module to connect 
   // execute following two commands to your pi's terminal
   // sudo apt-get update
   // npm install websocket
  var WebSocket = require('ws');
  var isWebSocketReady = false;
  var data="";
  var ws = null;
 // require serialport module to raspberry pi 
 // execute following command to terminal
 // npm install serialport
 var serialport = require("serialport");
 var SerialPort = serialport.SerialPort;
 var sp = new SerialPort("/dev/ttyACM0", { //for serial communication with 
 arduino 
 baudrate: 9600,  
 // we are using UNO so baudrate is 9600, you might need to change according 
 to your model
 parser: serialport.parsers.readline("\n")
 });

但是在我运行这个之后我收到了这样的错误

 /home/pi/parking.js:21
 parser: serialport.parsers.readline("\n")
                           ^

TypeError: serialport.parsers.readline is not a function
 at Object.<anonymous> (/home/pi/rainbow-parking.js:21:32)
 at Module._compile (module.js:409:26)
 at Object.Module._extensions..js (module.js:416:10)
 at Module.load (module.js:343:32)
 at Function.Module._load (module.js:300:12)
 at Function.Module.runMain (module.js:441:10)
 at startup (node.js:140:18)
 at node.js:1043:3

任何人都可以帮我解决这个问题。我怀疑问题出在我的 Nodejs 和 npm 版本不匹配。

node.js npm arduino raspberry-pi serial-port
3个回答
0
投票

您使用了错误的变量名称。而不是

serialport.parsers.readline

使用

串口.parsers.readline


0
投票

我可以看到您使用的非常旧,请查看文档https://node-serialport.github.io/node-serialport/global.html#Parsers您的代码使用它们的方式非常旧。

替换这部分代码

var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", { 
//for serial communication with arduino 
baudrate: 9600,  
// we are using UNO so baudrate is 9600, you might need to change according to your model
parser: serialport.parsers.readline("\n")
});

使用下面提到的代码

const SerialPort = require('serialport');
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort("/dev/ttyACM0",{
    baudRate: 9600,
    parser: new Readline("\n")
});

0
投票

好吧。我找到了解决这个问题的方法。问题是我的 npm 版本和串口版本不匹配。更新这两个版本相同即可轻松避免此问题。谢谢大家的帮助

© www.soinside.com 2019 - 2024. All rights reserved.