How to read DS3231 Internal temperature sensor, example code


i have replaced ds1307 more accurate ds3231 rtc.

since familiar libraries ds1307 didnt want re-write code temperature reading. instead kept code same , added function returns temperature. believe might used minor moddifications other dalas i2c temperature sensors.

since lost bit of time finding needed, decided share.
example code below

code: [select]
#include <wire.h>
#define ds3231_i2c_addr             0x68
#define ds3231_temperature_addr     0x11

void setup()
{
  serial.begin(9600);
   wire.begin();
}

void loop()
{
   int tempc = ds3231_get_treg();  // reads temperature int, save memory
   // float tempc = ds3231_get_treg();
   delay(500);
   serial.print(tempc);
}

float ds3231_get_treg()
{
    int rv;  // reads temperature int, save memory
//  float rv;
   
    uint8_t temp_msb, temp_lsb;
    int8_t nint;

    wire.begintransmission(ds3231_i2c_addr);
    wire.write(ds3231_temperature_addr);
    wire.endtransmission();

    wire.requestfrom(ds3231_i2c_addr, 2);
    temp_msb = wire.read();
    temp_lsb = wire.read() >> 6;

    if ((temp_msb & 0x80) != 0)
        nint = temp_msb | ~((1 << 8) - 1);      // if negative two's complement
    else
        nint = temp_msb;

    rv = 0.25 * temp_lsb + nint;

    return rv;
}


you aren't doing conversion properly. arduino uses twos complement arithmetic there's no need convert. also, fraction part of twos complement number treating separately.
i use code:
code: [select]

  /*   short temp; */
  temp = wire.read() << 8;
  temp |= wire.read();
  return(temp/256.);


pete


Arduino Forum > Using Arduino > Sensors > How to read DS3231 Internal temperature sensor, example code


arduino

Comments

Popular posts from this blog

Connecting Raspberry Pi 2 to P10(1R)-V706 LED Dot Matrix - Raspberry Pi Forums

TypeError: <unknown> is not a numpy array - Raspberry Pi Forums

datso and removing imagetitle - Joomla! Forum - community, help and support