Arduino/Python串口通信写入不工作
我正在尝试通过串口在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上查看串口,也可以通过终端的“screen命令”看到,还能通过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)
4 个回答
-2
这有点像在黑暗中摸索,但根据你的打印语句来看,这段代码是用Python 3写的。
你需要把所有的传输内容都转换成字节字符串,像这样:
ser.write('1'.encode())
-1
请尝试像这样添加 print(ser.write('1'))
。
while 1:
try:
ser.write('1')
print(ser.write('1'))
except: # catch *all* exceptions
print(e)
1
我试着用Arduino代码控制一个LED,看看是否有数据被写入端口。果然,它一直在写数据。但是在Arduino的串口监视器中却没有显示出内容。
以下是Arduino的代码:
int ledPin = 13;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
if (Serial.available()>0){
Serial.read();
for (int i = 0; i < 5; i++){
// read the input on analog pin 0:
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(ledPin, LOW); // turn the LED on (HIGH is the voltage level)
delay(50);
}
}
}
3
从你的代码来看,我觉得你应该是在使用Arduino的USB串口接口。如果是这样的话,每次通过USB接口建立串口连接时,Arduino都会自动重启。
这会导致它无法接收数据。你可以尝试用Python命令行发送串口数据,而不是用文件来测试一下。
如果这样可以成功,你有两个选择:
1) 在打开端口后加一行time.sleep(2),这样可以给Arduino一些时间来重启。-或者-
2) 在Arduino板的地线引脚和重置引脚之间安装一个10微法拉的电容。
这样可以防止在串口连接时Arduino重启,等你用这块板做其他项目时,这个电容也可以很容易地拆掉。