我的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 \0
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