Hi all,
In this blog post, I show how to read the temperature from a DS18B20 temperature sensor using Python on the Raspberry Pi.
This sensor is nice not only in that it's inexpensive, but it's also a digital sensor. Given that the Raspberry Pi doesn't easily handle analog inputs, the DS18B20 is a great choice.
In case you need it, here are my previous posts to help you get started with Python programming and IO pins for the Raspberry Pi:
For this tutorial, I am using:
1x Raspberry Pi Model B+ running Raspbian (other models should work fine too)
1x breadboard to make the connections
1x DS18B20 temperature sensor - I'm using a waterproof one with a foot long cable containing red, black, and yellow leads
3x M-F jumper wires
1x 10KΩ resistor
Edit: I tried this on a new RaspberryPi and it didn't work. Turns out I missed this step:
- Add the following line to /boot/config.txt
dtoverlay=w1-gpio
- You can edit that file with the leafpad editor by running "sudo leafpad /boot/config.txt" and then adding that line at the very bottom.
- Save, and reboot.
The hardware connections:
- put the 3 leads of the DS18B20 into the breadboard. (I found this worked ok enough, but ideally it's better to solder some good tips onto them for stronger connections.)
- connect a jumper wire from the yellow (data) wire to pin 7 (GPIO4) on the Raspberry Pi
- connect a jumper wire from the red (power) wire to pin 1 (3.3v) on the Raspberry Pi
- connect a jumper wire from the black (ground) wire to pin 9 (GND) on the Raspberry Pi
- add a 10KΩ resistor between data and power
So that's the hard part.
This is what is looks like:
(Check out my duct tape Pi case!)
Now open up the attached example (DS18B20.py) and run it, and you should see temperature numbers showing up on the Python console.
If you see error messages, it is most likely due to a loose wire. In my case the DS18B20 leads are a little short and one popped out, which caused some scary looking error messages when I tried to run the script!
The other thing I forgot at first was that 10K resistor - it is vitally important too.
This is what the output should look like, with numbers depending on your temperature, of course. Try putting your fingers on the sensor to see how that affects the readings.
For more details, also check out this Adafruit tutorial, which I used as a guide to get started.
The attached Python code is also derived from their example.
Edit: This has been tested and works on both the RPi model B+ and the RPi 2 model B.
Cheers,
-Nico
Top Comments