Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Negative Temperatures reported incorrectly by getTemperature() in RTC_DS3231.cpp #267

Open
girishnand opened this issue Nov 16, 2022 · 0 comments

Comments

@girishnand
Copy link

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;
}

From: https://datasheets.maximintegrated.com/en/ds/DS3231.pdf -

Temperature Registers (11h–12h)
Temperature is represented as a 10-bit code with a resolution of 0.25°C and is accessible at location 11h and 12h. The
temperature is encoded in two’s complement format. The upper 8 bits, the integer portion, are at location 11h and the
lower 2 bits, the fractional portion, are in the upper nibble at location 12h.

Although variable buffer[0] holds a signed value in twos complement format, it has been declared as uint8_t. Casting the value in buffer[0] to float does not handle negative values correctly, and we find in practice that for example a temperature of -1 deg C which is read from the DS3231's registers as {255,0}, is returned by this function as 255 deg C, and not as -1 deg C.

Changing the last line of the function to the following corrects this.

return (float) (*(int8_t *)buffer) + (buffer[1] >> 6) * 0.25f;

regards,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant