Hello Guys我正在使用来自nodejs的socket.io和serialport。现在我想从安装了服务器的覆盆子pi发出arduino上的命令。它们通过串口连接。当发出串行事件时,arduino只是重复发出的消息,并没有做任何事情,也许你们可以帮助我找到错误。
这是我的服务器代码:
var http = require('http');
var fs = require('fs');
Serialport = require('serialport');
port = '/dev/tty/ACM0';
// Loading the file index.html displayed to the client
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
serial = new Serialport(port, {baudrate: 115200});
port.on('open', function() {
port.write('main screen turn on', function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});
// open errors will be emitted as an error event
port.on('error', function(err) {
console.log('Error: ', err.message);
})
//Funktion um daten vom Arduino zu empfangen
serial.on('data', function(chunk){
readData =chunk.toString();
if(readData.indexOf('\n')){
io.sockets.emit('message',"Arduino sends: "+ readData);
} });
// socket.io initialisieren
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
// Willkommensgruß
console.log('Client verbunden');
socket.emit('message', 'Willkommen');
// Falls multiuser irgendwann realisiert sein sollte
// wird eine nachricht ausgegeben das ein neuer user beigetreten ist
socket.broadcast.emit('message', 'neuer Client');
// Wenn das message event ausgelöst wird wird es in der Konsole geloggt
socket.on('message', function (message){
console.log(message);
});
socket.on('move', function(message){
// move
var message2 = new Buffer(message);
console.log(message2.toString());
return serial.write(message2);
});
socket.on('start', function(message){
//motor 1
var message2 = new Buffer("motor 1");
console.log(message2.toString());
serial.write(message 2, function(err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
});
socket.on('stop', function(message){
//stop
var message2 = new Buffer("stop");
console.log(message2.toString());
return serial.write(message2);
});
socket.on('poke', function(message){
//stop
var message2 = new Buffer("ping");
console.log(message2.toString());
return serial.write(message2);
});
socket.on('sensoron', function(message){
//stop
var message2 = new Buffer("sensors 1");
console.log(message2.toString());
return serial.write(message2);
});
socket.on('sensoroff', function(message){
//stop
var message2 = new Buffer("sensors 0");
console.log(message2.toString());
return serial.write(message2);
});
});
server.listen(8080);
我在arduino上初始化了这样的命令:
cmdAdd("ping", cmdPing);
cmdAdd("move", cmdMove);