[英]Send a String from Python to Arduino LCD
I want to display a string on an Arduino LCD 16x2 using python, but I've encountered problems with serial communication. 我想使用python在Arduino LCD 16x2上显示字符串,但是遇到串行通信问题。
Here is the code running in 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);
}
}
It works perfectly with Serial communication from Keyboard provided in Arduino IDE. 它与Arduino IDE中提供的键盘进行的串行通信完美配合。 But it doesn't work when I try to send a string using the Python script below:
但是当我尝试使用下面的Python脚本发送字符串时,它不起作用:
import serial
import sys
import time
arduino = serial.Serial('COM3', 9600, timeout=0)
stringa = 'hello'
arduino.write(bytes(stringa,'utf-8'))
arduino.close()
Where is the problem? 问题出在哪儿? I can't find a solution!
我找不到解决方案! Thanks.
谢谢。
Take a look at the difference between the timeouts in the C file above and the python script below. 看一下上面的C文件中的超时与下面的python脚本之间的时差 。
The timeout is 10 milliseconds in your C file wheareas it's 0 in your Python script. C文件中的超时时间为10毫秒,而Python脚本中的超时时间为0。 Also check the result of the arduino.write() to make sure that it was successful.
还要检查arduino.write()的结果以确保成功。
Possibly implement something like the following: 可能实现类似以下内容的东西:
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()
If this does not work then try checking the serial ports between both the C file and the Python script. 如果这不起作用,请尝试检查C文件和Python脚本之间的串行端口。 Make sure they are the same.
确保它们相同。 Hope this helps!
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.