![](/img/trans.png)
[英]Losing bytes over Serial communication from Raspberry PI 3 to Arduino UNO
[英]Arduino Uno Raspberry Pi Serial Communication double readings
我使用Arduino Uno从光传感器将模拟数据转换为数字,然后通过USB电缆将此数据发送到树莓派。 但是,当我运行代码时,我从10位传感器读取了诸如1923的值。
这是arduino代码
int a = A0;
int meas = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
meas = analogRead(a);
if(Serial.readString() == "1"){ //Check that Raspberry wants data or not
Serial.println(meas);
}
}
这是Raspberry Pi中的Python代码
import serial
from datetime import datetime
now = datetime.now()
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write("1".encode())
s = ser.readline()
file = open("dataset.txt", "a")
file.write(now.strftime("%Y-%m-%d %H:%M") + " Sensor Value:" + str(s)+ "\n")
file.close()
这是每5分钟运行一次代码后的示例输出
14:08 Sensor Value:6
14:10 Sensor Value:8
14:15 Sensor Value:8
14:20 Sensor Value:10
14:25 Sensor Value:6
14:30 Sensor Value:9
14:35 Sensor Value:6
14:40 Sensor Value:7
14:45 Sensor Value:5
14:50 Sensor Value:5
14:55 Sensor Value:12
15:00 Sensor Value:1
15:05 Sensor Value:1
15:10 Sensor Value:10
15:15 Sensor Value:12
15:20 Sensor Value:14
15:25 Sensor Value:1922
15:30 Sensor Value:2211
15:35 Sensor Value:11
15:39 Sensor Value:6
15:40 Sensor Value:7
15:45 Sensor Value:8
15:50 Sensor Value:10
15:55 Sensor Value:1
16:00 Sensor Value:
16:05 Sensor Value:11
我想摆脱这些1和1922之类的东西,因为它们肯定是毫无意义的数据。
PS:传感器在山顶上,我正在使用远程连接检查数据并操纵代码。
我怎样才能做到这一点? 感谢您的时间。
我认为Mark Setchell是正确的。 您正在从过去的测量中获取数据。
就我个人而言,我将实现一个更可靠的协议,但是由于您的应用程序非常基础,因此您可以尝试使用一种更简单的方法,这就是他的建议。
这可以通过在python程序中在请求和读取之间添加一个小的延迟来轻松解决。 像这样的东西就足够了:
from time import sleep
...
ser.write("1".encode())
sleep(0.05);
s = ser.readline()
同时,我不喜欢您如何处理arduino中的读数。 如果您总是发送单字符命令,则建议采用以下方法:
void loop() {
meas = analogRead(a);
if (Serial.available())
{
if (Serial.read() == '1')
{
Serial.println(meas);
}
}
}
这不会阻止循环的执行(如果您打算扩展功能,可能会派上用场)
您可能会看一下校准,这是一段示例代码,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.