首页 > 解决方案 > 将串行数据发送到 arduino 可以在串行监视器中使用,但不能在 python 中使用

问题描述

我正在尝试通过 python 脚本将我的 arduino 上的一点点从 0 翻转到 1。如果我在串行监视器中输入 1 并按 Enter,则以下 arduino 代码可以很好地打开 LED:

int x;

void setup() {
  // this code proves that the LED is working
  digitalWrite(7, HIGH);
  delay(300);
  digitalWrite(7, LOW);
  Serial.begin(115200);
}

void loop() {
  Serial.print(x);
  if(Serial.available()){
    x = Serial.parseInt();
    // if x is anything other than 0, turn the LED on
    if (x){
      digitalWrite(7, HIGH);
    }
  }
}

但是当我尝试使用这个 python 脚本时,变量 x 可能保持为 0,因为 LED 没有打开:

import serial
import time
arduino = serial.Serial(port='COM3', baudrate=115200, timeout=5)
time.sleep(5)
print(arduino.read())
arduino.write(b"\x01")
print(arduino.read())
arduino.close()

我将两个打印语句放入以试图弄清楚发生了什么,但我无法理解输出。通常是

b'0'
b'0'

但有时它是

b'0'
b''

或者如果我在插入 arduino 后立即运行脚本:

b'\x10'
b'\x02'

或其他一些随机数。我在这里做错了什么?

标签: pythonarduinopyserial

解决方案


使用bytes("1", "<encoding>")而不是b"\x01"可能会起作用,其中 encoding 是您的 python 文件的编码(如utf-8),尽管我不确定有什么区别。

另一个可能的错误原因:您的波特率很大。对于这样简单的事情,你不需要这么大的波特;使用标准的 9600 可以正常工作。尝试更改波特率,看看是否有帮助。


推荐阅读