Arduino缓存串行连接?

2024-04-19 08:17:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用python从我的计算机与我的arduino通信。我让arduino在setup()的末尾通过串行发送一个1,因为它是在建立串行连接时运行的。然后,在python中,在将任何内容发送到arduino之前,我先听一下1。你知道吗

这是我的arduino代码:

int ledPin = 2;

void setup() {
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    Serial.write(1); // Ready signal
    digitalWrite(ledPin, HIGH); // For troubleshooting
    delay(200);
    digitalWrite(ledPin, LOW);
    delay(200);
    digitalWrite(ledPin, HIGH);
    delay(200);
    digitalWrite(ledPin, LOW);
}

void loop(){

}

还有我的Python:

import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)

ser.read(1) # Arduino sends one byte when serial connection established
print("Serial connected")
ser.close()

这在我第一次连接时就很好用了。我明白了:

$ python pyserialtest.py
Serial connected

但我第二次运行脚本时,什么也没发生。剧本挂了。我认为这是因为串行连接被python或arduino缓存,因此setup()没有运行。我试图通过在脚本末尾调用ser.close()来解决这个问题,试图清除连接,但仍然无法工作。你知道吗

我的arduino是uno版本3。Python版本2.7.6。你知道吗


Tags: importclosesetupserialarduinoserlowdelay
1条回答
网友
1楼 · 发布于 2024-04-19 08:17:20

请记住,Arduinosetup方法只运行一次。因此,第二次运行脚本时,脚本正在等待单字节串行确认,但它将永远等待,因为setup方法已经运行并将该字节发送到脚本的第一个实例。如果此时要重新启动Arduino,它将再次运行setup,发送确认字节,然后脚本将继续。你知道吗

相关问题 更多 >