esp8266i2carduino-esp8266floating

How to receive a float array using esp8266 via I2c


I tried to receive array of float values via I2c using Esp8s66 (in Arduino IDE) in the following way:

void receiveEvent(int byteCount) {
// Ensure byteCount matches the size of the float array
if (byteCount != ARRAY_LENGTH \* sizeof(float)) {
// Error handling: The received data size doesn't match the expected size
Serial.println("Error: Received data size mismatch");
return;
}

    // Read the received bytes and convert them into float values
    for (int i = 0; i < ARRAY_LENGTH; i++) {
        byte bytes[sizeof(float)];
        Wire.readBytes(bytes, sizeof(float)); // Read 4 bytes (1 float) from I2C
        floatArray[i] = *((float *)bytes); // Convert byte array to float
           Serial.println(floatArray[i], 1); // Print with 1 decimal places
    }

Any idea how to get this floating array? Tank you in advance!

I tried to interpret the received values via I2c


Solution

  • If the bytes stored a byte representative of a floating point value, then *(float*)bytes) would cast it back to a float. So it should be:

    float f = *(float*)bytes);
    Serial.println(f);
    

    and since you are using an ESP8266 and it supports Serial.printf(), you can do this as well:

    Serial.printf("%f\n", *(float*)bytes);