Python swallows the first value that comes in through serial communication

Viewed 39

I have an Nodemcu ESP8266 connected to my Raspberry Pi over a serial connection. The Nodemcu is frequently (every 5 min.) sending data to my Pi, but if I don't run the script on my Pi this data is not used in any way. The data is just a number, normally between 0-15. On the Pi I am trying to write a CSV-file with the incoming data (with timestamps) from the Nodemcu but the first value that comes in gets swallowed until the second value comes in. Then the first value gets written in the CSV-file but with the timestamp of the second value.

For example the Nodemcu sends this: (timestamps are not sent by the Nodemcu, I added them for comparison) 08:04:15 1 08:09:16 2 08:14:16 3 08:19:16 4 08:24:17 5 08:29:17 6 08:34:17 7

And the script writes this in the CSV-file: (these timestamps are written in the CSV-file) 08:09:16 1 08:14:16 2 08:19:16 3 08:24:17 4 08:29:17 5 08:34:17 6

I've checked the serial connection (pins on the Pi) and the script I'm running on the Nodemcu and they seem perfectly fine so I assume it is the script on my Pi. Here is the script I am running on my Pi:

import serial
import time
import csv
from datetime import datetime
value_mcu = ''
s = serial.Serial('/dev/ttyAMA0', 74880) 
time.sleep(5)

today = datetime.today().strftime('%Y-%m-%d')
with open('/home/pi/Desktop/CSV/' + today + '.csv','w') as db:
    db.write('Timestamp,Value\n')

while True:
    try:
        while value_mcu.strip() == '':
            value_mcu = s.readline().decode('utf-8').strip()
        today = datetime.today().strftime('%Y-%m-%d')
        now = datetime.today().strftime('%H:%M:%S')

        with open('/home/pi/Desktop/CSV/' + today + '.csv','a') as db:
            db.write(now + ',' + value_mcu + '\n')
        value_mcu = ''
    except KeyboardInterrupt:
        s.close()

I hope somebody got a clue on what's happening here. Thanks for the help in advance.

0 Answers
Related