Raspberry Pi Temperature Sensor using the DS18B20

In this tutorial, we will show you how you can easily set your Raspberry Pi up to read the temperature from the DS18B20 sensor.

Raspberry Pi Temperature Sensor

Like most of our sensor tutorials, the temperature sensor we are using with our Raspberry Pi will be relatively simple to use.

In this guide, we will use a DS18B20 waterproof sensor, which can provide temperature readings over a one-wire interface. Even better, it is waterproof, making it perfect for use in a wet environment.

Thanks to the DS18B20 sensor, getting temperature readings on your Raspberry Pi is pretty straightforward. Connecting the sensor requires a few simple connections, and reading the live data is easy.

There are many other temperature sensors you can use with your Raspberry Pi, but in this tutorial, we will focus on the DS18B20.

You will find the DS18B20 temperature sensor handy in many situations, especially for monitoring surface and liquid temperatures.

Equipment

The equipment that you will need for this Raspberry Pi temperature sensor is listed below.

Keep in mind the breadboard, and the breadboard wire is optional, but I highly recommend investing in these, as they may make working with circuitry a lot easier.

Optional

Video

If you want to see how to put together the circuit and a rundown of the code, then be sure to check out my video below.

I go through everything there is to know about this cool little circuit in the video. You can also find the full written tutorial right under the video.

Building the Raspberry Pi DS18B20 Circuit

The circuit that we will need to build is pretty straightforward as we only need a resistor and the temperature sensor.

The sensor I am using in this tutorial is a waterproof version of the DS18B20. It simply looks like a very long cord with a thick part on one end. If you have a plain version without wiring or waterproofing, it looks exactly like a transistor.

This sensor is pretty accurate, being within 0.05°C of the actual temperature. It can handle temperatures of up to 125°C (260°F), but it’s recommended you keep it below 100°C (210°F). This device also has an onboard analog-to-digital converter, so we’re able to easily hook it up to a digital GPIO pin on the Pi.

Keep in mind that not all temperature sensors are the same. Something like the TMP36 will not simply replace the DS18B20 in this tutorial.

The TMP36 is an analogue device, making it slightly harder to integrate with the Pi. The TMP36 has the same problem we had with the light sensor, because the Raspberry Pi doesn’t have any analogue pins.

Putting this circuit together is super simple. I will quickly go through some basic instructions below. If you’re having trouble following them, then please refer to the video or diagram.

If you need more information on the GPIO pins, then be sure to check out my guide to getting started with the Raspberry Pi GPIO pins.

1. First, connect the 3v3 pin from the Pi to the positive rail and a ground pin to the ground rail on the breadboard.

2. Now place the DS18B20 sensor onto the breadboard.

3. Place a 4.7k resistor between the positive lead and the output lead of the sensor.

4. Place a wire from the positive lead to the positive 3v3 rail.

5. Place a wire from the output lead back to pin #4 (Pin #7 if using physical numbering) of the Raspberry Pi.

6. Place a wire from the ground lead to the ground rail.

Once done, your circuit should look similar to the diagram below.  Keep in mind some versions of the temperature sensor may have more wires than just three. Refer to the datasheet for more information for each of the wires.

Raspberry Pi Temperature Sensor Diagram

The Raspberry Pi Temperature Sensor Code

The code for setting up the temperature sensor is a little more complicated than the circuit itself. This complexity is just because of how we need to handle the data from the sensor on our Raspberry Pi.

Since we are using Python, it will be worth learning some basics of the language. If you are interested in learning, we recommend checking out our Python beginners’ guide.

Over this next section, you will be learning how to enable OneWire support that is required to talk with the DS18B20 sensor, as well as how to use Python to talk with the sensor.

Enabling OneWire Support on your Raspberry Pi

1. Before we can begin writing our Python script so our Raspberry Pi can read data from the temperature sensor, we must enable OneWire support.

To add support for OneWire, we first need to open the boot config file and make some changes. You can open this file by running the following command. I like to use the nano text editor.

sudo nano /boot/firmware/config.txtCopy

2. Now, to the bottom of this file, you will want to add the following line.

This line enables the OneWire support on your Raspberry Pi and is what will enable it to read in data from the temperature sensor you wired in earlier.

By default, OneWire support on the Pi will utilize GPIO pin 4.

dtoverlay=w1-gpioCopy

3. After making this change, you can save and quit by pressing CTRL + X and then Y.

4. Despite making this change, OneWire support isn’t yet enabled. For this change to take effect, we must restart our Raspberry Pi.

Restarting your Pi from within the terminal is as simple as using the command below.

sudo rebootCopy

Verifying OneWire is Enabled

5. Once your Raspberry Pi finishes restarting, we can verify that it can see the attached temperature sensor. To achieve this, we will utilize the ls command to list out the contents of the “/sys/bus/w1/devices” directory.

Each directory listed by this command is a device connected to the OneWire interface on your Pi.

ls /sys/bus/w1/devicesCopy

7. For example, after running the command above, we saw a directory named “28-000007602ffa“. To get an idea of the sort of data that is coming in from the sensor, let us start by changing into that directory.

The ending folder name is likely different for you, so be sure to swap this out with the folder you retrieved from the previous command. If you have multiple sensors, you would likely see multiple folders.

cd /sys/bus/w1/devices/28-000007602ffaCopy

8. Once you are in the directory, you can utilize the cat command to get your Raspberry Pi to read data from your temperature sensor.

cat w1_slaveCopy

9. This command should output data but as you will notice it is not very user-friendly.

The first line should have a YES or NO at the end of it. If it is YES, then a second line with the temperature should appear. This line will look similar to something like t=12323, and you will need to do a bit of math to make this a usable temperature that we can understand easily. For example, Celsius you simply divide by 1000.

temperature output

Writing Python to Talk with your Temperature Sensor using your Raspberry Pi

10. Now that we are certain everything is working and that your Raspberry Pi can communicate with your temperature sensor, we can move on to writing some Python that will make use of this data.

Before we begin writing this code, start by ensuring you are in your home directory by using the cd command followed by the tilde symbol.

cd ~Copy

11. With us now in the right place, we will use the Nano text editor to begin writing a new Python script. We will be calling this script “temperature_sensor.py“.

The code we are using within this script was sourced from the tutorial over at Adafruit. We will briefly explain each part of the code so you get a rough idea of what is going on. If you don’t want the explanation, just skip to step 12.

nano temperature_sensor.pyCopy

a. To begin the Python script, we import three packages: OS, Glob, and time.

Next, we run the modprobe commands to ensure that OneWire is enabled and that our Pi can communicate with the temperature sensor.

After this, we declare three different variables that will point to the location of our sensor data. You shouldn’t have to change any of these.

import os
import glob
import time
 
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
 
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'Copy

b. We then declare a new Python function called “read_temp_raw“. This function is simple and is here to read the raw data the sensor is returning.

Once the data has been read in, we return it so that we can process it into actual usable temperature data.

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return linesCopy

c. Up next, we define a new function called “read_temp” that we will use to process the data from the “read_temp_raw ” function.

We first make sure that the first line contains YES. This means there will be a line with a temperature in it.

If there is a temperature, we then find the line starting with “t=” by using “lines[1].find('t=')“. “lines[1]” means we’re looking at the 2nd element in the array, in this case, the 2nd line.

Once we have the line, we get all the numbers that are after the “t=” and this is done at “lines[1][equals_pos+2:]“. “equals_pos “is the start position of the temperature (t), and we add 2 to the position, so we only get the actual temperature numbers.

We then convert the number into both Celsius and Fahrenheit temperatures. We return both of these to the code that called this function. This function is the print located in the while loop.

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_fCopy

d. The while loop we are placing at the end of our script is always “true” so it will run forever until the program is interrupted by an error or by the user cancelling the script.

This while loop simply calls the “read_temp()” function and prints the result to the command line. The script is then put to sleep for 1 second every time it has read the sensor.

while True:
	print(read_temp())	
	time.sleep(1)Copy

12. If you have entered all of the Python correctly, the code should end up looking like what we have shown below.

This bit of Python is super simple and is what will enable your Raspberry Pi to read in the temperature data from your DS18B20 sensor. The temperature data will be printed to the terminal every second.

import os
import glob
import time
 
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
 
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
 
def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines
 
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f
	
while True:
	print(read_temp())	
	time.sleep(1)Copy

13. If you are certain you have filled out this file correctly, you can save and quit by pressing CTRL + X, Y, and then ENTER.

Testing your New Raspberry Pi Temperature Sensor

14. Once you have finished writing out the code and have verified that the circuit has all been wired correctly, we can now run the Python script.

To call the Python script from within the terminal, all you need to do is use the command below.

sudo python temperature_sensor.pyCopy

15. You should now have an output of temperatures in both Fahrenheit and Celsius. You can alter this just to display your preferred temperature scale if you like.

Temperature Sensor Readings

That’s everything you need to know for getting the DS18B20 temperature sensor working with your Raspberry Pi.

If you’re looking to extend this one step further, then be sure to check out my tips below. I will be looking at incorporating this sensor into future projects, so stay tuned.

Possible Further Work

There are quite a few more things you’re able to do with this Raspberry Pi temperature sensor. I will quickly mention a couple of ideas, and some of them I may cover in the future.

You can have the Python script connect to a database such as MYSQL and store the data that way. If you add a timestamp to the data, you will be able to look back on data in the future and compare any changes.

This next tip would work great with the one above. You can use data stored in the MySQL database to make pretty graphs showing temperature over the course of a day, month, or even a year. You could make it plot a graph in real time, too.

Alternatively, using influxDB along with Grafana is a great way of visually displaying your temperature statistics.

Conclusion

I hope you have been able to build and get this Raspberry Pi temperature sensor working.

If you have reached this point in the tutorial, we hope you have successfully set up your Raspberry Pi to work as a temperature sensor.

The DS18B20 sensor we used in this guide works perfectly with the Pi, and reading its temperature data is a simple process.

If you have encountered any problems, have feedback, or anything else, please feel free to leave a comment below.

To explore what else you can do with your device, be sure to check out some of our many Raspberry Pi projects.

Need faster help? Premium members get priority responses to their comments.

Upgrade for Priority Support

Leave a Reply

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

38 Comments

  1. Avatar for Simon Bingham
    Simon Bingham on

    Good pages, I’m here because I’m looking to replace a legacy central heating controller with Rasberry PI. The thermal sensor that are in my system
    “DS1820” models. I wonder if this code will work for them ?
    Only one way to find out I guess.

  2. Avatar for Lars Lindehaven
    Lars Lindehaven on

    A great tutorial! I used it to get started with my own temperature project on a Raspberry Pi Zero W with Maria DB and Apache web server. See https://github.com/lindehaven/Raspberry

  3. Avatar for zeddi
    zeddi on

    how do you convert those temperature readings into a graphical format ?

  4. Avatar for Co Crocker
    Co Crocker on

    I would like to limit the output in both “C” and “F” to one decimal place. ie. 96.8.
    Can anyone help?

  5. Avatar for Edmilton (Ed) Silva
    Edmilton (Ed) Silva on

    Hi,
    That’s an outstanding tutorial! I am astonished with the simplicity you´ve gone over all stuff in an understandable way. Congratulations!

  6. Avatar for Darren Tiu
    Darren Tiu on

    Hi,
    Mine can’t seem to work the message keeps telling “modprobe: FATAL: Module w1-gpio not found” what should I do ?

  7. Avatar for Peter
    Peter on

    Thanks for posting this, great tips and tutorials

  8. Avatar for Adithya Nayabu
    Adithya Nayabu on

    I have followed the instructions, but my sensor turn too hot as soon as my circuit is turned on. Any help ?

    1. Avatar for Gus
      Gus on
      Editor

      Hi Adithya,

      Check the connections to the sensor and make sure the positive and ground leads are connected correctly.

    2. Avatar for Silverfox52z
      Silverfox52z on

      Check your wiring. If you get the wiring incorrect, the 18B20 will turn into a heating element. Reference the DS18B20 Data Sheet for the correct pin out. Be sure to take note that the 3 Pin TO-92 package is shown in the data sheet looking from the bottom.

  9. Avatar for KC
    KC on

    I got it – rocky mistake – I have used a 470K resistance instead 4.7K!!!!

  10. Avatar for KC
    KC on

    Using raspberry pi Zero with the latest software. Everything is working fine.

    I don’t see w1-slave file. the folders start with 00-… and it changes names almost every time I type ls 00*

    1. Avatar for Nils
      Nils on

      had the same problem, make sure the resistor is wired correctly

  11. Avatar for Dave Rose
    Dave Rose on

    Hi, this was a great tutorial among many I have trawled through to get the 18B20 working on the Pi. There was just one major problem. According to your circuit drawing, you have the + and – the wrong way round on the sensor, contrary to all the other tutorials for this sensor. Like this it does not work and gets too hot to touch. Rewired the correct way round it works fine now.

    I have been trying to find other programs to better use/translate the data from the sensor, like getting it to display on the 16 * 2 display. So far without success.

    Cheers.

    1. Avatar for Gus
      Gus on
      Editor

      Thanks for that Dave! I have fixed the circuit diagram, the software I use tells me the “correct” way is the “wrong” way and I trusted it since I used a pre-wired (Red, white,black) version in my tutorial. :/ All good now tho!

  12. Avatar for Ivaylo
    Ivaylo on

    Hello ,

    here is the code modification if you want to connect your temperature value to a database (you need to install library MySQLdb):

    import os
    import glob
    import time
    import MySQLdb
     
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
     
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[0]
    device_file = device_folder + '/w1_slave'
     
    conn = MySQLdb.connect(host="localhost", user="root", passwd="", db="nolinka")
    
    cursor = conn.cursor()
     
    def read_temp_raw():
        f = open(device_file, 'r')
        lines = f.readlines()
        f.close()
        return lines
     
    def read_temp():
        lines = read_temp_raw()
        while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = read_temp_raw()
        equals_pos = lines[1].find('t=')
        if equals_pos != -1:
            temp_string = lines[1][equals_pos+2:]
            temp_c = float(temp_string) / 1000.0
            temp_f = temp_c * 9.0 / 5.0 + 32.0
            return temp_c
    	
    while True:
    	print(read_temp())
    	mytemp = read_temp()
    	loggit = "UPDATE temperature SET Value=%s WHERE ID=1"
    	cursor.execute(loggit, (mytemp))
    	conn.commit()
    	
    	time.sleep(5)
    1. Avatar for Gus
      Gus on
      Editor

      Awesome work Ivaylo! Thanks for sharing 🙂

    2. Avatar for Edmilton (Ed) Silva
      Edmilton (Ed) Silva on

      Awsome code sharing, Ivaylo! It helped a lot on my project.
      Thanks for your great contribution!

  13. Avatar for vince
    vince on

    import os
    imprt glob
    import time
    do you run these commands?

    1. Avatar for Gus
      Gus on
      Editor

      These commands are in the script, you will need them in order for the script to run correctly.

  14. Avatar for Jerry
    Jerry on

    It works great on my raspberry pi 3 B. I’m new to the pi and to programming in python (only a Fortran class in college 40 years ago). I want to measure two temperatures, compare them, and energize a relay when the temperature differential is more than or less than desired amounts. Can you demonstrate how to add a second temperature sensor?

    1. Avatar for Gus
      Gus on
      Editor

      Hi Jerry,

      To add a 2nd sensor you should be able to wire it up almost exactly the same as the first sensor. Since it uses a one-wire interface just hook it up to the same input pin as the first sensor (pin#4 or pin #7 if using physical numbering).

      It should then appear in the steps from step 5 on wards.

      I haven’t been able to test this as I only have 1 sensor at the moment.

    2. Avatar for Mark
      Mark on

      I was able to get python to read two probes, wired in tandem with the following Python script:

      import os
      import glob
      import time
      
      os.system('modprobe w1-gpio')
      os.system('modprobe w1-therm')
      
      base_dir = '/sys/bus/w1/devices/'
      device_folder_0 = glob.glob(base_dir + '28-0120627ab4fa')[0]
      device_file_0 = device_folder_0 + '/w1_slave'
      
      def read_temp_raw_0():
          f = open(device_file_0, 'r')
          lines = f.readlines()
          f.close()
          return lines
      
      def read_temp_0():
          lines = read_temp_raw_0()
          while lines[0].strip()[-3:] != 'YES':
              time.sleep(0.2)
              lines = read_temp_raw_0()
          equals_pos = lines[1].find('t=')
          if equals_pos != -1:
              temp_string = lines[1][equals_pos+2:]
              temp_c = float(temp_string) / 1000.0
              temp_f = temp_c * 9.0 / 5.0 + 32.0
              return temp_f
      
      
      base_dir = '/sys/bus/w1/devices/'
      device_folder_1 = glob.glob(base_dir + '28-0120627ed3dc')[0]
      device_file_1 = device_folder_1 + '/w1_slave'
      
      def read_temp_raw_1():
          f = open(device_file_1, 'r')
          lines = f.readlines()
          f.close()
          return lines
      
      def read_temp_1():
          lines = read_temp_raw_1()
          while lines[0].strip()[-3:] != 'YES':
              time.sleep(0.2)
              lines = read_temp_raw_()
          equals_pos = lines[1].find('t=')
          if equals_pos != -1:
              temp_string = lines[1][equals_pos+2:]
              temp_c = float(temp_string) / 1000.0
              temp_f = temp_c * 9.0 / 5.0 + 32.0
              return temp_f
      
      while True:
              print(read_temp_0(),read_temp_1())
              time.sleep(1)
  15. Avatar for Big Bear
    Big Bear on

    This is a very helpful page thanks, the only thing is i am new to python and your code in line 12 gives me the error can you help me out here please
    line 12
    device_folder = glob.glob(base_dir + ’28*’)[0]
    IndexError: list index out of range

    1. Avatar for Gus
      Gus on
      Editor

      Hi Big Bear,

      This typically happens when there is no device folder. Can you confirm that a folder with a name similar to 28-000007602ffa is displaying when you run the following commands.

      cd /sys/bus/w1/devices
      ls

      If it isn’t then it’s likely the temperature sensor hasn’t been connected to the Pi correctly.

  16. Avatar for Pablo Rodriguez
    Pablo Rodriguez on

    Couldn’t get it to work on Pi 3B, so far I see that I don’t have the w1-therm module, only the w1-gpio… any ideas?

    1. Avatar for Gus
      Gus on
      Editor

      Hi Pablo,

      I will set this up on my Pi 3 and see if I get the same results.

  17. Avatar for Tshala
    Tshala on

    A brilliant tutorial. I followed it step-by-step and I got my Temperature Sensor working as expected.

    Thank you for sharing!

  18. Avatar for Cal
    Cal on

    Does not work on Pi 2 Model B. Even tried a second sensor

    Instructions very clear but when I finish step 6 the sensor does not show up, only w1_bus_master1

    Any ideas?

    1. Avatar for Tshala
      Tshala on

      Cal,
      I am using Raspberry Pi 2 model B and it works nicely.
      The only thing which comes to my mind that can cause you troubles is the connection/wiring.
      Please double check the connection/wiring and try using a different GPIO pin to see if it helps.

      Best luck!

    2. Avatar for Mikkel Holm Olsen
      Mikkel Holm Olsen on

      I have been struggling with this problem for a couple of weeks. This morning I succeeded getting it to work by using a level converter and powering the DS18B20 from 5V. This is the level converter I used: https://www.sparkfun.com/products/12009

      I bought the sensors off of Aliexpress, and I wonder if they are genuine. Maybe that is the reason they do not work reliably at 3.3V? Sensor was soldered directly to a header, so connection should be good and no wire length to cause problems.

  19. Avatar for Jim Knopick
    Jim Knopick on

    Could you show how to read 2 sensors and display the output as I would like to use the result with biofeedback.
    Thanks.

  20. Avatar for Joop Terwijn
    Joop Terwijn on

    I just starting to play with a pi, I must say nice content! I use an iPad to watch YouTube content. You mention the possibility to leave comments, well I can’t (using the iPad) the option is not showing with your content.
    I follow several channels and on other channels I can (and do) comment, so I suspect there is a mark missing while uploading 🙂