系统相关
首页 > 系统相关> > 将串行通信(Ubuntu,Python)发送到Arduino

将串行通信(Ubuntu,Python)发送到Arduino

作者:互联网

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

我有一个非常基本的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-14-04,arduino,python
来源: https://codeday.me/bug/20191121/2048393.html