Raspberry Pi 1- Wire Digital Thermometer Sensor (DS18B20)

TO-92 PackageWhile searching for a simple way to measure temperature using my Raspberry Pi I came across the DS18B20 1-wire digital temperature sensor. This promised an accurate way of measuring temperature with a few wires and almost no external components.

The device only cost a few pounds and it seemed too good to be true …

So I bought one. Within a few minutes I was measuring the temperature with it. It is so simple to use and the perfect starting point for creating a Raspberry Pi based temperature data logger.

DS18B20 Pin-out The diagram on the right shows the DS18B20 device. It has three pins and comes in a TO-92 package which means it looks similar to other devices you may have used such as transistors.

Pin 1 is Ground. Pin 2 is the data pin and Pin 3 is the power pin. The only external component required is a single 4.7Kohm resistor.

In my testing I didn’t have one of these so I used 2 x 2.2Kohm resistors in series. This worked fine.

I used a small piece of breadboard and some jumper cables to connect it to the GPIO header on my Raspberry Pi.

DS18B20 Temperature Sensor

DS18B20 Temperature Sensor

Pin 1 was connected to P1-06 (Ground)

Pin 2 was connected to P1-07 (GPIO4)

Pin 3 was connected to P1-01 (3.3V)

A 4.7Kohm resistor was placed between Pin 2 and Pin 3.

It is important to double check that you don’t confuse Pin 1 and Pin 3 on the device otherwise the power will be applied the wrong way round!

Once you have connected everything together you can power up your Raspberry Pi.

It’s always best to tackle new projects with an updated SD card. I tend to use the latest Raspbian image from the RaspberryPi.org download page and then update it from time to time using the following two commands :

sudo apt-get update
sudo apt-get upgrade

In order to configure the sensor you just need to make a small change to the config.txt file using :

sudo nano /boot/config.txt

add the following line to the bottom :

dtoverlay=w1-gpio,gpiopin=4

You can save the file using CTRL-X, Y then RETURN. The device is setup to report its temperature via GPIO4.

For the changes to take effect you will need to reboot using :

sudo reboot

Use the commands below to go to the directory that contains the detected 1-wire devices :

cd /sys/bus/w1/devices
ls

This will list the directories associated with your 1-wire devices. Each one has a unique ID and in my case it is 28-00000482b243. Your ID will be different so be sure to use that in the example code below. Using “cd” we can change to the temperature sensor directory, list the contents and then view the “w1_slave” file :

cd 28-00000482b243
ls
cat w1_slave

The complete command line setup process looks like this :

DS18B20 Command Line Setup

DS18B20 Command Line Setup

The “w1_slave” file contains a bunch of data but the “t=23062″ at the end is the temperature reading. In this example the temperature is 23.062 degrees Celsius (centigrade).

Try touching the sensor with your finger and then using “cat w1_slave” to take another reading …

In order to read the temperature via Python here is a basic script :

#!/usr/bin/python
def gettemp(id):
  try:
    mytemp = ''
    filename = 'w1_slave'
    f = open('/sys/bus/w1/devices/' + id + '/' + filename, 'r')
    line = f.readline() # read 1st line
    crc = line.rsplit(' ',1)
    crc = crc[1].replace('\n', '')
    if crc=='YES':
      line = f.readline() # read 2nd line
      mytemp = line.rsplit('t=',1)
    else:
      mytemp = 99999
    f.close()

    return int(mytemp[1])

  except:
    return 99999

if __name__ == '__main__':

  # Script has been called directly
  id = '28-00000482b243'
  print "Temp : " + '{:.3f}'.format(gettemp(id)/float(1000))

This ds18b20.py script can be downloaded directly to your Pi from BitBucket :

wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/ds18b20.py

and then run using :

python ds18b20.py

Note : You will need to replace my reference to 28-00000482b243 with the id of your device.

Troubleshooting :

  • Are you using the latest Raspbian image or have you updated your existing image?
  • Have you correctly wired up the device?
This entry was posted in Sensors, Tutorials & Help and tagged , , . Bookmark the permalink.



35 Responses to Raspberry Pi 1- Wire Digital Thermometer Sensor (DS18B20)

  1. Rpi1 says:

    I tried this using various tutorials but my Rpi with lastest firmware (rpi-update) is not detecting my DS18B20 sensor, I had a DHT11 which works fine.

    • rwise says:

      Have you tried using Occidentalis?

      • Matt says:

        No I haven’t tried that due to lack of time. Where possible I use the standard Raspbian image as that covers the most users and is always going to reflect the latest developments at the Foundation.

  2. Andrej says:

    Bought 2 DS18B20 and they work flawlessly, thank you!

  3. Yussuf says:

    Great article Matt. I was thinking about using these sensors to monitor my central heating system, Have you any idea how many of these sensors you can hook up ?

    I’d like to use at least 12 sensors to monitor various points in the system, out side temp and room temps. Eventually hooking up some valves and interface to the boiler to automate it all.

  4. Riyas says:

    worked flawlessly. Used to monitor my room temp remotely on vacation :-)

  5. Kamencesc says:

    Thank you, I’ve tried it with the DS18D20 in a PCB that I bought on ebay and it works perfect!

  6. Philip says:

    Thanks for the write up!

    I believe :

    Pin 3 was connected to P1-02 (3.3V)

    Is wrong, and it should actually be P1-01, as this is the 3.3V pin, and that’s actually how you’ve shown it on the diagram.

  7. Jeroen Steenhuis says:

    If using a long bus, it’s better to use a 10k resistor to +3,3 volt at both the begin and end of the line, otherwise echo on the line can disturb the communications…

    • Jeroen Steenhuis says:

      And also use an twisted pair like cat5 cable, I used green/white for data, green for ground (0 volt), brown/white for +3,3 volt, brown for data return.

      At the rpi i connected brown with green white to create 1 long path and put the resistors, 1 on the brown and one on the green/white…

  8. Marian says:

    I’m using collectd (sudo apt-get install collectd-core) with a perl CGI script (based on collection3 installed by collecd) to export the data via JSON to highcharts javascript library.

    http://renarin.zapto.org/wordpress/?p=26 shows my CPU & GPU temps.

  9. Pingback: ใช้ DS18B20 ผ่านทาง 1-Wire เพื่อวัดอุณหภูมิ | Raspberry Pi Thailand

  10. Pingback: LCD display with RPi and room temperature : The Unwritten Words

  11. Warren says:

    Hello, I am looking for a way to connect a thermometer in an item in the oven and send me the temps online. Also any idea were to get the probe?

  12. Pingback: Adding the temperature sensor to the Pi | Colin's Arduino, Computer and Electronics Blog

  13. Paulmw says:

    Hi,
    i have problem with GPIO4, i think it’s crashed. When I switch to mode out it comes to mode in after few seconds. What do you think?
    Is there any possibilities how to use these thermometer by 1W on other port?
    Thank you!

  14. Manolo says:

    hello ive been pouring over the internet trying to find a solution. my pi wont recognize the waterproof DS18B20 at all. could it be faulty? ive tried so many things. changed jumper cables, changed the resister etc.

  15. bookmarked, fantastic site!

  16. Ian says:

    stopped working since the sudo apt-get update then upgrade, have they done something to where the devices are now kept?

    Try an older ver of build

    • Matt says:

      It’s a bit confusing but try adding the following line to the end of /boot/config.txt :

      dtoverlay=w1-gpio,gpiopin=4

      I can’t find my sensor so can’t test at the moment.

  17. Jasper says:

    hello,

    wen i am try to look for the id of my senser.
    it won’t give the number but only w1_bus_master1
    does somone nows wath i am doing wrong?
    i use the TSIC 206/306 as sensor.

  18. Ramon says:

    How do you convert the following print command line so it would work in Python3?
    print “Temp : ” + ‘{:.3f}’.format(gettemp(id)/float(1000))

    I need to use Python3 and I’m getting a syntax error.

    • Matt says:

      I think you just put brackets around it as print is a function in Python 3 :
      print(“Temp : ” + ‘{:.3f}’.format(gettemp(id)/float(1000)))

      • Ramon says:

        Thanks, Matt! I tried enclosing it in double quotes and single quotes and didn’t try brackets.
        It works great! I’m displaying the temp on an I2c lcd and the library only works on Python3.

  19. Derek says:

    Please don’t ever type “sudo nano” or “sudo vim” etc.
    Always use “sudoedit” instead as this runs in a way that can’t be exploited and makes sure that the file hasn’t been edited under you causing changes to be trampled on.
    If you don’t like the editor that sudoedit uses, change your EDITOR variable in your bashrc.

  20. Wayne says:

    I am guessing the need to put dtoverlay=w1-gpio,gpiopin=4 into /boot/config.txt is due to the introduction of device tree. Have a look at this for more. http://www.raspberrypi.org/documentation/configuration/device-tree.md

  21. Pingback: What is a failproof method for testing a GPIO pin? | DL-UAT

  22. Florent says:

    Hi,

    I used your code for a quick and dirty systemd (Arch-arm for now) integration with logging to /var/tmp/temp (csv):

    https://github.com/UbiCastTeam/rpi-temp-logger

    Thanks to systemd, it does print out the current temperature to journalctl:
    Mar 10 15:52:53 myhost python[146]: Temp of sensor 28-0414604d6aff : 25.56 C
    Mar 10 15:53:24 myhost python[146]: Temp of sensor 28-0414604d6aff : 25.56 C

    I hope you don’t mind me reusing your code (i chose a BSD license); please tell if that’s an issue.

  23. Bogdan says:

    You are the best. My ds18b20 works fine.
    Thank you. I bookmarked the site.

  24. Tim says:

    I have been struggling for a month. Was it my sensors or my pi? So I bought another pi because I could not “see” my sensors. Still not luck. Added the one line of code dtoverlay=w1-gpio,gpiopin=4 there it was. Thanks!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>