向 arduino 发送串行数据在串行监视器中有效,但在 python 中无效
sending serial data to arduino works in serial monitor, but not in python
我正在尝试通过 python 脚本将我的 arduino 上的一位从 0 翻转到 1。如果我在串行监视器中键入 1 并按回车键,以下 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'
或其他一些随机数。
我在这里做错了什么?
使用 bytes("1", "<encoding>")
而不是 b"\x01"
可能有效,其中编码是 python 文件的编码(如 utf-8
),尽管我不确定是什么区别是
另一个可能的错误原因:你的波特率太大了。对于像这样简单的事情,您不需要这么大的波特率;使用标准 9600 可以正常工作。尝试更改波特率,看看是否有帮助。
我正在尝试通过 python 脚本将我的 arduino 上的一位从 0 翻转到 1。如果我在串行监视器中键入 1 并按回车键,以下 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'
或其他一些随机数。 我在这里做错了什么?
使用 bytes("1", "<encoding>")
而不是 b"\x01"
可能有效,其中编码是 python 文件的编码(如 utf-8
),尽管我不确定是什么区别是
另一个可能的错误原因:你的波特率太大了。对于像这样简单的事情,您不需要这么大的波特率;使用标准 9600 可以正常工作。尝试更改波特率,看看是否有帮助。