Open edgar-bonet opened 4 months ago
We ran into the same problem with negative temps. Do you have any idea when this will be merged?
@BillyGriffiths: No idea. This repo seems practically unmaintained. The last change to the source code of the library was the merge of pull request #257, on 2022-08-04. Since then, it has only had minute changes that do not touch the source code of the library itself.
As reported in issue #287, the method
RTC_DS3231::getTemperature()
fails on negative temperatures. This is because the conversion from raw bytes to afloat
-typed temperature assumes the value is always positive, wheres the datasheet specifies it is stored as a signed, two's complement integer.This pull request fixes the method by changing the conversion code to this:
Some points worth noting:
Casting
buffer[0]
to an unsigned type is meant to avoid signed integer overflow, which is undefined behavior in C++.Assigning the result to a signed integer makes numbers with the most significant bit set be interpreted as negative. There is no extra work to do, as all current processors use two’s complement representation internally.
Multiplying by
1 / 256.0
(rather than1 / 4.0
) obviates the need for the 6-bit shift. Also,1 / 256.0
being a compile-time constant, there is no division performed at run-time (which would be expensive).This code also reduces the number of floating-point operations to only two (int-to-float conversion and multiplication), v.s. four in the original code (two int-to-float conversions, one multiplication and one addition).
Tested down to −27.00°C by @i440bx.
Fixes #287.