【问题标题】:What function could I use to send values to Arduino uno with node js?我可以使用什么函数通过节点 js 向 Arduino uno 发送值?
【发布时间】:2021-12-28 07:21:45
【问题描述】:

我有一个问题,我在 Arduino 中的代码允许我发送值以打开带有 Serial.read () 的 LED,但是当我使用节点 js port.write () 执行此操作时,我尝试了几种方法,但它没有打开领导。

arduino 代码

int pin = 12;
String vali="OFF";
char val;

void setup() {
  pinMode(pin,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  val = Serial.read();
  if(val == '1'){
    digitalWrite(pin,HIGH);
    vali="ON";
  }
  else if(val == '0'){
    digitalWrite(pin,LOW);
    vali="OFF";
  }
    delay(1000);
    Serial.println(" estado:"+ vali );
}

js 代码


const Serialport = require('serialport');
const readline = Serialport.parsers.Readline;
var val = 0;
const port = new Serialport('COM3', {
    baudRate: 9600
});
const parse = port.pipe(new readline({ delimiter: '\r\n' }));

port.on('open', function() {
    console.log('conect ');
});

port.write("1\r\n");
parse.write("1\r\n");

parse.on("data", (data) => {
    console.log(data);
});

【问题讨论】:

  • 您确定将数据发送到正确的端口吗?

标签: javascript node.js arduino serial-port


【解决方案1】:

由于delay(1000); 的阻塞延迟而停止,Serial.read 无法完全读取数据。尝试删除它并添加类似的语句

if(Serail.available > 0)
{
    // Then read data and afterwards turn the led on or off with delay inside here.
    // Also for 1,2  or any other numeric you can use Serial.parseInt() function
    // to read them
}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 2013-06-05
  • 2019-10-20
  • 2014-08-24
  • 2017-02-04
  • 1970-01-01
相关资源
最近更新 更多