Loading...
Pages: [1]   Go Down
Author Topic: DS1821 Temperature Sensor over OneWire with Highest Resolution Calculation  (Read 1968 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 1
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I had a hard time finding some sample code for this because most OneWire examples assume addressable devices, but the DS1821 is non-addressable, I realize most people aren't using these devices, but I thought I'd share the code out for anybody else looking.


Code:
#include <OneWire.h>
#include <Wire.h>

OneWire  ds(10);  // on pin 10

void setup(void) {
  Serial.begin(9600);
  ds.reset();

}

unsigned int readBytes(int count)
{
    unsigned int val = 0;
    for (int i = 0; i < count; i++)
    {
        val |= (unsigned int)(ds.read() << i * 8);
    }
    return val;
}

void loop(void) {
  byte temp_read = 0;
  unsigned int count_remain = 0;
  unsigned int count_per_c = 0;
  byte configuration_register = 0;

  ds.reset();
  ds.write(0xEE); //Start Converting the temperatures 
 
   do {
        delay(1);
        configuration_register = 0;
        ds.reset();
        ds.write(0xAC);

        // Read the configuration Register from the DS1821
        configuration_register = readBytes(1);
    } while ((configuration_register & (1 << 7)) == 0); // If Bit #8 is 1 then we are finished converting the temp

 
    // Get Temp
    ds.reset();
    ds.write(0xAA);
    temp_read = readBytes(1); ;

    // Get Count Remaining
    ds.reset();
    ds.write(0xA0);
    count_remain = readBytes(2);

    // Load The Counter to populate the slope accumulator
    ds.reset();
    ds.write(0x41);

    // Read Count Per Deg
    ds.reset();
    ds.write(0xA0);
    count_per_c = readBytes(2);

    // If we are reading above the 200 mark then we are below 0 and need to compensate the calculation
    if (temp_read >= 200) temp_read -= 256;

    float highResTemp = (float)temp_read - .5 + (((float)count_per_c - (float)count_remain) / (float)count_per_c);

    highResTemp = (float)((1.80 * highResTemp) + 32.00);
    Serial.print(highResTemp);
    Serial.println(" Fahrenheit");

   delay(1000);
}


Logged

Netherlands
Offline Offline
Tesla Member
***
Karma: 90
Posts: 9401
In theory there is no difference between theory and practice, however in practice there are many...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset


Thanks for sharing!
Logged

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -

0
Offline Offline
Newbie
*
Karma: 0
Posts: 6
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

How to program the sensor in the thermostat mode and back into a thermometer?
Logged

Pages: [1]   Go Up
Print
 
Jump to: