繁体   English   中英

使用Node.js与Arduino进行串行通信

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM