gpt4 book ai didi

python - Arduino/Python串行通信写入不工作

转载 作者:行者123 更新时间:2023-11-30 23:24:36 25 4
gpt4 key购买 nike

我正在尝试通过串口在 python 和 arduino 之间发送消息。我使用以下代码成功地进入了 Arduino->python 方向:

python :

import termios, fcntl, sys, os, serial, time, smtplib
ser = serial.Serial('/dev/tty.usbserial-AD02AY8A', 9600, writeTimeout = 0)
while 1:
message = ser.readline()
print(message)

Arduino:

// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
Serial.write('1');
}

// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
Serial.println("BOBBY");
delay(1); // delay in between reads for stability
}

在这种情况下,我可以查看arduino的串口和终端上的“屏幕命令”,以及通过python重印“BOBBY”。

当我尝试从 python 发送消息时,它从未显示在终端屏幕或 Arduino 串行端口上。

这是不起作用的Python代码。 arduino 代码对于这个来说应该不重要,因为我只是监视串行端口。

import termios, fcntl, sys, os, serial, time, smtplib
ser = serial.Serial('/dev/tty.usbserial-AD02AY8A', 9600, writeTimeout = 0)
time.sleep(2)

while 1:
try:
ser.write('1')
except: # catch *all* exceptions
print(e)

最佳答案

根据您的代码,我认为可以安全地假设您正在 Arduino 上使用 USB 串行接口(interface)。如果是这种情况,Arduino 会在每次通过 USB 接口(interface)建立串行连接时进行重置。

这将阻止它接收传输。您可以通过尝试使用 python 命令行而不是文件发送串行来测试这一点。

如果有效,您有两个选择,

1) 打开端口后写入 time.sleep(2) 行,以便 Arduino 有时间重新启动。 -或-

2)在Arduino板上的接地引脚和复位之间安装一个10微法拉电容。

这将防止它在串行端口连接时进入重置状态,并且稍后当您将板用于其他项目时可以轻松删除。

关于python - Arduino/Python串行通信写入不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23332198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com