PySerial和Arduino无法正确通信

问题描述 投票:0回答:1

我希望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()

有时打印一些b'\xf0'后我会得到waiting(这不是我要的内容),有时它卡在循环中,只是打印waiting直到停止为止。为什么返回b'\xf0'而不是Lr?为什么有时不返回任何内容?

提前感谢!

python arduino pyserial
1个回答
0
投票

使用板载LED进行测试并冲洗缓冲液(仅当您未从浮游植物一侧锤击数据时才有效;

// 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();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.