Sunday, 6 July 2014

Temperature logging with a DS18B20 and a Raspberry Pi

I wanted to do some temperature logging so I hooked up a DS18B20 temperature sensor to a Raspberry Pi.

About the DS18B20

Dallas DS18B20
The DS18B20 is a temperature sensor that is nice and cheap and reasonably accurate (±0.5°C) and only uses 1 pin on the Pi for data transfer even when multiple sensors are used.  

The Rasbian distribution has built in support for the 1 wire protocol making it easy to get up and running.








Connecting the temperature sensor

The sensors has three legs:
  1. Ground
  2. Data
  3. Either 3.3v or 5v
Here is a datasheet (from Maxim who now own Dallas) from this we can see we need to put a 4.7kΩ resistor between pins 2 and 3. Rasbian's built in support for 1-wire protocol is exposed on GPIO Pin 4 so this is where we need to connect pin 2 on the sensor to.

Use the following diagram to wire everything up. Connect pin 1 to GND, connect pins 2 & 3 with a 4.7kΩ resistor, connect pin 3 to 3.3V and then connect pin 2 to the Raspberry PI's GPIO pin 4.

Wiring the DS18B20

To access the sensor two modules need to be loaded, to do these use these commands:
sudo modprobe w1-gpio
sudo modprobe w1-therm
It will look like nothing happened but you will now be able to see the sensor, type
ls /sys/bus/w1/devices
28-000004e53685  w1_bus_master1

This is the output I get when I run this on my machine, the sensors is indicated by the file starting with "28", the numbers that come after that are different for each device (they have unique addresses) so yours will differ. To read the data type the following (substituting your device number)
cat /sys/bus/w1/devices/28-xxxxxxxxxxxx/w1_slave
a6 01 4b 46 7f ff 0a 10 f6 : crc=f6 YES
a6 01 4b 46 7f ff 0a 10 f6 t=26375

If the first line ends with "YES" then the temperature is available and it the value at the end of the second line. In this example the temperature is 2637 / 1000 = 26.375°C.

Here is some sample Python code
Save the code to a file called something like read-temp.py make it executable with chmod +x read-temp.py and the run it with ./read-temp.py and it will display the current temperature.

   Raw temp:  26562
Temperature:  26.6

Try putting your thumb on top of the sensor and re-running the code and you'll see the value read has gone up.

In my next blog I who how to add the LCD display to show the current temperature and how to log the data over time and produce a graph with gnuplot showing how the temperature has fluctuated.