【问题标题】:Send a String from Python to Arduino LCD从 Python 向 Arduino LCD 发送字符串
【发布时间】:2018-03-18 13:41:24
【问题描述】:

我想使用 python 在 Arduino LCD 16x2 上显示一个字符串,但我遇到了串行通信问题。

这是在 Arduino 中运行的代码:

Arduino 代码

#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
String stringa;
const unsigned long TimeOut = 10; // timeout 10 ms
String stringa1;
String stringa2;

void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop() {
  stringa = "";
  unsigned long T = 0; // timer
  T = millis(); // timer running
  while (millis() - T < TimeOut) {
    // waiting timeout
    while (Serial.available() > 0) {
      // receiving Serial
      stringa += char(Serial.read()); // add char
      T = millis(); // reset timer
    }
  }
  if (stringa.length() > 32) {
    lcd.setCursor(0, 1);
    lcd.print("stringa length: " + stringa.length());
    delay(2000);
    lcd.print("                ");
  } else {
    stringa1 = stringa.substring(0 , 16);
    stringa2 = stringa.substring(16);
    lcd.setCursor(0, 0);
    lcd.print(stringa1);
    lcd.setCursor(0, 1);
    lcd.print(stringa2);
    delay(5000);
  }
}

它与 Arduino IDE 中提供的键盘串行通信完美配合。但是当我尝试使用下面的 Python 脚本发送字符串时它不起作用:

Python 代码

import serial
import sys
import time
arduino = serial.Serial('COM3', 9600, timeout=0)
stringa = 'hello'
arduino.write(bytes(stringa,'utf-8'))
arduino.close()

问题出在哪里?我找不到解决办法!谢谢。

【问题讨论】:

    标签: python string serialization arduino pyserial


    【解决方案1】:

    看看上面的 C 文件和下面的 python 脚本中的超时之间的区别

    在 C 文件中超时为 10 毫秒,而在 Python 脚本中为 0。还要检查 arduino.write() 的结果以确保它成功。

    可能实现如下:

    import serial
    import sys
    import time
    arduino = serial.Serial('COM3', 9600, timeout=10)
    stringa = 'hello'
    try:
        arduino.write(stringa.encode())
    except OsError:
        print "Write failed!"
    arduino.close()
    

    如果这不起作用,请尝试检查 C 文件和 Python 脚本之间的串行端口。确保它们相同。希望这会有所帮助!

    【讨论】:

    • 不管怎样都不管用...就像Arduino没有看到与python脚本的连接
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多