python - 将串行数据发送到 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'
或其他一些随机数。我在这里做错了什么?
解决方案
使用bytes("1", "<encoding>")
而不是b"\x01"
可能会起作用,其中 encoding 是您的 python 文件的编码(如utf-8
),尽管我不确定有什么区别。
另一个可能的错误原因:您的波特率很大。对于这样简单的事情,你不需要这么大的波特;使用标准的 9600 可以正常工作。尝试更改波特率,看看是否有帮助。
推荐阅读
- android - 黑色背景的应用程序图标 Android Studio
- r - R/Shiny:仅在单击操作按钮后更改绘图
- powershell - 从脚本中的临时文件中删除动态文本
- c# - 在 docuSign 中的用户之间传输信封
- c# - GMapRoute 没有得到正确的路线
- python - 有效地计算一个列表中的元素数量少于其他列表中的元素
- javascript - 如何从 Azure DevOps 扩展中检索工作项?
- clion - CLion 2019.2.1 工具链:未找到 WSL
- netsuite - 如何解决“请输入金额的值。” 使用 restlet 创建 NetSuite 发票时?
- asp.net - 响应在大量记录之前完成