Self-contained function for DS18B20 getOneWireTemp

This is mostly just some re-organizing of code I’ve gleaned off this forum, but it might be useful for anyone doing stuff with OneWire temperature sensors. It relies on the very good existing OneWire library. Here’s the function:

boolean getOneWireTemp(byte *addr, double *retnTemp, OneWire * OW){
  byte present = 0;
  byte data[12];
  int raw;
  double temp;
  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->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, const is for converting DS18B20 data
    *retnTemp=temp*1.8+32;//convert to fahrenheit and set the final return value
    return true;
    return false;

Takes 3 parameters:

Pointer to the OneWire address of the temperature sensor
Pointer to a place to write the sensor reading
Pointer to the OneWire object
Returns true if successful getting the temperature, false is something went wrong.

Comments, suggestions, etc are welcome. I’m somewhat of a newbie coder, so tell me what you think :slight_smile:

Almost forgot! Here’s some an example usage code!

#include <OneWire.h>

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

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(frac,&ascii[strlen(ascii)],10); //put the frac after the deciaml
  return ascii;

void loop(void) {
  double temp;
  if (getOneWireTemp(sensor1,&temp,&ds))

Again, comments, criticism, etc, welcome :slight_smile: