gpt4 book ai didi

python - 从 Arduino 到 RPi 的气压计数据。 readline() 的 Python 错误

转载 作者:行者123 更新时间:2023-11-30 22:14:06 25 4
gpt4 key购买 nike

一直在努力解决这个问题。 Adruino 上的气压计数据如下所示:

1008.941008.951008.94

我很满意。这些现在每 10 秒“读取”一次。

问题出在我的 python 脚本上。我可以读取所有数据并将其写入我的 mySQLdb。但数据并不总是好的。它会像这样:

1008.94108.95108.941008.96

“丢失的零”或其他值始终出现在 Adruino 的串行监视器上。

如何让 python 脚本读取整个 xxxx.xx 行?甚至在低压 xxx.xx 时也只是想。

这是我的python代码:

import MySQLdb
import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)
db = MySQLdb.connect("localhost", "root", "pword","weather")
cursor = db.cursor()

while 1:
# print ("Waiting for data...")
# print("")
x = ser.readline()
clock = (time.strftime("%H:%M:%S"))
print x
# print ("Collecting data...")
x = x
# print ("Inserting to database...")
# print ("")
sql = ("""INSERT INTO WeatherP (pres, Time) VALUES (%s, %s)""", (x, clock,))
cursor.execute(*sql)
db.commit()
#

谢谢。提努斯

最佳答案

我找到了以下 here :

ser.read(ser.inWaiting())

根据pySerial documentation inWaiting() 确实返回缓冲区中接收到的数据的大小。这可以解决您的问题,因为读取函数有一个参数给定的数据大小(在您的情况下为 1 个字节,因为您没有指定)如果接收到的数据较大,则可能会导致此类问题。

关于python - 从 Arduino 到 RPi 的气压计数据。 readline() 的 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39052107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com