[英]Arduino Serial and Socket
我試圖使用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');
});
向Arduino發送串行消息並不像簡單地傳遞一個String那樣容易。 不幸的是,您必須按字符發送String字符,Arduino會接收該字符並將其連接回String。 發送完最后一個字符后,您需要發送一個最后的換行符(/ 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
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.