arduino - 将整个变量从 raspberrypi (python) 发送到 arduino 时出错
问题描述
我想通过串行通信将存储在变量“int3”中的数字“500”从 python 传输到 arduino。arduino 使用 Serial.read() 读取数据,但只打印“5”。提前致谢。我有 int3、字节 2 和字节 3 要从 python 发送,但希望 arduino 打印 int3 的值。
import serial
import time
ser=serial.Serial('/dev/ttyACM0',9600)
int3 = 500
int3 = b'%d' %int3
while (1):
ser.write(int3)
ser.write(b'2')
ser.write(b'3')
#print type(ser.write)
time.sleep(1)
print(int3)
String r;
void setup(){
Serial.begin(9600);
// while(!Serial)
// {
// ;
// }
}
void loop(){
if(Serial.available() > 0){
r =(Serial.read() - 0); //conveting the value of chars to integer
Serial.print(r[0]);
delay(100);
//while(Serial.available () !=0) r=Serial.read();
}
}
解决方案
将 if 替换为 while 循环:
String fromRaspberry;
void loop(){
char c;
while (Serial.available() > 0) {
c = Serial.read(); //read char
fromRaspberry += c; //add the read char to string
}
int x = fromRaspberry.toInt(); //convert string to int
Serial.println(x);
// clear the string for new input:
fromRaspberry = "";
}
推荐阅读
- python - python键盘库 - 没有输出,但没有错误消息
- spring - WebSocket应用程序上的Spring CORS策略错误
- python - 在 Python 中发送带有函数输出的邮件
- visual-studio-code - 如何在拆分视图中查看设置 UI 和 JSON?
- python - Kivy:如何使用高度创建小部件 on_start:self.minimum_height
- c++ - valgrind的C++程序的内存使用信息错误?
- r - r data.table - 有条件地写入外部文件
- c# - C# 日期验证
- javascript - 浏览器未检测到使用 Compression-Webpack-Plugin 压缩并通过 AWS Webpack-S3-Plugin 上传的 .gzip 文件
- python - Seaborn barplot 在闪避参数下表现异常