Python 没有收到来自Arduino Mega 2560 的第一行串行数据,但收到所有后续数据,为什么会这样?

Python not receiving the first line of serial data from an Arduino Mega 2560, but receiving all subsequent data, why is this happening?

我的 python 代码似乎没有从我的 Arduino 接收第一行串行数据。通过 Arduino 的串行监视器发送相同的命令,我可以将所有相同的数据点以正确的顺序打印在屏幕上。但是当我切换到 python 时,我可以获得除第一行之外的所有数据。作为临时解决方法,我现在将原始第一行数据作为最后一行数据从 arduino 发送到 python。然后,我的 python 代码能够读取丢失的数据,只要它不是前导行即可。真奇怪。这是处理串行交换的 python 代码片段:

def get_data(messageHeader, val):
"""sends and receives arduino data

Arguments:
    messageHeader {str} -- determines which command to upload
    val {str} -- value of input data to upload
"""
header = str(messageHeader)
value = str(val)

if header == "a":
    command = "<" + header + ", " + value + ">"
    print(command)
    ser.write(command.encode())
    if ser.readline():
        time.sleep(0.5)
        for x in range(0, numPoints):
            data = ser.readline().decode('ascii')
            dataList[x] = data.strip('\r\n')
            print("AU: " + str(x) + ": " + dataList[x])
        print(dataList)
else:
    print("Invalid Command")

当我想从 arduino 检索串行数据时,我通过我的 python 终端发送命令 "a",因为它匹配 arudino 代码中内置的临时命令。

这是一些arduino代码:

void loop() 
{
  recvWithStartEndMarkers();
  checkForSerialMessage();
}

void checkForSerialMessage()
{
  if (newData == true) 
  {
    strcpy(tempBytes, receivedBytes);
    // this temporary copy is necessary to protect the original data
    //   because strtok() replaces the commas with [=12=]
    parseData();
    showParsedData();
    newData = false;
    if (messageFromPC[0] == 'a')
    {
        ledState = !ledState;
        bitWrite(PORTB, 7, ledState);

        for(int i = 0; i < 6; i++)
        {
          Serial.println(threshold_longVals[i]);
        }

        for(int i = 0; i < 9; i++)
        {
          Serial.println(threshold_intVals[i]);  
        }

        Serial.println(threshold_floatVal);
        Serial.println(threshold_longVals[0]);
    }
   }
}

当通过 Arduino 的串行监视器发送 "a" 时,我以正确的顺序收到所有 threshold_long/int/floatVals。您会注意到,在 arduino 代码的底部,我添加了一行以再次打印 threshold_longVals[0],因为出于某些我不知道的原因,数据从 python 一侧打印在屏幕上以 threshold_longVals[1] 开头。我很难理解为什么它不是以 threshold_longVals[0]?

开头

谢谢。

if ser.readline():

此处您正在阅读第一行,但立即将其丢弃。

您需要将其存储在一个变量中,然后适当地使用它:

first_line = ser.readline()
if first_line:
    # do something with first_line