python - 向 Arduino 发送串行通信(在 Ubuntu 上使用 Python)

标签 python arduino ubuntu-14.04

这是我很长一段时间以来看到的最奇怪的事情。

我有非常基本的 Python 代码来向 Arduino Uno R3 发送命令使用在 Ubuntu 上运行的 Python .

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 中的延迟:

阿杜伊诺:

void setup ()
{
    // ..... //
    Serial.begin (115200);
    Serial.print ("Ready...\n");
}

python :

import serial

ser = serial.Serial('/dev/ttyACM0', 115200)
print (ser.readline())

通过这种方式,Python 会一直等待,直到读取就绪消息,为完成重置留出时间。

在关闭串行端口之前,您也必须等待 Arduino 完成其任务。

如果自动重置对您的项目来说是个问题,您可以尝试禁用它 Disabling Arduino auto reset

关于python - 向 Arduino 发送串行通信(在 Ubuntu 上使用 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183378/

相关文章:

python - 在python中的图像中的表格上创建边框

用键盘或其他硬件按钮控制 Helm 机?

git - 为什么 Ubuntu 机器无法访问 Github?

c++ - 在函数中重载运算符而不写入主体 2 次

android - 适用于 Android 的类似 Gameboy 的按键和方向键

ruby - 净 :HTTP SSL negotiation timeout on Ubuntu 14. 04

c - Ubuntu串行通信: reads failing and then coming in all at once

python - Pandas 切片,列中带有冒号

python - 以 eps 格式导出时,Matplotlib 标签/标题消失

python - 使用 Flask 和 MongoEngine 开发 Tumblelog 应用程序时出错