0
我有一個關於我的代碼的問題。這是關於Arduino和Raspberry與系列通信和Json格式之間的溝通。通過Arduino發送一個覆蓋的python代碼獲取json消息
這裏我的覆盆子 python腳本:
#!/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"
這裏我的Arduino代碼:
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) +
"\"}'");
}
在Python代碼,返回buffer
:
'{ 「一個」: 「1」, 「2」: 「2」, 「3」: 「3」, 「4」: 「4」}'
在理論上three
回報:
我測試它在python控制檯,它的工作原理(無串行鏈路):
buffer = '{"one":"1", "two":"2", "three":"3", "four":"4"}'
data = json.loads(buffer)
three=data["three"]
print three 3
,並返回預期:
但在實時代碼,我不能得到的three
價值和json.loads(buffer)
引發錯誤的所有時間:
錯誤:嘗試解析不完整的消息
'{「one」:「1」,「two」:「2」,「three」:「3」,「 4 「:」 4" } '
錯誤:嘗試解析一個不完整的消息
'{ 「一個」: 「1」, 「2」: 「2」, 「3」: 「3」, 「4」:「4」}'
在這種情況下,我的代碼不起作用。目的是獲取Arduino在python中以不同變量發送的所有值。
謝謝。
嘗試在發生錯誤時打印的實際誤差和'buffer'打印前;打印緩衝區'我懷疑你必須引入一些「掛起」(即'sleep')來確保Arduino代碼在Python代碼嘗試讀取之前寫入所有內容。 – DeepSpace
返回>期望值:第1行第1列(char 0) >錯誤:嘗試解析不完整的消息 >'{「one」:「1」,「two」:「2」,「three」:「 3「,」4「:」4「}'緩衝區通常是正確的,並且緩衝區的打印工作。 – Arnould
當你啓動Python程序時,我正在運行Arduino。因此python程序會在某個隨機時間點打開串口,也許在一個句子的中間被髮送到樹莓。這樣解析不完整的JSON字符串時可能會發生錯誤。 –