首页 文章

Python串行写入Arduino不同于Arduino 's Serial Monitor' s Serial Writes

提问于
浏览
1

我有一个Python脚本,将字符串 test 写入Arduino串口 . 如果arduino收到 test 字符串,它应该回复一个字符串 ok ,LED 13应该像...

Problem: 当使用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 Script

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

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

response = serial.readline()
print response

1 回答

  • 2
    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
    

    如果您不想等待固定的秒数,您可能需要等待 ser.cts (清除发送)

相关问题