Skip to content

Commit

Permalink
RTC_DS3231: handle negative temperatures
Browse files Browse the repository at this point in the history
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 adafruit#287.

[1] https://www.analog.com/media/en/technical-documentation/data-sheets/DS3231.pdf#page=15
  • Loading branch information
edgar-bonet committed May 6, 2024
1 parent 5298434 commit 5002b54
Showing 1 changed file with 2 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/RTC_DS3231.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**************************************************************************/
Expand Down

0 comments on commit 5002b54

Please sign in to comment.