Raspberry Pi 1- Wire Digital Thermometer Sensor (DS18B20)

42

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?
Share.

42 Comments

  1. 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.

      • 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. 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.

  3. 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.

  4. Jeroen Steenhuis on

    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 on

      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…

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

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

  7. 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?

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

  9. 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!

  10. 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.

  11. 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

    • 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.

  12. 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.

    • Hi Jasper,
      your sensor (Tsic) is not supported by the 1wire protcoll. You will need to use the zacwire protocoll in order to read out Tsic sensors.

  13. 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.

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

      • 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.

  14. 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.

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

  16. 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.

  17. 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!!

  18. Sigh – I have a knack of finding problems no-one has published yet.
    I have several DS18B20 with either a Raspberry Pi 1B or v2 which insists it constantly 85 C where I am playing. For those that aren’t aware 85 is the default temperature recorded at power up. My problem is that I cannot convince it to change to something realistic.
    Since everything I have read does not include explicitly sending a Convert T command, I presume that that is not necessary.
    I’m assuming that, I’m missing something really trivial, or something is amiss in the drivers on all of my SD cards and for both versions. Now I’m out of my league – I have no idea where to look and what for.

    Anyone got any suggestions ?

    cheers
    Graham
    ( New Zealand )

    • All I can suggest is creating a fresh SD card with the latest Raspbian image, using 1 sensor and following the tutorial. I’m not sure what you mean by a “Convert T command”?

  19. So here’s a very red face | 😉 |
    It turns out I failed to notice a pesky little ‘p’ on the end of the part number !! – that makes it parasitic power only, and I haven’t been doing that. :-(
    So in exchange for a couple of days head scratching and cussing – at least I’ve learned what the symptom is for that ‘wrong device’ or ‘incorrectly connected’ scenario.
    cheers
    Graham.

    • Not familiar with the device but seems to be just a resistor that varies with temperature. It has no intelligence doesn’t support the 1-wire protocol.

  20. Pingback: Hooking Up Thermometer to Raspberry Pi (DS18B20) | Pythagoraspberry

Leave A Reply