我刚刚开始使用 javascript,但我仍在努力了解它是如何工作的。
你能解释一下为什么会这样吗
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
//socket.emit('test', { arduinotest: 'Arduino Connected'});
});
});
这不是,我得到一个“数据未定义错误”
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', received(data));
});
function received(data) {
console.log('data received: ' + data);
//socket.emit('test', { arduinotest: 'Arduino Connected'});
}
由于我不喜欢有很多嵌套函数,我应该如何分离我的函数?
这是我的整个代码
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, SerialPort = require('serialport').SerialPort;
//SERIAL
var portName = '/dev/ttyACM0';
var serialPort = new SerialPort(portName, {
baudRate: 115200,
dataBits: 8,
stopBits: 1,
parity: 'none',
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
//socket.emit('test', { arduinotest: 'Arduino Connected'});
});
});
//SERVER
app.get('/', function (req, res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket){
socket.emit('test', { servertest: 'Server Connected' });
socket.on('value', function (data){
switch(data.key)
{
case "Right":
if(data.state == "True")
{
serialPort.write("d180\n");
console.log("test RT");
}
else if(data.state == "False")
{
serialPort.write("d90\n");
console.log("test RF");
}
break;
case "Left":
if(data.state == "True")
{
serialPort.write("d0\n");
console.log("test LT");
}
else if(data.state == "False")
{
serialPort.write("d90\n");
console.log("test LF");
}
break;
case "Up":
if(data.state == "True")
{
serialPort.write("s0\n");
console.log("test UT");
}
else if(data.state == "False")
{
serialPort.write("s90\n");
console.log("test UF");
}
break;
case "Down":
if(data.state == "True")
{
serialPort.write("s180\n");
console.log("test DT");
}
else if(data.state == "False")
{
serialPort.write("s90\n");
console.log("test DF");
}
break;
}
});
});
server.listen(9081, '192.168.1.158');
我应该如何从我的串行端口代码(注释掉的行)中访问我的套接字对象?
感谢您帮助我理解
乔