这是我在很长一段时间内看到的最奇怪的事情。
我有一个非常基本的python代码,可以使用Arduino Uno R3
上运行的Python
向Ubuntu
发送命令。
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 115200)
time.sleep(2)
if ser.isOpen():
print "Port Open"
print ser.write("START\n")
ser.close()
以上代码相应地工作并打印:
Port Open
6
我有一个Arduino运行,它接收此命令并切换LED。那很简单。
奇怪的是,如果我删除了行time.sleep(2)
,Arduino会停止切换LED。 Python仍打印出端口已打开且已成功传输6B。
为什么需要延迟? 我没有看到其他地方?我还从运行Windows的PC上测试了程序,结果相同。
修改 我用不同的波特率测试过,没关系,行为是一样的。 以下是Arduino代码,但我认为它不相关。
#define LED_PIN 2
#define FAKE_DELAY 2*1000
String inputString = ""; // a string to hold incoming data
boolean stringComplete = false; // whether the string is complete
void setup() {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
Serial.begin(115200);
inputString.reserve(50);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
digitalWrite(LED_PIN, HIGH); // turn the LED on (HIGH is the voltage level)
Serial.print("Processing incoming command: ");
Serial.println(inputString);
if (inputString.startsWith("START")) {
Serial.print("processing START...");
delay(FAKE_DELAY);
}
// clear the string:
inputString = "";
stringComplete = false;
digitalWrite(LED_PIN, LOW); // turn the LED off
}
}
/*
SerialEvent occurs whenever a new data comes in the
hardware serial RX. This routine is run between each
time loop() runs, so using delay inside loop can delay
response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
inputString += inChar;
// if the incoming character is a newline, set a flag
// so the main loop can do something about it:
if (inputString.endsWith("\n")) {
stringComplete = true;
}
}
}
答案 0 :(得分:3)
通过USB打开或关闭串口时,Arduino UNO会自动重置。所以你必须给Arduino足够的时间来完成重置。我通常使用一个ready check(print(Arduino) - read(Python))来避免python中的延迟:
Arduino的:
void setup ()
{
// ..... //
Serial.begin (115200);
Serial.print ("Ready...\n");
}
的Python:
import serial
ser = serial.Serial('/dev/ttyACM0', 115200)
print (ser.readline())
通过这种方式,python会一直等到读取就绪消息,从而有时间完成重置。
在关闭串口之前,您还必须等待Arduino完成任务。
如果您的项目出现自动重置问题,可以尝试将其停用Disabling Aruduino auto reset