{"id":133368,"date":"2023-10-19T14:20:48","date_gmt":"2023-10-19T14:20:48","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=133368"},"modified":"2023-10-19T14:54:52","modified_gmt":"2023-10-19T14:54:52","slug":"raspberry-pi-ds18b20-python","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-ds18b20-python\/","title":{"rendered":"Raspberry Pi: Temperature Readings with DS18B20 Sensor (Python)"},"content":{"rendered":"\n<p>Learn how to interface the Raspberry Pi with the DS18B20 temperature sensor and how to get temperature readings using a Python program.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/Raspberry-Pi-DS18B20-temperatue-sensor-Guide.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Temperature Readings with DS18B20 Sensor Python\" class=\"wp-image-133423\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/Raspberry-Pi-DS18B20-temperatue-sensor-Guide.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/Raspberry-Pi-DS18B20-temperatue-sensor-Guide.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/Raspberry-Pi-DS18B20-temperatue-sensor-Guide.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/Raspberry-Pi-DS18B20-temperatue-sensor-Guide.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\"><strong>Table of Contents<\/strong><\/h2>\n\n\n\n<p>Throughout this tutorial, we\u2019ll cover the following main topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#ds18b20-intro\" title=\"\">Introducing the DS18B20 Temperature Sensor<\/a><\/li>\n\n\n\n<li><a href=\"#ds18b20-rpi-wiring\" title=\"\">Wiring the DS18B20 Temperature Sensor to the Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"#enable-one-wire\" title=\"\">Enabling One-Wire on the Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"#testing-ds18b20\" title=\"\">Testing the Temperature Sensor<\/a><\/li>\n\n\n\n<li><a href=\"#rpi-ds18b20-python-script\" title=\"\">Getting Sensor Readings from the DS18B20 &#8211; Python Script<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before continuing with this tutorial, check the following prerequisites.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Get familiar with the Raspberry Pi board\u2014if you\u2019re not familiar with the Raspberry Pi, you can read our&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\"><strong>Raspberry Pi Getting Started Guide here<\/strong>.<\/a><\/li>\n\n\n\n<li>You must know how to run and create Python files on your Raspberry Pi. We like to program our Raspberry Pi via SSH using an extension in VS Code. We have a detailed tutorial about that subject:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\"><strong>Programming Raspberry Pi Remotely using VS Code (Remote-SSH)<\/strong><\/a>.<\/li>\n\n\n\n<li>Know how to use the Raspberry Pi GPIOs so that you know how to wire the circuit properly. Read the following tutorial:&nbsp;<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\"><strong>Raspberry Pi Pinout Guide: How to use the Raspberry Pi GPIOs?<\/strong><\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ds18b20-intro\">Introducing DS18B20 Temperature Sensor<\/h2>\n\n\n\n<p>The <a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/ds18b20-temperature-sensor-2\/\" target=\"_blank\">DS18B20 temperature sensor<\/a> is a one-wire digital temperature sensor. This means that it just requires one data line (and GND) to communicate with your ESP32.<\/p>\n\n\n\n<p>It can be powered by an external power supply or it can derive power from the data line (called &#8220;parasite mode&#8221;), which eliminates the need for an external power supply.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"490\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/DS18B20-tempeature-sensor-pinout.jpg?resize=750%2C490&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DS18B20 Temperature Sensor Pinout Pins\" class=\"wp-image-86735\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/DS18B20-tempeature-sensor-pinout.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/DS18B20-tempeature-sensor-pinout.jpg?resize=300%2C196&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Each DS18B20 temperature sensor has a unique 64-bit serial code. This allows you to wire multiple sensors to the same data wire. So, you can get temperature from multiple sensors using just one GPIO.<\/p>\n\n\n\n<p>The DS18B20 temperature sensor is also available in <a href=\"https:\/\/makeradvisor.com\/tools\/ds18b20-digital-temperature-sensor\/\" target=\"_blank\" rel=\"noopener\" title=\"\">waterproof version<\/a>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/ds18b20-waterproof.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DS18B20 Temperature Sensor Waterproof version\" class=\"wp-image-86674\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/ds18b20-waterproof.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/ds18b20-waterproof.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Here&#8217;s a summary of the most relevant specs of the DS18B20 temperature sensor:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Communicates over one-wire bus communication<\/li>\n\n\n\n<li>Power supply range: 3.0V to 5.5V<\/li>\n\n\n\n<li>Operating temperature range: -55\u00baC to +125\u00baC<\/li>\n\n\n\n<li>Accuracy +\/-0.5 \u00baC (between the range -10\u00baC to 85\u00baC)<\/li>\n<\/ul>\n\n\n\n<p>For more information consult the <a aria-label=\" (opens in a new tab)\" href=\"https:\/\/datasheets.maximintegrated.com\/en\/ds\/DS18B20.pdf\" target=\"_blank\" rel=\"noreferrer noopener\">DS18B20 datasheet<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Parts Required<\/h2>\n\n\n\n<p>To follow this tutorial you need the following parts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noreferrer noopener\">Raspberry Pi Board<\/a>&nbsp;\u2013 read&nbsp;<a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-starter-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">Best Raspberry Pi Starter Kits<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/ds18b20-temperature-sensor-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">DS18B20 temperature sensor<\/a> \u2013&nbsp;<a aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/ds18b20-digital-temperature-sensor\/\" target=\"_blank\" rel=\"noreferrer noopener\">waterproof version<\/a><\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" aria-label=\"4.7k Ohm resistor\u2028 (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\">4.7k Ohm resistor<\/a><\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" aria-label=\"Jumper wires (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\">Jumper wires<\/a><\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" aria-label=\"Breadboard (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\">Breadboard<\/a><\/li>\n<\/ul>\n\n\n<p>You can use the preceding links or go directly to <a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\">MakerAdvisor.com\/tools<\/a> to find all the parts for your projects at the best price!<\/p><p style=\"text-align:center;\"><a href=\"https:\/\/makeradvisor.com\/tools\/?utm_source=rnt&utm_medium=post&utm_campaign=post\" target=\"_blank\"><img data-recalc-dims=\"1\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2017\/10\/header-200.png?w=1200&#038;quality=100&#038;strip=all&#038;ssl=1\"><\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"ds18b20-rpi-wiring\">Wiring a DS18B20 Temperature Sensor to the Raspberry Pi<\/h2>\n\n\n\n<p>The DS18B20 temperature sensor comes with three pins: GND, data, and VCC. The DS18B20 temperature sensor can be powered through the VDD pin (<strong>normal mode<\/strong>), or it can derive its power from the data line (<strong>parasite mode<\/strong>). You can choose either mode. We prefer using the normal mode.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter is-resized\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"490\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/DS18B20-tempeature-sensor-pinout.jpg?resize=750%2C490&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DS18B20 Temperature Sensor Pinout Pins\" class=\"wp-image-86735\" style=\"width:747px;height:488px\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/DS18B20-tempeature-sensor-pinout.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/07\/DS18B20-tempeature-sensor-pinout.jpg?resize=300%2C196&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>If you&#8217;re using the waterproof version, you can identify each pin by its color:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>black: GND<\/li>\n\n\n\n<li>red: VDD<\/li>\n\n\n\n<li>yellow: data line<\/li>\n<\/ul>\n\n\n\n<p>The DS18B20 temperature sensor communicates using one-wire communication protocol. The Raspberry Pi supports one-wire on any GPIO pin, <strong>but the default is GPIO 4<\/strong>. So, we&#8217;ll wire the data pin of the sensor to GPIO 4. If you need to use another GPIO, see one of the following sections to learn how to <a href=\"#enable-one-wire-not-default\" title=\"\">enable the one-wire bus on a different pin<\/a>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/raspberry-pi-ds18b20-wiring_bb.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1090\" height=\"946\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/raspberry-pi-ds18b20-wiring_bb.png?resize=1090%2C946&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi with DS18B20 Temperature Sensor Wiring\" class=\"wp-image-133420\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/raspberry-pi-ds18b20-wiring_bb.png?w=1090&amp;quality=100&amp;strip=all&amp;ssl=1 1090w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/raspberry-pi-ds18b20-wiring_bb.png?resize=300%2C260&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/raspberry-pi-ds18b20-wiring_bb.png?resize=1024%2C889&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/raspberry-pi-ds18b20-wiring_bb.png?resize=768%2C667&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1090px) 100vw, 1090px\" \/><\/a><\/figure><\/div>\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>DS18B20<\/strong><\/td><td><strong>Raspberry Pi Pico<\/strong><\/td><\/tr><tr><td>GND<\/td><td>GND<\/td><\/tr><tr><td>Data (DQ)<\/td><td>Default one-wire pin ins GPIO 4 <br>you also need to connect a 4.7KOhm resistor between the data line and VCC<\/td><\/tr><tr><td>VDD<\/td><td>3V3(OUT)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"enable-one-wire\">Enable One-Wire Communication on the Raspberry Pi<\/h2>\n\n\n\n<p>To enable the one-wire interface, open a Terminal window on your Raspberry Pi (for example, via SSH), type the following command and press Enter.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sudo raspi-config<\/pre>\n\n\n\n<p>The following menu will open. Select<strong> Interface Options<\/strong>:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"661\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/rpi-interface-options.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Enable One-Wire Communication on the Raspberry Pi\" class=\"wp-image-133380\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/rpi-interface-options.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/rpi-interface-options.png?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><\/figure><\/div>\n\n\n<p>Select <strong>1-wire<\/strong>.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"661\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/1-wire-rpi-configuration-tool.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Enable Wire one-wire interface\" class=\"wp-image-133381\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/1-wire-rpi-configuration-tool.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/1-wire-rpi-configuration-tool.png?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><\/figure><\/div>\n\n\n<p>And enable it.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"661\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/enable-1-wire-configuration-tool-rpi.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"one-wire interface enabled\" class=\"wp-image-133382\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/enable-1-wire-configuration-tool-rpi.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/enable-1-wire-configuration-tool-rpi.png?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><\/figure><\/div>\n\n\n<p>Finally, select <strong>Finish<\/strong>, and then reboot the Raspberry Pi.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"661\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/reboot-rpi-configuration-tools.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"one wire is enabled on Raspberry Pi\" class=\"wp-image-133383\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/reboot-rpi-configuration-tools.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/reboot-rpi-configuration-tools.png?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"enable-one-wire-not-default\">Enabling one-wire on a different GPIO (not default)<\/h3>\n\n\n\n<p>The default one-wire GPIO for the Raspberry Pi is GPIO 4. If you want to enable the one-wire bus on a different pin, you need to run the following commands.<\/p>\n\n\n\n<p>Open and edit the <em>config.txt<\/em> file using:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sudo nano \/boot\/config.txt<\/pre>\n\n\n\n<p>Add the following line at the end of the file, in which x is the GPIO you want to use for one-wire:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">dtoverlay=w1-gpio,gpiopin=<strong>x<\/strong><\/pre>\n\n\n\n<p>For example, if you want to enable one-wire on GPIO22, it would be as follows:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">dtoverlay=w1-gpio,gpiopin=22<\/pre>\n\n\n\n<p>Press <strong>CTRL-X<\/strong>, then press <strong>Y<\/strong> and <strong>Enter <\/strong>to save the changes.<\/p>\n\n\n\n<p>Reboot your Raspberry Pi with:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sudo reboot<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"testing-ds18b20\">Testing the DS18B20 Temperature Sensor<\/h2>\n\n\n\n<p>With the sensor wired to your Raspberry Pi, let&#8217;s just test that it can find the sensor and report the readings before writing the Python code.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ds18b20-sensor.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ds18b20 temperature sensor with raspberry pi\" class=\"wp-image-133424\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ds18b20-sensor.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ds18b20-sensor.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>Run the following commands on a terminal window:<\/p>\n\n\n\n<p>This command loads the <span class=\"rnthl rntliteral\">w1-gpio<\/span> kernel module, which is responsible for enabling the GPIO pin for one-wire communication:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sudo modprobe w1-gpio<\/pre>\n\n\n\n<p>Then, the following line loads the <span class=\"rnthl rntliteral\">w1-therm<\/span> kernel module, which adds support for DS18B20-specific features, such as reading temperature data from the sensor.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">sudo modprobe w1-therm<\/pre>\n\n\n\n<p>Then, change the current working directory to <span class=\"rnthl rntliteral\">\/sys\/bus\/w1\/devices\/<\/span>. In this directory, it exposes information about connected one-wire devices, including the DS18B20 sensor (if it can find the sensor).<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">cd \/sys\/bus\/w1\/devices\/<\/pre>\n\n\n\n<p>Finally, list the contents of the <em>devices <\/em>folder that should show one or more directories, each representing a one-wire device.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">ls<\/pre>\n\n\n\n<p>In the case of the DS18B20 temperature sensor, you&#8217;ll see a folder like <span class=\"rnthl rntliteral\">28-xxxxxxxxxxxx<\/span>, where <span class=\"rnthl rntliteral\">xxxxxxxxxxxx<\/span> is the unique address of your DS18B20 sensor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"661\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/searching-devices-terminal-rpi.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"discover one-wire for ds18b20\" class=\"wp-image-133384\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/searching-devices-terminal-rpi.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/searching-devices-terminal-rpi.png?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><\/figure><\/div>\n\n\n<p>Navigate to the directory representing the DS18B20 sensor. For example, in my case it&#8217;s as follows (use the directory of your sensor):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">cd <em><strong>28-03173311a0ff<\/strong><\/em><\/pre>\n\n\n\n<p>After navigating to the directory representing the DS18B20 sensor, you can use the <span class=\"rnthl rntliteral\">cat<\/span> command to read the contents of the <span class=\"rnthl rntliteral\">w1_slave<\/span> file. This file contains the raw temperature data in a specific format.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">cat w1_slave<\/pre>\n\n\n\n<p>The contents of the <span class=\"rnthl rntliteral\">w1_slave<\/span> file will look something as shown in the next screenshot (first line contains the status of the reading: <span class=\"rnthl rntliteral\">YES<\/span> means a valid reading, and the second line shows the temperature (you need to divide by 1000 to get it in degrees Celsius).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"661\" height=\"418\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/check-temperature-sensor-terminal-ds18b20-rpi.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"find one wire slave\" class=\"wp-image-133386\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/check-temperature-sensor-terminal-ds18b20-rpi.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/check-temperature-sensor-terminal-ds18b20-rpi.png?resize=300%2C190&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 661px) 100vw, 661px\" \/><\/figure><\/div>\n\n\n<p>If everything went smoothly until now, you are ready to write the Python program to get the readings.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"rpi-ds18b20-python-script\">Raspberry Pi with DS18B20 &#8211; Getting Temperature Readings (Python Script)<\/h2>\n\n\n\n<p>The following script prints temperature readings in the shell from the DS18B20 temperature sensor. The readings are printed both in Celsius and Fahrenheit degrees. <\/p>\n\n\n\n<p>Create a new Python file called&nbsp;<em>temp-ds18b20.py<\/em>&nbsp;and copy the following code.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-ds18b20-python\/\n\n# Based on the Adafruit example: https:\/\/github.com\/adafruit\/Adafruit_Learning_System_Guides\/blob\/main\/Raspberry_Pi_DS18B20_Temperature_Sensing\/code.py\n\nimport os\nimport glob\nimport time\n \nos.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')\n \nbase_dir = '\/sys\/bus\/w1\/devices\/'\ndevice_folder = glob.glob(base_dir + '28*')[0]\ndevice_file = device_folder + '\/w1_slave'\n\ndef read_temp_raw():\n    f = open(device_file, 'r')\n    lines = f.readlines()\n    f.close()\n    return lines\n\ndef read_temp():\n    lines = read_temp_raw()\n    while lines[0].strip()[-3:] != 'YES':\n        time.sleep(0.2)\n        lines = read_temp_raw()\n    equals_pos = lines[1].find('t=')\n    if equals_pos != -1:\n        temp_string = lines[1][equals_pos+2:]\n        temp_c = float(temp_string) \/ 1000.0\n        temp_f = temp_c * 9.0 \/ 5.0 + 32.0\n        return temp_c, temp_f\nwhile True:\n\tprint(read_temp())\t\n\ttime.sleep(1)\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/Raspberry-Pi\/ds18b20_basic.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>In this code, we&#8217;ll basically reproduce the previous steps on the Python script to get the readings, and we&#8217;ll display them on the Python shell.<\/p>\n\n\n\n<p>Start by importing the required libraries:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import os\nimport glob\nimport time<\/code><\/pre>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">os<\/span> library allows you to interact with the operating system, and in this code, it&#8217;s used to execute system commands (<span class=\"rnthl rntliteral\">os.system<\/span>) to load the required kernel modules for 1one-wire communication with the DS18B20 sensor (similar to what we did on the Terminal before).<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">glob<\/span> library helps find files or directories that match a specific pattern, and it&#8217;s used here to locate the directory representing the DS18B20 sensor based on its unique address prefix.<\/p>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">time<\/span> library is used to introduce delays in the code to give enough time for the sensor to get valid readings.<\/p>\n\n\n\n<p>Next, load the following kernel modules (<span class=\"rnthl rntliteral\">w1-gpio<\/span> and <span class=\"rnthl rntliteral\">w1-therm<\/span>) to interface with the DS18B20 sensor via one-wire communication protocol. These commands use the <span class=\"rnthl rntliteral\">os.system<\/span> function to execute shell commands within Python<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>os.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')<\/code><\/pre>\n\n\n\n<p>The following lines set up paths and filenames for reading the temperature data:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>base_dir = '\/sys\/bus\/w1\/devices\/'\ndevice_folder = glob.glob(base_dir + '28*')&#091;0]\ndevice_file = device_folder + '\/w1_slave'<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">base_dir<\/span> represents the directory where the one-wire devices are located under the <span class=\"rnthl rntliteral\">\/sys<\/span> filesystem.<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">device_folder<\/span> is obtained using the <span class=\"rnthl rntliteral\">glob.glob<\/span> function, which searches for directories matching the pattern &#8217;28*&#8217;. The DS18B20 sensors typically have a unique address starting with <span class=\"rnthl rntliteral\">28<\/span>. This ensures that the code finds the correct folder representing the DS18B20 sensor connected to the Raspberry Pi.<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">device_file<\/span> represents the path to the <span class=\"rnthl rntliteral\">w1_slave<\/span> file that contains the raw temperature data.<\/li>\n<\/ul>\n\n\n\n<p>The function <span class=\"rnthl rntliteral\">read_temp_raw()<\/span> gets the temperature readings from the <span class=\"rnthl rntliteral\">w1_slave<\/span> file (that&#8217;s the place where those are stored). This function opens the <span class=\"rnthl rntliteral\">w1_slave<\/span> file, reads its contents line by line, and then returns a list containing the lines.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def read_temp_raw():\n    f = open(device_file, 'r')\n    lines = f.readlines()\n    f.close()\n    return lines<\/code><\/pre>\n\n\n\n<p>Finally, the <span class=\"rnthl rntliteral\">read_temp()<\/span> function reads the temperature data.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def read_temp():\n    lines = read_temp_raw()\n    while lines&#091;0].strip()&#091;-3:] != 'YES':\n        time.sleep(0.2)\n        lines = read_temp_raw()\n        equals_pos = lines&#091;1].find('t=')\n    if equals_pos != -1:\n        temp_string = lines&#091;1]&#091;equals_pos+2:]\n        temp_c = float(temp_string) \/ 1000.0\n        temp_f = temp_c * 9.0 \/ 5.0 + 32.0\n        return temp_c, temp_f<\/code><\/pre>\n\n\n\n<p>First, it checks if it can find a &#8220;YES&#8221; in the first line as we&#8217;ve seen previously. If the data is not valid, it waits for 0.2 seconds and retries until a valid reading is obtained.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while lines&#091;0].strip()&#091;-3:] != 'YES':\n    time.sleep(0.2)\n    lines = read_temp_raw()\n    equals_pos = lines&#091;1].find('t=')<\/code><\/pre>\n\n\n\n<p>The function then extracts the temperature value from the second line after <span class=\"rnthl rntliteral\">t=<\/span> and converts it to Celsius (<span class=\"rnthl rntliteral\">temp_c<\/span>) and Fahrenheit (<span class=\"rnthl rntliteral\">temp_f<\/span>). It returns both temperature values. As we&#8217;ve seen previously, we need to divide by 1000 to get the temperature in Celsius degrees. Then, we just need to convert that value to Fahrenheit.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>temp_c = float(temp_string) \/ 1000.0\ntemp_f = temp_c * 9.0 \/ 5.0 + 32.0\nreturn temp_c, temp_f<\/code><\/pre>\n\n\n\n<p>Finally, we have a loop (<span class=\"rnthl rntliteral\">while True<\/span>) that calls the <span class=\"rnthl rntliteral\">read_temp()<\/span> function to get the temperature in Celsius and Fahrenheit, then prints the values with two decimal places. The loop runs indefinitely, with a one-second delay between each temperature reading.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while True:\n    temperature_celsius, temperature_fahrenheit = read_temp()\n    print(f'Temperature: {temperature_celsius:.2f} \u00b0C')\n    print(f'Temperature: {temperature_fahrenheit:.2f} \u00b0F')\n    print('')\n    time.sleep(1)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>Save your Python file. Then run it on your Raspberry Pi. Run the following command on the directory of your project file (use the name of your file):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><em>python temp_ds18b20.py<\/em><\/pre>\n\n\n\n<p>After running the script, new temperature readings will be published in the Python shell every second. Touch the sensor to see the temperature increasing. It will display the readings both in Celsius and Fahrenheit degrees.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"547\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ds18b20-temperature-python-demonstration-readings-shell.png?resize=750%2C547&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"demonstration temperature ds18b20 raspberry pi\" class=\"wp-image-133387\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ds18b20-temperature-python-demonstration-readings-shell.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/ds18b20-temperature-python-demonstration-readings-shell.png?resize=300%2C219&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to get temperature readings from the DS18B20 and print the results on the Python shell.<\/p>\n\n\n\n<p>We hope you found this tutorial useful. We have tutorials for other popular sensors:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-bme280-python\/\">Raspberry Pi: BME280 Temperature, Humidity and Pressure Sensor (Python)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-dht11-dht22-python\/\">Raspberry Pi: DHT11\/DHT22 Temperature and Humidity (Python)<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-detect-motion-pir-python\/\">Raspberry Pi: Detect Motion using a PIR Sensor with Python<\/a><\/li>\n<\/ul>\n\n\n\n<p>You can check all our Raspberry Pi projects on the following link:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-raspberry-pi\/\" title=\"\">Free Raspberry Pi Projects and Tutorials<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to interface the Raspberry Pi with the DS18B20 temperature sensor and how to get temperature readings using a Python program. Table of Contents Throughout this tutorial, we\u2019ll cover &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi: Temperature Readings with DS18B20 Sensor (Python)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-ds18b20-python\/#more-133368\" aria-label=\"Read more about Raspberry Pi: Temperature Readings with DS18B20 Sensor (Python)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":133423,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[301,264,190,268],"tags":[],"class_list":["post-133368","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-raspberrypi","category-project","category-raspberry-pi","category-raspberry-pi-project"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/Raspberry-Pi-DS18B20-temperatue-sensor-Guide.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/133368","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=133368"}],"version-history":[{"count":12,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/133368\/revisions"}],"predecessor-version":[{"id":137648,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/133368\/revisions\/137648"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/133423"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=133368"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=133368"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=133368"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}