【发布时间】: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