【发布时间】:2023-03-29 21:31:01
【问题描述】:
我正在尝试通过 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'
或其他一些随机数。 我在这里做错了什么?
【问题讨论】:
-
也许你的python脚本应该发送
1并输入。