This is a basic tutorial on how we can use a DS18B20 temperature sensor with a Raspberry Pi. For the communication between the two devices we will be using the 1-wire interface. This interface can be used to connect to plethora of inexpensive sensors. Each of these sensors have their own 64 bit serial code. This feature lets us connect more sensors to the same 1-wire bus. You can read more about it here. So let’s begin :
Contents
Hardware Requirements
- DS18B20 temperature sensor
- 4.7k ohm resistor
- Jumper cables
- Raspberry Pi 3
Circuit Diagram
NOTE : If you are using the water proof version of the same sensor, you can follow convention and conned the red, black and yellow wires to 3.3v, GND, and pin 4 as shown in the fritzing diagram above.
Setup
First we need to alter the Raspberry Pi’s config file to enable the 1 wire interfacing (use by this sensor).
- Open /boot/config.txt with your favorite text editor
sudo nano /boot/config.txt
- canAdd the following line to the bottom of the file
dtoverlay=w1-gpio,gpiopin=4
- You should also load in the device kernel modules by running the following
sudo modprobe w1-gpio
sudo modprobe w1-therm
Testing the sensor
- Open your terminal at the location of the temperature sensor.
cd /sys/bus/w1/devices
- Write the command
ls
to list out all w1 devices. you will see an alpha numeric similar to28-0314977912af
, this number is the serial number of your sensor. You mustcd
into this directory withcd 28-0314977912af
. - Next, we have to list out the contents of the file named
w1_slave
.
cat w1_slave
- You will get an output similar to this
dd 01 55 05 7f a5 a5 66 81 : crc=81 YES
dd 01 55 05 7f a5 a5 66 81 t=29812
The number that follows t=
is the temperature in micro degree celcius (10^-3).
Python Script
def get_temp(dev_file):
f = open(dev_file,"r")
contents = f.readlines()
f.close()
index = contents[-1].find("t=")
if index != -1 :
temperature = contents[-1][index+2:]
cels =float(temperature)/1000
return cels
if __name__ =="__main__":
temp = get_temp("/sys/bus/w1/devices/28-0314977912af/w1_slave")
print(temp)
- First, we open and read the file that contains the temperature.
- We locate where the number is and store it in
temperature
. - We then divide the
temperature
by 1000 and thus return the temperature in degree celcius. - Finally we run the
get_temp
function.
Alternatives
Apart from the DS18B20 temperature sensor you can also use the DHT11 and DHT22 temperature sensors. These sensors contain two major components — a thermistor and a humidity sensor. These sensors have also been documented extensively and there many resources to follow. You can follow the installation process here and see some example code here.
Conclusion
With this I conclude this simple tutorial on how you can control a DS18B20 temperature sensor with your Raspberry Pi. I also hope you learnt a bit about the 1-Wire interface.
Thank you for reading
Happy Learning 😀