rambopanda rambopanda - 1 year ago 55
Python Question

Data saved to text file is inconsistent

My controller is receiving data from a radio module through a serial port, it's recording temperature and humidity to two decimal places every 1 second, using 'a' as a signal to time stamp it. For example:

a21.12 65.43
a21.13 65.40

Here is the code I'm using:

import serial
import datetime

connected = False


for device in locations:
print "Trying...",device
ser = serial.Serial(device, 9600)
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()


When I check my text file afterwards the result seems to be different every time. If I let it run for just 2 or 3 seconds I sometimes get a correct result, sometimes I only get the humidity, sometimes I get the time stamp with a number that is half temperature, half humidity (like 2.16.3). If I let it run for more than a few seconds the file is just completely blank.

The basis for my code is from a question previously asked on here and it worked fine until I added the time stamp part. I tried changing the radio transfer rate from 9600 to 4800 but that just turned the numbers into garbage characters.

I'm running this on a Raspberry Pi 2 model B so I could be demanding too much from it in a short time.

Answer Source

You are calling read() twice and writing only the output of the second call. I don't imagine that is your intent.

You can change this section:

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(" ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download