我的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]开头
谢谢
在这里,您正在阅读第一行,但立即放弃它
您需要将其存储在变量中,然后适当地使用它:
相关问题 更多 >
编程相关推荐