I have a got a question about my code. It's about communication between Arduino and Raspberry with serial communication and Json format.
Here my python script for Raspberry :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
import simplejson as json
ser = serial.Serial('/dev/ttyACM0',9600)
buffer = ""
while True:
try:
buffer = ser.readline()
print buffer
data = json.loads(buffer)
print data["three"]
three = data["three"]
print three
#rcv = dummy.split()
#print(rcv)
buffer = ""
print " "
except json.JSONDecodeError:
print "Error : try to parse an incomplete message"
Here my Arduino code :
int one=1;
int two=2;
int three = 3;
int four = 4;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("'{\"one\":\"" + String(one) +
"\", \"two\":\"" + String(two) +
"\", \"three\":\"" + String(three) +
"\", \"four\":\"" + String(four) +
"\"}'");
}
In the python code, buffer
returns :
'{"one":"1", "two":"2", "three":"3", "four":"4"}'
In theory three
returns :
3
I test it in python console and it works (without serial link) :
buffer = '{"one":"1", "two":"2", "three":"3", "four":"4"}'
data = json.loads(buffer)
three=data["three"]
print three 3
And it return as expected :
3
But in the real time code, I cannot get the value of three
and json.loads(buffer)
raised an error all the time :
Error : try to parse an incomplete message
'{"one":"1", "two":"2","three":"3", "four":"4"}'
Error : try to parse an incomplete message
'{"one":"1", "two":"2","three":"3", "four":"4"}'
In that case, my code doesn't work. The aim is to obtain all the values send by Arduino in different variables in python.
Thank you.