javascript - Arduino JSON over Serial,Json.Parse 返回意外的 JSON 输入

标签 javascript node.js json

我正在构建一个简单的网页,其中的数据通过 JavaScript DOM 操作进行更新。我想从 Arduino 接收数据,这是我在 Arduino 上使用序列化并在 node.js 中使用 SerialPort 完成的。

我能够将通过串行传输的数据作为一个 block 进行控制台记录,返回如下。

{
    "day": "Friday",
    "temperature": 288,
    "humidity": 1099
}

根据我的研究,我认为我需要解析我的 Json 对象,但我得到了一个

( Node :7759)UnhandledPromiseRejectionWarning:SyntaxError:JSON.parse() 中的 JSON 输入意外结束....

我对这个问题非常陌生,非常感谢任何能为我指明正确方向的帮助。

Node JS代码

const SerialPort = require('serialport');
const Readline = require('@serialport/parser-readline');
const port = new SerialPort('/dev/cu.usbmodem14201', { baudRate: 9600 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));// Read the port data

port.on("open", () => {
  console.log('serial port open');
});
parser.on('data', data =>{
  str = data.toString();
  str = JSON.stringify(data);
  str = JSON.parse(data);

  console.log(str.day);
});

Arduino代码

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  myFunction();
  delay(5000);
}

int myFunction(){
   StaticJsonDocument<256> doc;
    int temp = 288;
    int humidity = 1099;
    
    doc["day"] = "Friday";
    doc["temperature"] = temp;
    doc["humidity"] = humidity;

    serializeJsonPretty(doc,Serial);
    Serial.println();
  }

最佳答案

我修好了,谢谢大家给我指明了正确的方向。问题出在我的 Arduino 代码中。我使用的是静态 JSON,它没有给我压缩字符串。

我将其切换为动态,如在 https://arduinojson.org/ 上找到的那样文档。

我的 Arduino 更改为以下内容。

#include <ArduinoJson.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  myFunction();
  delay(5000);
}

int myFunction(){
    DynamicJsonDocument doc(260);
    
    int temp = 21;
    int humidity = 99;
    
    doc["day"] = "Monday";
    doc["temperature"] = temp;
    doc["humidity"] = humidity;

    serializeJson(doc,Serial);
    Serial.println();
  }

关于javascript - Arduino JSON over Serial,Json.Parse 返回意外的 JSON 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65943697/

相关文章:

windows - git 未安装或不在 PATH 中

json - Ansible 按 json 属性分组

Javascript 示例程序无法运行

javascript - Node.js express.json 中间件未按预期解析请求

javascript - Canvas 背景图像未显示在打开的网页上

node.js - 如何在 Nodejs 中使用异步

javascript - JavaScript 中两个相似代码块的不同行为

javascript - 如何在 Mocha 测试期间接受用户输入 (NodeJs)

json - 在 Swift 中转换 JSON 数据

json - 编码不解码时如何忽略 JSON 字段