[英]Serial communication with arduino using nodejs
我試圖通過使用nodejs控制arduino。 我的問題是,即時通訊試圖向arduino寫一個整數,但是該值不會注冊。 可以幫忙嗎?
node.js串行通信代碼:
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var serialPort = new SerialPort("/dev/cu.usbmodem14131", {
baudrate: 9600,
parser: serialport.parsers.readline("\n")
});
serialPort.on("open", function () {
console.log('open');
serialPort.write("45/r/n") // wrinting offset value to the arduino
serialPort.on('data', function(data) {
console.log(data);
});
});
這里是arduino代碼”
#include <Wire.h>
int offset = 0;
String inString = "";
void setup()
{
Serial.begin(9600);
delay(100);
}
void loop(){
Serial.println(offset); //printing the offset
while (Serial.available() > 0) {
int inChar = Serial.read();
// convert the incoming byte to a char
// and add it to the string:
inString += (char)inChar;
// if you get a newline, print the string,
// then the string's value:
if (inChar == '\n') {
Serial.print("Offset:");
Serial.println(inString.toInt());
offset = inString.toInt();
// clear the string for new input:
inString = "";
}
}
delay(1000);
}
我不太確定我是用錯誤的方式寫入值還是接收到錯誤的值,但是如果我在arduino IDE中手動輸入值,則arduino代碼可以正常工作。
謝謝。
我不確定您的nodejs代碼,但我認為arduino例程存在問題。 我確實注意到您的nodejs例程正在發送/ r / n,而Arduino例程僅在查找/ n。
您擁有的while循環完全可以在不到一個字符的時間內執行,因此可能會使字符之間增加1秒的延遲。
我將其結構保持在while循環中,直到收到換行符為止。 以下示例尚未編譯,但演示了該概念。 它還過濾掉“ / r”字符。
int inChar;
void loop(){
// clear the string for new input:
inString ="";
inChar=0;
while (inchar!= '\n') {
while (Serial.available() > 0) {
inchar = Serial.read();
// do you need to filter the '/r' for it to work correctly?
if (inchar != '/r') {
// convert the incoming byte to a char
// and add it to the string:
inString += (char)inChar;
}
}
}
// when you receive a newline, print the label and
// the string's value:
Serial.print("Offset:");
Serial.println(inString.toInt());
offset = inString.toInt();
delay(1000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.