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->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, 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 ![]()