I have a project and this project depends entirely on the communication between Arduino Due and Nano 33 BLE.
I want to send data via UART from the sensor located in the Nano as float data, and I receive it in the form of a float as well.
But by using Serial.read(), the data will be send as int, and by using Parsefloat, the information is received incorrectly.
Is there a way to send sensor data from nano to Due without error? And in the right form?
Here is the Nano code:
float h = 22.5;
float x, y, z;
int i = 0;
unsigned long previousMillis = 0;
const long interval = 500;
void TimerOhne();
void Acceleration();
void setup()
{
Serial.begin(9600);
Serial1.begin(9600);
if (!IMU.begin())
{
Serial.println("Failed to initialize IMU!");
while (1)
;
}
Serial.println("Read the serial");
}
void loop()
{
// TimerOhne();
Acceleration();
}
void TimerOhne()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
// save the last time you blinked the LED
previousMillis = currentMillis;
Serial1.write(h);
Serial.println(h);
Serial.println();
Serial.print("i ist: ");
Serial.print(i);
Serial1.write(66);
Serial1.write(i);
Serial.println();
i++;
}
}
void Acceleration()
{
if (IMU.accelerationAvailable())
{
IMU.readAcceleration(x, y, z);
}
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
x = x * 100;
y = y * 100;
Serial1.write(4);
Serial1.write(x);
Serial1.write(6);
Serial1.write(y);
Serial1.write(8);
Serial1.write(i);
i++;
Serial.print("X ist: ");
Serial.println(x);
Serial.print("y ist: ");
Serial.println(y);
}
}
Here is the Due code
float r;
unsigned long previousMillis = 0;
const long interval = 500;
void setup()
{
// Begin the Serial at 9600 Baud
Serial.begin(9600);
Serial1.begin(9600);
}
void loop()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
r = Serial1.read();
Serial.println(r);
}
}
To transport an
floatin binary you have to send the bytes of the float as a byte array.you can receive them as
Note: this assumes the float type is encoded the same way on both sides, which is true since both MCU are ARM architecture.
If you want to transport the number as text and parse it on the other Arduino, use
Serial1.print(x)to send it and you can use the parseFloat() function.