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

时间:2016-06-30 00:10:31

标签: python pyserial

我的控制器通过串口从无线电模块接收数据,它每隔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上运行它,所以我可能会在短时间内对它提出太多要求。

1 个答案:

答案 0 :(得分:1)

您正在调用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()
相关问题