我正在开发一个 Arduino 项目来控制电机和读取传感器。我决定使用使用Node.js的 Web 视图作为介质通道,使用任一库(SerialPort 和 SerialPort2)从串行端口读取/写入浏览器。
当我使用电线将 Arduino 直接连接到 USB 设备时,两者都工作正常,但是当我通过无线适配器将 Arduino 连接到 USB 设备时,Node.js 似乎无法读取任何内容**(APC220)即使我可以使用 Arduino 串行监视器读取接收到的所有内容。
我检查了这背后的所有可能原因;我检查了用于与无线串行和 APC220 以及桥接器(USB 到串行转换器)进行 Arduino 通信的波特率。它们都具有相同的设置:9600 波特率,无奇偶校验/流控制,数据位:8,停止位:1。
行为如下。它可以毫无问题地连接到COM 端口,然后我尝试打印错误,但似乎两个 SerialPort 库都没有识别出错误。然后没有读取事件(数据),这意味着它(Node.js)没有与串行端口交互,即使它是打开的。
注意:我知道我可以使用另一个 Arduino 作为 USB 端口和无线适配器之间的媒介,但我想了解这个问题并在没有这样的工作的情况下干净地解决它。
问题可能是什么?
服务器 [node.js]:
var SerialPort = require('serialport2').SerialPort;
var portName = 'COM15';
var io = require('socket.io').listen(8000); // Server listens for socket.io communication at port 8000
io.set('log level', 1); // Disables debugging. This is optional. You may remove it if desired.
var sp = new SerialPort(); // Instantiate the serial port.
sp.open(portName, { // portName is instatiated to be COM3, replace as necessary
baudRate: 9600, // This is synchronised to what was set for the Arduino code
dataBits: 8, // This is the default for Arduino serial communication
parity: 'none', // This is the default for Arduino serial communication
stopBits: 1, // This is the default for Arduino serial communication
flowControl: false // This is the default for Arduino serial communication
});
io.sockets.on('connection', function (socket) {
// If socket.io receives message from the client browser then
// this call back will be executed.
socket.on('message', function (msg) {
console.log(msg);
});
// If a web browser disconnects from Socket.IO then this callback is called.
socket.on('disconnect', function () {
console.log('disconnected');
});
});
var cleanData = ''; // This stores the clean data
var readData = ''; // This stores the buffer
sp.on('data', function (data) { // Call back when data is received
readData = data.toString(); // Append data to buffer.
// If the letters '[' and ']' are found on the buffer then isolate what's in the middle
// as clean data. Then clear the buffer.
console.log(readData); // **Here you should be able to print the data if you receive any**
if (readData.indexOf(']') >= 0 && readData.indexOf('[') >= 0) {
cleanData = readData.substring(readData.indexOf('[') + 1, readData.indexOf(']'));
readData = '';
console.log("-- "+cleanData);
io.sockets.emit('message', cleanData);
}else if(readData.indexOf('[') >= 0){
cleanData = readData.substring(readData.indexOf('[') + 1, readData.length);
readData = '';
}else if(readData.indexOf(']') >= 0){
cleanData += readData.substring(0, readData.indexOf(']'));
readData = '';
console.log("-- "+cleanData);
io.sockets.emit('message', cleanData);
}else{
cleanData += readData;
readData = '';
}
//console.log(readData);
//io.sockets.emit('message', readData);
});