在写和读之间,您不应该关闭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)Python
Serial.read函数默认情况下仅返回一个字节,因此您需要在循环中调用它或等待数据传输然后读取整个缓冲区。
在Arduino方面,您应该考虑
loop没有可用数据时函数中会发生什么。
void loop(){ // serial read section while (Serial.available()) // this will be skipped if no data present, leading to // the pre sitting in the delay function below { delay(30); //delay to allow buffer to fill if (Serial.available() >0) { char c = Serial.read(); //gets one byte from serial buffer readString += c; //makes the string readString } }相反,请等待
loop函数开始直到数据到达:
void loop(){ while (!Serial.available()) {} // wait for data to arrive // serial read section while (Serial.available()) { // continue as before编辑2
这是从Python与您的Arduino应用进行交互时得到的结果:
>>> import serial>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)>>> s.write('2')1>>> s.readline()'Arduino received: 2rn'因此,这似乎很好。
在测试您的Python脚本时,似乎问题在于打开串口时Arduino会重置(至少我的Uno会这样做),因此需要等待几秒钟才能启动。您还只读取了一行响应,因此我也在下面的代码中修复了该问题:
#!/usr/bin/pythonimport serialimport syslogimport time#The following line is for serial over GPIOport = '/dev/tty.usbmodem1411' # note I'm using Mac OS-Xard = serial.Serial(port,9600,timeout=5)time.sleep(2) # wait for Arduinoi = 0while (i < 4): # Serial write section setTempCar1 = 63 setTempCar2 = 37 ard.flush() setTemp1 = str(setTempCar1) setTemp2 = str(setTempCar2) print ("Python value sent: ") print (setTemp1) ard.write(setTemp1) time.sleep(1) # I shortened this to match the new value in your Arduino pre # Serial read section msg = ard.read(ard.inWaiting()) # read all characters in buffer print ("Message from arduino: ") print (msg) i = i + 1else: print "Exiting"exit()现在是上面的输出:
$ python ardser.pyPython value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Python value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Python value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Python value sent:63Message from arduino:Arduino received: 63Arduino sends: 1Exiting



