如何通过 I2c 使用 esp8266 接收浮点数组

问题描述 投票:0回答:1

我尝试使用 Esp8s66(在 Arduino IDE 中)通过 I2c 通过以下方式接收浮点值数组:

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
    }

知道如何获取这个浮动数组吗? 提前给你加油!

我尝试通过 I2c 解释接收到的值

esp8266 i2c arduino-esp8266 floating
1个回答
0
投票

如果

bytes
存储了代表浮点值的字节,则
*(float*)bytes)
会将其转换回
float
。所以应该是:

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

由于您使用的是 ESP8266 并且它支持

Serial.printf()
,您也可以这样做:

Serial.printf("%f\n", *(float*)bytes);
© www.soinside.com 2019 - 2024. All rights reserved.