这是我很长时间以来见过的最奇怪的事情.我有一个非常基本的python代码,可以使用在Ubuntu上运行的Python将命令发送到Arduino Uno R3.import serialimport timeser = serial.Serial(/dev/ttyACM0, 115200)time.sl...

这是我很长时间以来见过的最奇怪的事情.
我有一个非常基本的python代码,可以使用在Ubuntu上运行的Python将命令发送到Arduino Uno R3.
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;
}
}
}
解决方法:
通过USB打开或关闭串行端口时,Arduino UNO自动复位.因此,您必须给Arduino足够的时间来完成重置.我通常使用就绪检查(打印(Arduino)-读取(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
本文标题为:将串行通信(Ubuntu,Python)发送到Arduino


基础教程推荐
- Flask框架debug与配置项的开启与设置详解 2022-10-20
- Python实现字符串匹配算法代码示例 2023-09-04
- Python之路-Python中的线程与进程 2023-09-04
- python-如何在Windows上以提升的特权运行脚本? 2023-11-11
- 如何利用python turtle绘图自定义画布背景颜色 2023-08-04
- 使用Pycharm创建一个Django项目的超详细图文教程 2022-09-02
- Python遗传算法Geatpy工具箱使用介绍 2022-10-20
- 如何使用python生成大量数据写入es数据库并查询操作 2022-10-20
- CentOS7.4 安装Python3.5 2023-09-03
- Python中的def __init__( )函数 2022-10-20