我正在使用 Arduino 和 raspberry pi 构建一个 IoT 应用程序。有一个要求是从 Arduino 读取串行输出。这个读数是由树莓派完成的。对于这个过程,我使用的是节点串口模块。
在读取该串行输出时,我必须使用一个条件。我只需要包含整数值的一行。所以我使用了以下代码行。
图片:在这里你可以看到包含整数的行。因为这是一个循环,你可以看到多行。我需要读一遍该行以进行循环
var sp = new serialport("/dev/ttyACM0", { //for serial communication with arduino
//baudrate: 9600,
baudRate: 9600,
// we are using UNO so baudrate is 9600, you might need to change according to your model
//parser: serialport.parsers.readline("\n")
parser: new Readline("\r\n")
if(data === parseInt(data,10)){
dataTemp = data;
}
});
如您所见,我使用 if 条件来检查该行是否为整数。但是当我使用腻子执行此操作时,控制台回复我以下内容:
/home/pi/indigo-parking.js:24
if(data === parseInt(data,10)){
^^
SyntaxError: Unexpected token if
所以我想知道任何人都可以帮助我完成这个。如果您有任何想法/解决方案,请与我分享。(我在下面包含了完整的代码......你可以参考它以获得更好的主意)
树莓派的完整代码:
//indigo parking data transfer
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "861b8f68ff30439288d755b5e7a74374"; // Indigo parking DEVICE ID
var device_token = "0f8681a1bd624624b6d4841358f323c2"; //Indigo parking DEVICE TOKEN
// import websocket module
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var dataTemp="";
var ws = null;
// import serialport module
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var Readline = serialport.parsers.Readline
//const port = new SerialPort('/dev/tty-usbserial1')
var sp = new serialport("/dev/ttyACM0", { //for serial communication with arduino
//baudrate: 9600,
baudRate: 9600,
// we are using UNO so baudrate is 9600, you might need to change according to your model
//parser: serialport.parsers.readline("\n")
parser: new Readline("\r\n")
if(data === parseInt(data,10)){
dataTemp = data;
}
});
var parking_state=0;// variable to check for parking state_gate
// this is for demo purpose only
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket connection and setup GPIO pin
*/
function start() {
//Create the WebSocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("WebSocket connection is open ....");
// after creating connection you have to register with your Authorization information
register();
});
ws.on('message', function(dataTemp) {
//this loop is called whenever the client sends some message
handleRcvMsg(dataTemp); //data is received to the function handleRcvMsg()
});
ws.on('close', function() {
console.log("WebSocket connection is closed ....");
});
}
/**
* Sends a register message to /websocket endpoint
*/
//Client will only work when device gets registered from here
function register(){
console.log("Registering device on the WebSocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
//data after receiving is sent here for processing
function handleRcvMsg(msg){
var msgObj = JSON.parse(msg);
if (msgObj.type != "action") return; //Early return;
var actions = msgObj.dataTemp.actions;
var actionName = actions[0].name; //assume that there is only one action in actions
console.log("The received action is " + actionName);
//you must know your registered actions in order to perform accordinlgy
// we will not receive any action in our case
if (actionName.toLowerCase() == "parking_state")
{
// your code here
}
else {
//this loop executes if some unregistered action is received
//so you must register every action in cloud
console.log('Do nothing since receiving unrecognized action ' + actionName);
return;
}
}
/**
* Send one message to ARTIK Cloud
*/
//This function is responsible for sending commands to cloud
function sendStateToArtikCloud(parking){
try{
ts = ', "ts": '+getTimeMillis();
var dataTemp = {
"indigolot": parking
//setting the parking value from argument to our cloud variable "parking"
//we will get the value from arduino
};
var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(dataTemp)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload + '\n');
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString() +'\n');
}
}
function exitClosePins() {
console.log('Exit and destroy all pins!');
process.exit();
}
start();
//exectes every time when data is received from arduino (30sec programmed delay from arduino)
sp.on("open", function () {
sp.on('data', function(dataTemp) {
console.log("Serial port received data:" + dataTemp);
//sendStateToArtikCloud(data);//parking data to artik cloud
sendStateToArtikCloud(dataTemp);
});
});
process.on('SIGINT', exitClosePins);
这不是明显的语法错误吗?
var sp = new serialport("/dev/ttyACM0", {
baudRate: 9600,
parser: new Readline("\r\n")
if(data === parseInt(data,10)){//// this line////
dataTemp = data;
}
});
串行端口构造函数接受一个对象作为第二个参数。您正在if
对象内编写一个子句。
不知道串口,但如果解析器接受函数,你可以在它周围包装一个函数。或者也许使用 iife
parser: (function(){
let data = new Readline("\r\n")
if(data === parseInt(data,10)){
dataTemp = data;
return dataTemp;
})();
或类似的东西
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句