【问题标题】:Python Serial Writes to Arduino is different from Arduino's Serial Monitor's Serial WritesPython 对 Arduino 的串行写入不同于 Arduino 的串行监视器的串行写入
【发布时间】:2016-09-12 18:35:10
【问题描述】:

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

问题:当使用Arduino Serial Monitor将test写入串口时,Arduino如预期回复ok并且LED#13亮起。

但是,当 Python 脚本将 test 写入同一个串行端口时,什么也没有发生。 Arduino 不回复串口,LED #13 不亮。

有什么想法可以修复 Python 脚本以使 Arduino 的 ok 响应和 LED 13 亮起吗?

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

【问题讨论】:

    标签: python arduino serial-port pyserial


    【解决方案1】:
    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(清除发送)

    【讨论】:

    • 有效!!花了一个多小时尝试编码字符串和东西哈哈
    • 我在 python + serial + ardiuno 方面有很多经验;P
    • 太棒了!一个相关问题:在 Python 的无限循环中,Arduino 在发送test 后需要大约一秒钟的时间回复ok。有没有办法加快速度?
    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    相关资源
    最近更新 更多