我正在尝试学习 Node.js 以尝试通过串行端口连接一个工作的 Arduino 示例。代码如下:
var serialport = require("serialport"); // include the serialport library
var SerialPort = serialport.SerialPort; // localize object constructor
var express = require('express'),
app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
// listen for new web clients:
server.listen(8080);
// open the serial port. Change the name to the name of your port, just like in Processing and Arduino:
var sp = new SerialPort("/dev/ttyACM0", {
// look for return and newline at the end of each data packet:
parser: serialport.parsers.readline("\r\n")
});
// respond to web GET requests with the index.html page:
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
// listen for new socket.io connections:
io.sockets.on('connection', function (socket) {
// if there's a socket client, listen for new serial data:
sp.on('data', function (data) {
// set the value property of scores to the serial string:
scores.value = data;
// for debugging, you should see this in Terminal:
console.log(data);
// send a serialdata event to the web client:
socket.emit('serialEvent', scores);
});
});
代码成功执行,输出如下:
info - socket.io started
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized Yh2i5KCqhagEnCIK41q3
debug - setting request GET /socket.io/1/websocket/Yh2i5KCqhagEnCIK41q3
debug - set heartbeat interval for client Yh2i5KCqhagEnCIK41q3
debug - client authorized for
debug - websocket writing 1::
然后我在我的 Arduino 串行监视器中输入一些输入,我的 Node.js 脚本崩溃并出现以下错误:
/home/sisko/NodeJS/nodeSerialServer/serialServer.js:49
scores.value = data;
^
ReferenceError: scores is not defined
at SerialPort.<anonymous> (/home/sisko/NodeJS/nodeSerialServer/serialServer.js:49:3)
at SerialPort.EventEmitter.emit (events.js:93:17)
at parsers.readline (/home/sisko/NodeJS/nodeSerialServer/node_modules/serialport/serialport.js:36:17)
at Array.forEach (native)
at Object.parsers.readline [as parser] (/home/sisko/NodeJS/nodeSerialServer/node_modules/serialport/serialport.js:35:13)
at process.nextTick.options.dataCallback (/home/sisko/NodeJS/nodeSerialServer/node_modules/serialport/serialport.js:89:15)
at EventEmitter.emit (events.js:93:17)
at ReadStream._emitData (fs.js:1365:10)
at afterRead (fs.js:1347:10)
at Object.wrapper [as oncomplete] (fs.js:362:17)