Facebook Twitter Instagram Pinterest YouTube
    Trending
    • Pi Pico W Launched
    • Add Kodi to RetroPie Menu
    • Disable Auto-login in Raspberry Pi OS
    • Raspberry Pi Cloud Storage with MEGA
    • RetroPie Temperature Monitor from Menu
    • Pi Pico Pinout and Power Pins
    • Install Arduino IDE on Raspberry Pi
    • Raspberry Pi 400 SSD Upgrade
    Facebook Twitter Instagram Pinterest YouTube RSS
    Raspberry Pi SpyRaspberry Pi Spy
    • Home
    • Categories
      • General
      • Hardware
      • Programming
      • Python
      • Software
      • Tutorials & Help
    • BerryClip
      • BerryClip Instructions
      • BerryClip Plus Instructions
      • Videos & Reviews
    • Buy
      • Buy Pi
      • Buy Pi Accessories
      • Buy Books
    • Tools
      • Ultimate Raspberry Pi Alexa Skill
      • Pi Power Estimator App
      • Pi-Lite 14×9 LED Matrix Sprite Editor
      • RPiREF Pin-out Reference App
      • Simple Ohm’s Law Calculator
      • Web Sites & Links
    • Tutorials & Help
        Featured
        November 9, 20200

        Raspberry Pi Temperature Monitoring

        Recent
        May 6, 2022

        Add Kodi to RetroPie Menu

        February 26, 2022

        Disable Auto-login in Raspberry Pi OS

        February 2, 2022

        Raspberry Pi Cloud Storage with MEGA

      1. Contact Us
      2. Site Map
      Raspberry Pi SpyRaspberry Pi Spy
      You are at:Home»Hardware»Interfaces»1-wire»Using DS18B20 Digital Temperature Sensors with the Raspberry Pi
      DS18B20 waterproof temp sensors

      Using DS18B20 Digital Temperature Sensors with the Raspberry Pi

      52
      By Matt on March 15, 2013 1-wire, Sensors, Tutorials & Help

      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-outDS18B20 Temperature Sensor

      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.

      Hardware Setup

      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
      • Sensor Pin 1 connected to P1-06 (Ground)
      • Sensor Pin 2 connected to P1-07 (GPIO4)
      • Sensor Pin 3 connected to P1-01 (3.3V)

      A 4.7Kohm resistor was placed between Sensor pin 2 and 3.

      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.

      Update Raspbian

      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

      Enable 1-Wire Interface

      The DS18B20 sensor uses the 1-Wire protocol. This needs to be enabled so either follow the instructions below or refer to the Enable 1-Wire Interface on the Raspberry Pi post.

      In order to enable the 1-Wire interface 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

      Check for Connected Devices

      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.

      Get Sensor ID

      Each sensor 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.

      Read Temperature

      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 enabled the 1-wire interface?
      • Have you correctly wired up the device?
      • Did you add the correct sensor ID to the Python script?
      Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
      Previous ArticleCheap PIR Sensors and the Raspberry Pi – Part 2
      Next Article Top 10 Things to Connect to Your Raspberry Pi

      Related Posts

      Add Kodi to RetroPie Menu

      Disable Auto-login in Raspberry Pi OS

      Raspberry Pi Cloud Storage with MEGA

      52 Comments

      1. Rpi1 on March 16, 2013 9:17 am

        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.

        Reply
        • rwise on March 21, 2013 3:00 pm

          Have you tried using Occidentalis?

          Reply
          • Matt on March 22, 2013 10:51 am

            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.

            Reply
      2. Andrej on March 20, 2013 4:44 pm

        Bought 2 DS18B20 and they work flawlessly, thank you!

        Reply
      3. Yussuf on March 28, 2013 10:29 pm

        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.

        Reply
      4. Hindberid on April 4, 2013 7:31 pm

        Hi.
        I use graphite for data logger.
        http://hindberid.is/index.php/raspberry-pi

        Reply
      5. Riyas on April 6, 2013 11:41 pm

        worked flawlessly. Used to monitor my room temp remotely on vacation 🙂

        Reply
      6. Kamencesc on April 24, 2013 10:49 pm

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

        Reply
      7. Philip on April 27, 2013 12:02 am

        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.

        Reply
        • Matt on April 29, 2013 8:14 pm

          Well spotted. I have updated the text.

          Reply
      8. Jeroen Steenhuis on May 9, 2013 4:36 pm

        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…

        Reply
        • Jeroen Steenhuis on May 9, 2013 4:39 pm

          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…

          Reply
          • discarn8 on January 10, 2016 8:18 am

            Jeroen – how far away was your sensor from your pi? 10′? 20′? 30′?

            Also, do you have a quick diagram of what you are describing? I’m having a little trouble visualizing it. Thanks in advance.

            Reply
      9. Marian on May 10, 2013 4:52 am

        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.

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

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

      12. Warren on July 21, 2014 4:01 am

        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?

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

      14. Paulmw on October 24, 2014 8:25 pm

        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!

        Reply
      15. Manolo on November 8, 2014 1:54 am

        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.

        Reply
      16. Zoey Sullivan on January 13, 2015 10:14 pm

        bookmarked, fantastic site!

        Reply
      17. Ian on February 6, 2015 7:10 pm

        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

        Reply
        • Matt on February 6, 2015 9:13 pm

          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.

          Reply
          • Rick on February 9, 2015 9:28 pm

            type: nano /boot/config.txt

            Btw thanks for the information, it works now here !

            Reply
            • Greg on February 17, 2015 3:05 pm

              Had the same issue this AM after reboot. Adding
              dtoverlay=w1-gpio,gpiopin=4
              to /boot/config.txt fixed the problem for me.

              Thanks!

              Reply
              • Dan on March 8, 2015 1:28 pm

                Thanks, I was worried I broke the sensors, but this worked for me! 3/8/15

      18. Jasper on February 17, 2015 1:49 pm

        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.

        Reply
        • Sylvia on April 28, 2015 5:57 pm

          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.

          Reply
      19. Ramon on February 18, 2015 9:09 pm

        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.

        Reply
        • Matt on February 18, 2015 9:50 pm

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

          Reply
          • Ramon on February 19, 2015 5:13 am

            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.

            Reply
            • whooper on March 27, 2016 2:48 am

              Short Bus = Networks of less than 1 meter (3 feet).
              Long Bus = Anything longer than a short bus.

              You can also make VDD = 5V (power it from the 5V pin) and Vpullup = 3.3V. The sensor Data line (DQ) is open-drain so it can only go as high as the Vpullup voltage.

              And by the way .. did you know that you can ask MAXIM for a couple of sample sensors?

              https://www.maximintegrated.com/en/app-notes/index.mvp/id/148

              Reply
      20. Derek on February 19, 2015 6:42 pm

        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.

        Reply
      21. Wayne on March 6, 2015 12:36 pm

        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

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

      23. Florent on March 10, 2015 2:58 pm

        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.

        Reply
      24. Bogdan on April 16, 2015 6:12 pm

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

        Reply
      25. Tim on April 18, 2015 5:39 pm

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

        Reply
      26. Graham on April 28, 2015 11:07 am

        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 )

        Reply
        • Matt on April 28, 2015 8:11 pm

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

          Reply
      27. Graham on April 30, 2015 3:29 am

        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.

        Reply
      28. dhouha on May 15, 2015 1:52 pm

        Hi

        I have “pt100” analog temperature sensor ;is it supported by the 1wire protcoll?

        Reply
        • Matt on May 22, 2015 7:59 pm

          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.

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

      30. Bqt on January 7, 2016 8:48 pm

        Hi
        Got GPIO4 occupied by RTC.
        Changed to another port and altered command to:
        dtoverlay=w1-gpio,gpiopin=24

        Works perfect in Python2, not at all in Python3.

        Lets go fill the house with temp-sensors 😉

        Reply
      31. discarn8 on January 10, 2016 8:22 am

        Is anyone familiar with the maximum distance that one can have the sensor away from the pi? I read Jeroen’s post above, but I am wondering if the sensor could be mounted 20 to 50′ away and still provide an accurate reading? Has anyone tested this? Thanks in advance

        Reply
        • whooper on March 27, 2016 3:16 am

          Use a serial/usb adapter. You can reach 30m (100 ft) with one.

          If you have a sensor reading (and not the default 85 deg C) it’s as accurate as it can be.

          With the GPIO, in order to have a longer cable .. try lower the resistor value to 2kohm, see what you get.

          Reply
      32. John Wiggins on January 29, 2017 7:36 am

        if you want to use the sensor without having to reboot you can run

        sudo modprobe w1-gpio

        Reply
      33. James on September 10, 2017 1:19 pm

        Hi,

        Great article – much appreciated.

        I am new and trying to get in to electronics.

        How did you know that this requires a 4.7Kohm resistor?

        What does the dtoverlay=w1-gpio,gpiopin=4 command do, and is it necessary for newer Pis?

        Thanks

        Reply
        • Matt on September 10, 2017 4:31 pm

          The value of the resistor is specified in the datasheet for the DS18B20 (https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf)
          The dtoverlay command tells the system you want to use the 1-wire protocol on GPIO4. This required for newer Pis.

          Reply
      34. mark xavier on January 29, 2020 7:58 pm

        Great article…..I want to use two temp sensors on gpio 4 and gpio17
        what should my entry in config.txt be?
        dtoverlay=w1-gpio,gpiopin=4

        Reply
        • Matt on May 20, 2020 9:58 pm

          Ideally you should connect both sensors to GPIO4. Each one will have its own ID and you can read them independently in your software.

          Reply

      Leave A Reply Cancel Reply

      This site uses Akismet to reduce spam. Learn how your comment data is processed.

      Recent Posts
      June 30, 2022

      Pi Pico W Launched

      May 6, 2022

      Add Kodi to RetroPie Menu

      February 26, 2022

      Disable Auto-login in Raspberry Pi OS

      February 2, 2022

      Raspberry Pi Cloud Storage with MEGA

      January 7, 2022

      RetroPie Temperature Monitor from Menu

      Categories
      • 1-wire
      • 3D Printing
      • Add-ons
      • BBC Micro:bit
      • BerryClip
      • Books
      • Camera Module
      • Cases
      • Events
      • General
      • Hardware
      • I2C
      • Infographics
      • Interfaces
      • Minecraft
      • Model A+
      • Model B+
      • News
      • Pi Models
      • Pi Pico
      • Pi Zero
      • Power
      • Programming
      • Python
      • Raspberry Pi OS
      • Raspbian
      • RetroGaming
      • Robotics
      • Sensors
      • Software
      • SPI
      • Tutorials & Help
      Tags
      3D Printing Arduino audio battery berryclip Birthday bluetooth cambridge camera CamJam DigiMakers display games GPIO I2C interface Kickstarter LCD LED Linux media Minecraft Model A Model B motionEyeOS PCB photography photos Pi-Lite portable power python Raspberry Jam Raspberry Pi Bootcamp raspbian Retrogaming retroPie screen SD card security sensor SPI temperature ultrasonic video
      Raspberry PI Related
      • Adafruit Blog
      • Average Maker
      • Official RaspBerry Pi Site
      • Raspberry Pi Pod
      • RasPi.tv
      • RaspTut
      • Stuff About Code
      Tech Resources
      • MattsBits – Pi Resources
      • Microbit Spy
      • Technology Spy
      Archives
      About

      Unofficial site devoted to the Raspberry Pi credit card sized computer offering tutorials, guides, resources,scripts and downloads. We hope to help everyone get the most out of their Pi by providing clear, simple articles on configuring, programming and operating it.

      Popular Posts
      September 19, 2014

      Top 5 Reasons The Raspberry Pi Sucks

      July 27, 2012

      16×2 LCD Module Control Using Python

      October 20, 2013

      Analogue Sensors On The Raspberry Pi Using An MCP3008

      Recent Posts
      June 30, 2022

      Pi Pico W Launched

      May 6, 2022

      Add Kodi to RetroPie Menu

      February 26, 2022

      Disable Auto-login in Raspberry Pi OS

      Facebook Twitter Instagram Pinterest YouTube RSS

      Entries RSS | Comments RSS

      This site is not associated with the official Raspberrypi.org site or the Raspberry Pi Foundation. Raspberry Pi is a trademark of the Raspberry Pi Foundation.

      Copyright © 2022 - All Rights Reserved - Matt Hawkins

      Type above and press Enter to search. Press Esc to cancel.