繁体   English   中英

Python对Arduino的串行写入与Arduino的串行监视器的串行写入不同

[英]Python Serial Writes to Arduino is different from Arduino's Serial Monitor's Serial Writes

我有一个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素描

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
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 (清除发送)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM