我无法将数据从NodeJ发送到Arduino .. Serial.available()始终是假的..我不知道我的失败是什么..有谁可以帮助我?
这是我的JavaScript / NodeJS代码
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var serialPort = new SerialPort("COM3", {
baudrate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log(data);
});
data="omg";
for(var i=0; i<data.length; i++){
serialPort.write(new Buffer(data[i], 'ascii'), function(err, results) {
if(err!=null)
{
console.log('Error: ' + err);
}
else
console.log('Results ' + results);
});
}
});
这是我的Arduino代码
void setup() {
Serial.begin(9600);
}
String inData = "";
void loop(){
while (Serial.available() > 0) {
char received = Serial.read();
inData.concat(received);
Serial.println(received);
// Process message when new line character is received
if (received == '\n') {
// Message is ready in inDate
}
}
}
NodeJs OutPut
node server.js DEPRECATION:请改用
require('serialport')
require('serialport').SerialPort
开放
结果:未完成
结果:未完成
结果:未完成
答案 0 :(得分:0)
尝试听nodeJS ^^。
替换:
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
通过
var SerialPort = require("serialport");
编辑:
您的data
未在您的范围内初始化。
试试这个:
var SerialPort = require("serialport");
var serialPort = new SerialPort("COM3", {
baudrate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
var _data = '';
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log(data);
_data += data;
});
for(var i=0; i<_data.length; i++){
serialPort.write(new Buffer(_data[i], 'ascii'), function(err, results) {
if(err!=null)
{
console.log('Error: ' + err);
}
else
console.log('Results ' + results);
});
}
});
serialPort.on('error', function(err) { console.log(err); });