From 8db593a819a389cc1f87f525bf5b52a911116ba1 Mon Sep 17 00:00:00 2001 From: Phil Howard Date: Wed, 12 May 2021 15:00:43 +0100 Subject: [PATCH] AS7262 convert float correctly --- drivers/as7262/as7262.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/drivers/as7262/as7262.cpp b/drivers/as7262/as7262.cpp index 8f14ebfd..3309e104 100644 --- a/drivers/as7262/as7262.cpp +++ b/drivers/as7262/as7262.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "as7262.hpp" @@ -161,10 +162,19 @@ namespace pimoroni { i2c_write(reg, &value, 1); } + // convert the AS7262s 4-byte big-endian float value into a native float float AS7262::i2c_reg_read_float(uint8_t reg) { - float value; + uint32_t value; i2c_read(reg, (uint8_t *)&value, 4); - return __builtin_bswap32(value); + value = __builtin_bswap32(value); + + // Fails due to -Werror=strict-aliasing in MicroPython build + // return reinterpret_cast(value); + + // Assumes sizeof(uint32_t) == sizeof(float) + float result; + memcpy(&result, &value, sizeof(float)); + return result; } uint8_t AS7262::i2c_reg_read_uint8(uint8_t reg) {