我对nodejs全新,我一直在尝试与arduino和节点app进行通信。我的节点代码监听串口并将数据发送到page.Everything正常但是发生了一个奇怪的情况。
var cleanData = ''; // this stores the clean data
var readData = ''; // this stores the buffer
sp.on("open", function () {
console.log('open serial communication');
});
// Listens to incoming data
sp.on('data', function (data) { // call back when data is received
readData += data.toString(); // append data to buffer
// as clean data. Then clear the buffer.
if (readData.indexOf('B') >= 0){
cleanData = readData.substring(readData.indexOf('B')+1,readData.length);
console.log(cleanData);
readData = '';
//io.sockets.emit('pulse', cleanData);
}
});
以'B'开头的数据应该打印但是当我运行代码时,我看到了
226
Q26
226
Q252
207
Q498
喜欢这些。为什么打印'Q'的数据?
答案 0 :(得分:0)
您也可以拆分换行,例如;
sp.on('data', function (data) { // Call back when data is received
readData += data.toString(); // Append data to buffer
while(readData.indexOf('\n') > 0) { // Process all full rows
// Get everything before the line feed
var cleanData = readData.substring(0, readData.indexOf('\n'));
// ...and remove what we just extracted from the read buffer
readData = readData.substring(readData.indexOf('\n') + 1, readData.length);
// If it contains a B, well... you know what to do
if(cleanData.indexOf('B') > 0) {
console.log(cleanData);
//io.sockets.emit('pulse', cleanData);
}
}
});