[英]Using Python readline() to get multiple sensor data over USB from Arduino Uno
我有一个 Raspberry pi 3B+ 通过 USB 电缆连接到 Arduino Uno 并且正在接收多个传感器数据。 我试图找出在 python 中将它们分开的最佳方法。 就像我得到如下数据:
27.3
0
1
它需要知道第一行是温度,第二行是运动检测,第三行是噪声检测等等......
想法 1) 让所有传感器以相同的顺序同时更新。 在循环中对其进行编码,以便第一行 readline() 保存到温度变量,第二行保存到运动变量,依此类推,直到它循环回来......
想法 2)在每个传感器数据前面放置某种标志,并让 python 读取每一行并决定如何处理它。 像温度一样 output 像 t27.3 和 python 中的代码会看到前面的 t 并且知道获取数据的 rest 并将其更新到服务器。 我不确定代码的外观如何
哪种方法更好(最好更快)? 如果是第二个,你能指点我一些解析字符串的代码吗? 自从我不得不这样做以来已经有一段时间了,我已经完全忘记了。 谢谢!
我的建议是使用一种面向未来的数据格式,所以让我们使用一个简单的 JSON。
它的标准化 phyton 内置了支持,并且在 Arfuino 上我们可以手动编写代码,而无需庞大的库
因此,这里有两个片段可以满足您的暂时需求。 随意修改,阅读代码中的注释以了解更多关于使用的功能
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
import json
ser = serial.Serial('/dev/ttyACM0',9600)
buffer = ""
while True:
try:
buffer = ser.readline()
print buffer
data = json.loads(buffer)
print data["temperature"]
temperature = data["temperature"]
print temperature
print data["motion "]
motion = data["motion "]
print motion
print data["noise"]
noise = data["noise"]
print noise
buffer = ""
print " "
except json.JSONDecodeError:
print "Error : try to parse an incomplete message"
在 Arduino 方面,我们使用全局字符数组来构建我们的 JSON
char jsonData[256] = {'\0'}; /* Defined globally choose size large enough */
char numBuffer[16] = {'\0'}; /* Defined globally used for convering numbers to string */
// here we build the JSON
strcpy (jsonData, "{\"temperature\":\"" );
// If its an int use this command
// itoa(temperature, numBuffer, 10); // convert int DATA from sensors etc.
// For float we use this command
// dtostrf(floatvar, StringLengthIncDecimalPoint, numVarsAfterDecimal, charbuf);
dtostrf(temperature, 3, 2, numBuffer); // -> xx.xx
strcat(jsonData, numBuffer);
strcat (jsonData, "\",\"motion\":\"" );
itoa(motion, numBuffer, 10); // convert int DATA from sensors etc.
strcat(jsonData, numBuffer);
strcat (jsonData, "\",\"noise\":\"" );
itoa(noise, numBuffer, 10); // convert int DATA from sensors etc.
strcat(jsonData, numBuffer);
strcat (jsonData, "\"}");
// The JSON data looks like: {"temperature":"21.50","motion":"113","noise":"321"}
Serial.println(jsonData);
不要忘记在两台机器上(在软件中)设置相同的串行速度并从一侧启动以确保 JSON 的完整传输
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.