Interpret serialdata in python
<p>I'm currently struggling with an issue. I have an arduino sending serialdata to my raspberry pi. The raspberry pi reads the data and stores it in a database. What i'm struggling with is to get data in the correct order. If i start the script at the correct time, the values get read properly. If i don't they get mixed up.</p>

<p>I have a headerByte sent from the arduino, this value is 999 and it is the first value to be sent each time. Is there a way in python to make 999 the marker for the beginning of every read? My variables will never exceed 999 so this will not be a problem.</p>

<p>Python code:</p>

<pre><code>import serial
import time

values = []
serialArduino = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1)

voltageRead = serialArduino.readline()
currentRead = serialArduino.readline()


while True:
       voltageRead = serialArduino.readline()
       currentRead = serialArduino.readline()
       print"V=", voltageRead, "A=", currentRead
</code></pre>

<p>Arduino Code:</p>

<pre><code>void loop() {
  float voltageRead = analogRead(A0);
  float ampsRead = analogRead(A1);
  float calculatedVoltage = voltageRead / 103;
  float calculatedCurrent = ampsRead / 1;
  int headerByte = 999;
  Serial.println(headerByte);
  Serial.println(calculatedVoltage);
  Serial.println(calculatedCurrent);
  delay(1000);

}
</code></pre>

<p>Your method isn't particularly efficient; you could send everything as a struct from the Arduino (header + data) and parse it on the RPi side with the <code>struct</code> module though your way does have the advantage of simplicity. But, if 999 is the highest value you expect in your readings, then it makes more sense to use a number <em>greater</em> than 999 like 1000. And 999 isn't really a byte.</p>

<p>That said, if "1000" is your header, you can simply check for the header's presence like this:</p>

<pre><code>HEADER = "1000"
serialArduino = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1)

while True:
    if serialArduino.readline().rstrip() == HEADER: # check for header
        voltageRead = serialArduino.readline()  # read two lines
        currentRead = serialArduino.readline()
        print"V=", voltageRead, "A=", currentRead
</code></pre>

python arduino serial-port raspberry-pi3