Code:


//Matt G.
//onion@doorcreekorchard.com
//July 2008


boolean getOneWireTemp(byte *addr, double *retnTemp, OneWire * OW){
  byte present = 0;
  byte data[12];
  int raw;
  double temp;

  OW->reset();
  OW->select(addr);
  OW->write(0x44,1);         // start conversion, with parasite power on at the end

  delay(800);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = OW->reset();
  if (present)  //only continue if the sensor is actually there and responding
  {
    OW->select(addr);    
    OW->write(0xBE);         // Read Scratchpad which now contains the temperature data
    for ( int i = 0; i < 9; i++) {           // we need 9 bytes
      data[i] = OW->read();
    }
     if ( OneWire::crc8( data, 8) != data[8]) {
        //Serial.println("CRC is not valid!\n");
        return false;
        }
    raw=(data[1]<<8)+data[0];  //put the two bytes of the temperature (from the response) into a raw int
    temp = (double)raw * 0.0625; //convert to celcius
    *retnTemp=temp*1.8+32;//convert to fahrenheit and set the final return value
    return true;
  }
    return false;
}

Example usage:

#include <OneWire.h>

/* DS18B20 Temperature chip i/o

 */

byte sensor1[8]= {0x28,0xB5,0x4E,0x8A,0x01,0x00,0x00,0xD0};
OneWire  ds(12);  // on pin 12

void setup(void) {
  // initialize inputs/outputs
  // start serial port
  Serial.begin(19200);
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
}

char* tempToAscii(double temp)
{
  char ascii[32];
  int frac;
  frac=(unsigned int)(temp*1000)%1000;  //get three numbers to the right of the deciaml point
 itoa((int)temp,ascii,10);
  strcat(ascii,".");
  itoa(frac,&ascii[strlen(ascii)],10); //put the frac after the deciaml

  return ascii;
}

void loop(void) {
  double temp;

  if (getOneWireTemp(sensor1,&temp,&ds))
  {
   Serial.println(tempToAscii(temp));
  }

Notes:Takes 3 parameters:

  1. Pointer to the OneWire address of the temperature sensor
  2. Pointer to a place to write the sensor reading
  3. Pointer to the OneWire object

Returns true if successful getting the temperature, false is something went wrong.

I don't really take any credit for this code, it's really just a re-organization of code I found on the forums. Hopefully people will find this useful as bit of an abstraction layer. Perhaps I'll make an official library with more stuff some time. Another useful function is the tempToAscii in the example code.

Share