PySerial和Arduino通信不正确



我希望Arduino只有在收到来自python脚本的正确命令时才向python脚本发送信息。似乎有什么地方沟通不畅。

Arduino代码:

char inChar;
bool serial_ready;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
while (!Serial) {
;
}
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available()) {
// read the incoming byte:
inChar = Serial.read();
if (inChar == 'r') {
Serial.print('L');
} else {
Serial.print(inChar);
}
serial_ready = false;
}
}

Python脚本:

import serial
if __name__ == '__main__':
ser = serial.Serial('COM4',115200,timeout=0)
# send signal to arduino
ser.reset_input_buffer()
ser.reset_output_buffer()
try:
ser.write(b'r')
while (ser.inWaiting() <= 0):
print('waiting')
byte_wait = ser.inWaiting()
ard_in = ser.read(byte_wait)
print(ard_in)
except KeyboardInterrupt:
print('KeyboardInterrupt')
ser.close()

有时我在打印出几个waiting后得到b'xf0'(这不是我想要的(,有时它卡在循环中,只打印waiting,直到我停止它。为什么它返回b'xf0'而不是Lr?为什么它有时什么都不回?

提前感谢!

这里是一个带有板载LED和刷新缓冲区的测试(只有当您没有从phyton端锤击数据时才有效(;

// Open a serial connection and flash LED when input is received
int ledRed = 13;      // Onboard LED connected to digital pin 13
char inChar;
bool serial_ready;
void setup() {
pinMode(ledRed, OUTPUT);
Serial.begin(115200);
while (!Serial) {
;
}
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available()) {
// read the incoming byte:
digitalWrite(ledRed, HIGH);
inChar = Serial.read();
if (inChar == 'r') {
Serial.print('L');
} else {
Serial.print(inChar);
}
digitalWrite(ledRed, LOW);
Serial.flush();
}
}

最新更新