将整个变量从 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 = "";
}

最新更新