Arduino串口和插座

时间:2014-06-26 20:29:50

标签: node.js sockets arduino

我正在尝试使用Node.js和Socket.io以及我的代码将串行数据发送到Arduino。

并且html页面只有一个按钮。它的工作节点和html端。但这不是发送串行数据。

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
 var port = process.env.PORT || 3000;


 server.listen(port, function () {
//  console.log('Server listening at port %d', port);
});

 // Routing

 app.use(express.static(__dirname + '/public'));

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM3", {
baudrate:9600
}, false); // this is the openImmediately flag [default is true]



io.on('connection', function (socket) {

    socket.on('my other event', function (data) {
        console.log(data);

        serialPort.open(function () {
            console.log('open');
            serialPort.on('data', function (data) {
                console.log('data received: ' + data);
            });

        serialPort.write(data, function (err, results) {
            console.log('err ' + err);
            console.log('results ' + results);
        });
    });

  });
  });

 app.get('/', function (req, res) {
 res.sendfile(__dirname + '/index.html');
});

1 个答案:

答案 0 :(得分:1)

向Arduino发送串行消息并不像简单地传入String那么容易。不幸的是,您必须按字符发送字符串,Arduino将接收该字符并将其连接回字符串。在发送完最后一个字符后,您需要发送一个最后一个新行字符(/ n),这是Arduino停止连接和评估消息的信号。

这是您需要在Node.js服务器中执行的操作:

// Socket.IO message from the browser
socket.on('serialEvent', function (data) {

    // The message received as a String
    console.log(data);

    // Sending String character by character
    for(var i=0; i<data.length; i++){
        myPort.write(new Buffer(data[i], 'ascii'), function(err, results) {
            // console.log('Error: ' + err);
            // console.log('Results ' + results);
        });
    }

    // Sending the terminate character
    myPort.write(new Buffer('\n', 'ascii'), function(err, results) {
        // console.log('err ' + err);
        // console.log('results ' + results);
    });
});

这是收到此内容的Arduino代码:

String inData = "";

void loop(){
    while (Serial.available() > 0) {
        char received = Serial.read();
        inData.concat(received);

        // Process message when new line character is received
        if (received == '\n') {
            // Message is ready in inDate
        }
    }
}