From 5002b540838ed22465c8530f1f632cdcd03fbd16 Mon Sep 17 00:00:00 2001 From: Edgar Bonet Date: Fri, 16 Jun 2023 14:16:42 +0200 Subject: [PATCH] RTC_DS3231: handle negative temperatures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RTC_DS3231::getTemperature() assumes the temperature register stores a positive integer whereas, according to the datasheet,[1] it is a signed number in two’s complement format. Fix the method by transferring this register into a signed 16-bit integer. As the CPU uses two’s complement natively, no further conversion is needed other than scaling by a factor (1/256.0). Fixes #287. [1] https://www.analog.com/media/en/technical-documentation/data-sheets/DS3231.pdf#page=15 --- src/RTC_DS3231.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/RTC_DS3231.cpp b/src/RTC_DS3231.cpp index c24a65a2..38890a80 100644 --- a/src/RTC_DS3231.cpp +++ b/src/RTC_DS3231.cpp @@ -114,7 +114,8 @@ void RTC_DS3231::writeSqwPinMode(Ds3231SqwPinMode mode) { float RTC_DS3231::getTemperature() { uint8_t buffer[2] = {DS3231_TEMPERATUREREG, 0}; i2c_dev->write_then_read(buffer, 1, buffer, 2); - return (float)buffer[0] + (buffer[1] >> 6) * 0.25f; + int16_t temp = uint16_t(buffer[0]) << 8 | buffer[1]; + return temp * (1 / 256.0); } /**************************************************************************/