Setting up the sensor
The DS18B20 is a 1-wire digital sensor and is very easy to setup. It has 3 pins, 3.3v in, data & ground and you will also need a 4.7K-10K resistor 'pull-up' the data line.
Looking at the sensor with the flat side facing you:
- Pin 1 -> Raspberry Pi GND
- Pin 2 -> Raspberry Pi GPIO 4
- Pin 3 -> Raspberry Pi 3V
- 4.7K resistor goes between Pin 2 & 3
Setup the software
In order to read data from the sensor I needed to install some modules using modprobe. Once I had I could read the data from the sensor (including the current temperature) just like reading a file.
The sensor appeared as a directory in /sys/bus/w1/devices directory. The name of the directory is 28-########## with the hashes being the Id of the sensor:
I could then read the temperature data from the w1_slave file:
The data from the sensor looks like this:
The first line tells us whether the data read was successful with YES.
The second line displays the temperature as t=#####.
The temperature is returned in 1000's of a degress so 24437 is 24.437 centigrade.
I created a python module which would periodically sample the temperature from the sensor and allow a calling program to read the temperature from module as and when required, similar to the module I wrote for reading GPS data.
There is a more complete example of how to use the module in the code below but simply you use it like this:
Temperature Sensor Controller code