【问题标题】:Serial communication with arduino using nodejs使用 nodejs 与 arduino 进行串行通信
【发布时间】:2015-10-09 05:32:01
【问题描述】:

我试图通过使用 nodejs 来控制 arduino。我的问题是我试图向arduino写入一个整数,但该值不会注册。 any1可以帮忙吗?

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 代码可以正常工作。

谢谢。

【问题讨论】:

  • 也许问题是每个串口或android上的i/o端口?我在谈论模拟和数字信号,它们是否正确连接?
  • 我确定它连接正确,因为我可以从 arduino 接收串行数据,我就是无法写入它。

标签: javascript node.js arduino serial-port


【解决方案1】:

我不确定您的 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);  
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多