保存到文本文件的数据不一致

Data saved to text file is inconsistent

我的控制器通过串口从无线电模块接收数据,它每 1 秒记录一次温度和湿度到小数点后两位,使用 'a' 作为时间戳的信号。例如:

a21.12 65.43
a21.13 65.40

这是我使用的代码:

import serial
import datetime

connected = False

locations=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3']

for device in locations:
    try:
        print "Trying...",device
        ser = serial.Serial(device, 9600)
        break
    except:
        print "Failed to connect on",device

while not connected:
    serin = ser.read()
    connected = True


with open('tempdata.txt', 'w') as text_file:
    while 1:
        if ser.read() is 'a':
            text_file.write(datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'))
            text_file.write(" ")
        x = ser.read()
        text_file.write(x)
        text_file.flush()

ser.close()

当我之后检查我的文本文件时,结果似乎每次都不一样。如果我让它 运行 只持续 2 或 3 秒,我有时会得到正确的结果,有时我只会得到湿度,有时我会得到时间戳,其中的数字是一半温度,一半湿度(比如 2.16.3 ).如果我让它 运行 超过几秒钟,文件就会完全空白。

我的代码的基础来自之前在这里提出的一个问题,在我添加时间戳部分之前它工作正常。我尝试将无线电传输速率从 9600 更改为 4800,但这只会将数字变成垃圾字符。

我运行在 Raspberry Pi 2 型号 B 上使用它,所以我可能会在短时间内对它要求过高。

您正在调用 read() 两次并且仅写入第二次调用的输出。我不认为那是你的意图。

您可以更改此部分:

with open('tempdata.txt', 'a') as text_file:
    while 1:
        content = ser.read()
        if content is 'a':
            text_file.write(datetime.datetime.now().strftime('%d/%m/%Y %H:%M:%S'))
            text_file.write(" ")
        text_file.write(content)
        text_file.flush()