2

I'm fairly new to Arduino so I used a sample code before integrating this into my main code. I'm printing my value in a JSON format over serial. My Arduino outputs this and the python receives this and prints it in the same format

{

"value" : 5

}

but when I use python to try writing to a JSON file on my computer, I'm not getting the same JSON format. Can anyone figure out what's wrong? I need to write to my JSON file in JSON format, but instead, I'm getting this format written in my JSON file " \"value\": 5\r\n" instead of {"value: 5"}. Another problem I'm getting is that sometimes the values I get in my JSON get cut off so sometimes I end up with \r\n" or other parts of the current output. My goal is to get the python code to overwrite the JSON file in real-time, so whenever I open the JSON file, the entire output should be there in the correct JSON format. Any help is appreciated, thank you.

Arduino Code:

#include <ArduinoJson.h>

int analogPin = 3;
int data = 0; char userInput;

StaticJsonDocument<100> testDocument; char buffer[100];

void setup(){

Serial.begin(9600); // setup serial

StaticJsonDocument<100> testDocument;

testDocument["sensorType"] = "Temperature"; testDocument["value"] = 10;

char buffer[100];

serializeJsonPretty(testDocument, buffer);

Serial.println(buffer);

} int(i)=1; void loop(){

testDocument[&quot;value&quot;] = i;

serializeJsonPretty(testDocument, buffer);

Serial.println(buffer);

i=i+1;

}

Python Code:

import serial
import json
import time

ser = serial.Serial('COM4', baudrate = 9600, timeout=1)

while 1:

data = (ser.readline().decode('ascii')) #split('\r\n')

#j = json.loads(data)


file = &quot;C:/Users/Mike/Desktop/test.json&quot;

my_data_file = open(file, 'w')

with open(file1, &quot;w&quot;) as my_data_file :
    json.dump(data, my_data_file)

print(data)

Mike
  • 21
  • 1
  • 2

0 Answers0