Reputation: 1588
I m trying to Send serial data to Arduino using Node.js and Socket.io and my code.
and the html page have only one button. its work node and html side .but this is not send serial data.
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');
});
Upvotes: 1
Views: 922
Reputation: 523
Sending serial messages to the Arduino is not as easy as simply passing in a String. Unfortunately you have to send the String character by character which the Arduino will receive and concatenate back to a String. After you sent the last character you need to send one final new line character (/n) which is a signal for the Arduino to stop concatenating and evaluate the message.
This is what you need to do in your Node.js server:
// 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);
});
});
And this is the Arduino code that receives this:
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
}
}
}
Upvotes: 1