Python串行写入Arduino不同于Arduino的Serial Monitor的串行写入

时间:2016-09-12 18:35:10

标签: python arduino serial-port pyserial

我有一个Python脚本,它将字符串test写入Arduino串口。如果arduino收到test字符串,它应该使用字符串ok回复,并且LED 13应该喜欢...

问题:当使用Arduino串行监视器将test写入串口时,Arduino会按预期回复ok,并且LED#13亮起。

但是,当Python脚本将test写入同一个串行端口时,没有任何反应。 Arduino不回复串口,LED#13不亮。

如何修复Python脚本以使Arduino和LED 13的ok响应亮起来?

Arduino Sketch

int ledPin = 13;


void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}


void loop() {

    while(Serial.available() == 0) { }

    if(Serial.readString() == "test\r\n") {
      Serial.print("ok\r\n");
      digitalWrite(ledPin, HIGH);
    } 

    readString = ""; // Clear recieved buffer
    delay(100);
}

Python脚本

port = 'COM5'
ser = serial.Serial(
    port=port,
    baudrate=9600,
    timeout=5
)

serial.write("test\r\n")

response = serial.readline()
print response

1 个答案:

答案 0 :(得分:2)

<script type="text/javascript">
    function CalculateImageSize(id){
        var image = document.getElementById(id);
        var height = image.offsetHeight;
        var width = image.offsetWidth;
        ...
        // use height, width to resize image.
    }
</script>

如果您不想等待固定的秒数,您可能需要等待port = 'COM5' ser = serial.Serial( port=port, baudrate=9600, timeout=5 ) # you need to sleep after opening the port for a few seconds time.sleep(5) # arduino takes a few seconds to be ready ... #also you should write to your instance ser.write("test\r\n") # and give arduino time to respond time.sleep(0.5) response = self.serial.readline() print response (清除发送)