在编写和读取之间,不应该关闭Python中的串行端口。当Arduino响应时,端口可能仍处于关闭状态,在这种情况下,数据将丢失。while running:
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(6) # with the port open, the response will be buffered
# so wait a bit longer for response here
# Serial read section
msg = ard.read(ard.inWaiting()) # read everything in the input buffer
print ("Message from arduino: ")
print (msg)
PythonSerial.read函数默认只返回一个字节,因此您需要在循环中调用它,或者等待数据传输,然后读取整个缓冲区。
在Arduino方面,您应该考虑当没有数据可用时,loop函数中会发生什么。void loop()
{
// serial read section
while (Serial.available()) // this will be skip