我正在与 Arduino 和 Raspberry pi 3 进行双向通信。Raspberry 需要向 Arduino 发送一个 Float 值,Arduino 收到此值后,需要将其与另一个浮点数相加并返回给覆盆子。但是当 arduino 将值发回时,它们是不正确的。
Arduino 代码:
float we = 0.0;
float wd = 0.0;
void setup(){
Serial.begin(9600);
}
void loop(){
if(Serial.available() > 0){
int valorWe = Serial.read() - '0';
int valorWd = Serial.read() - '0';
we = we + valorWe;
wd = wd + valorWd;
}
Serial.print(we);Serial.print(",");
Serial.println(wd);
delay(500);
}
树莓代码:
#!/usr/bin/env python3
import serial
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
ValorEsquerdo = 90
ValorDireito = 90
valorEnviado = 5
ValorRecebido = 0
we = 0.5
wd = 0.5
ser.flush()
# Infinite loop
while (1):
line = ser.readline().decode('utf-8')
# Take out the commas. Parse the string into a list.
parsed = line.split(',')
parsed = [x.rstrip() for x in parsed]
# We know we need to receive 2 integers. This code helps with any loss
# of data that might happen as data is transferred between Arduino
# and the Raspberry Pi.
if(len(parsed) > 1):
print(parsed)
ValorEsquerdo = float(float(parsed[0]+'0'))
ValorDireito = float(float(parsed[1]+'0'))
print("Valor roda esquerda: " + str(ValorEsquerdo))
print("Valor roda direita: " + str(ValorDireito))
ser.write(str(wd).encode('utf-8'))
ser.write(str(we).encode('utf-8'))
在下图中,您可以看到这些值是整数且不正确,因为我从 0 开始并增加了 0.5。