问题描述
我正在编写一个 Python 脚本,它向 Arduino 发送一个字符,然后 Arduino 将接收到的字符打印回来.但在这种情况下,Arduino 总是给出一个垃圾值.执行 Python 脚本时也没有错误.
I am writing a Python script, that sends a character to an Arduino and the Arduino prints the received character back. But in this case, the Arduino is always giving a garbage value. Also there is no error while executing the Python script.
我查阅了多篇博客、文章和教程,并按照具体步骤操作,但没有找到解决方案.
I have checked multiple blogs, articles and tutorials and followed the exact steps, but I got no solution.
这是我的 Python 脚本:
This is my Python script:
import serial
ser = serial.Serial("/dev/ttyACM0",9600)
ser.write('8')
read=ser.readline()
print(read)
这是 Arduino 代码:
This is the Arduino code:
int temp;
void setup() {
Serial.begin(9600);
temp=5;
}
void loop() {
temp=Serial.read();
Serial.println(temp);
delay(1000);
}
Arduino 总是打印 -1 作为响应.
Arduino always prints -1 in response.
推荐答案
退货
可用传入串行数据的第一个字节(如果没有可用数据,则为 -1) - int
the first byte of incoming serial data available (or -1 if no data is available) - int
按照 Ivan Sheigets 的建议或
So do as Ivan Sheigets suggested or
void setup() {
Serial.begin(9600);
Serial.print("You sent: ");
}
void loop() {
int temp=Serial.read();
if(temp>=0)
Serial.print((char)temp);
}
确保将传入的值转换为 char (char)temp
.
Make sure to cast the incoming value to char (char)temp
.
这篇关于Python serial.write() 不会向 Arduino 发送串行数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!