python和arduino串口通信_将串行通信(Ubuntu,Python)发送到Arduino

当Python通过USB向ArduinoUnoR3发送命令时,若不加延迟,Arduino无法正确处理指令。原因是Arduino在串口打开时会自动复位,需要时间完成初始化。解决方案是在Python中加入延迟,确保Arduino有足够时间完成重置过程。此外,通过在Arduino端打印就绪消息,可以在Python端等待消息确认,从而避免硬编码延迟。
摘要由CSDN通过智能技术生成

这是我很长时间以来见过的最奇怪的事情.

我有一个非常基本的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完成其任务.

标签:ubuntu-14-04,arduino,python

来源: https://codeday.me/bug/20191121/2048393.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值