{"id":134396,"date":"2023-10-17T16:04:11","date_gmt":"2023-10-17T16:04:11","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=134396"},"modified":"2024-01-17T15:05:50","modified_gmt":"2024-01-17T15:05:50","slug":"raspberry-pi-dht11-dht22-python","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-dht11-dht22-python\/","title":{"rendered":"Raspberry Pi: DHT11\/DHT22 Temperature and Humidity (Python)"},"content":{"rendered":"\n<p>Learn how to interface the DHT11 and DHT22 digital temperature sensors with the Raspberry Pi to get temperature and humidity readings. You&#8217;ll learn how to connect the sensors to the Raspberry Pi, include the required libraries, and write a Python script that displays the current temperature and humidity on the shell\/terminal.<\/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\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi with DHT11 DHT22 Getting Temperature and Humidity Python\" class=\"wp-image-134402\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial.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\">Table of Contents<\/h2>\n\n\n\n<p>Throughout this tutorial, we&#8217;ll cover the following main topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"#prerequisites\" title=\"\">Prerequisites<\/a><\/li>\n\n\n\n<li><a href=\"#dht-sensor-introduction\" title=\"\">Introducing the DHT11 and DHT22 Sensors<\/a><\/li>\n\n\n\n<li><a href=\"#dht-sensor-raspberry-pi-wiring\" title=\"\">Wiring the DHT Sensor to the Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"#raspberry-pi-DHT-python-code\" title=\"\">Raspberry Pi Getting Temperature and Humidity from DHT Sensor (Python Script)<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"prerequisites\">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&#8217;re not familiar with the Raspberry Pi, you can read our <a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\" title=\"\"><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 on VS Code. We have a detailed tutorial about that subject: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\" title=\"\"><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: <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=\"dht-sensor-introduction\">Introducing DHT11\/DHT22 Sensors<\/h2>\n\n\n\n<p>The DHT11 and DHT22 sensors are used to measure temperature and relative humidity. These are very popular among makers and electronics hobbyists.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"750\" height=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/DHT11-and-DHT22-Sensors.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DHT11\/DHT22 Temperature and Humidity Sensors \" class=\"wp-image-132937\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/DHT11-and-DHT22-Sensors.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/DHT11-and-DHT22-Sensors.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>These sensors contain a chip that does analog to digital conversion and spit out a digital signal with the temperature and humidity. This makes them very easy to use with any microcontroller.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">DHT11 vs DHT22<\/h3>\n\n\n\n<p>The DHT11 and DHT22 are very similar but differ in their specifications. The following table compares some of the most important specifications of the DHT11 and DHT22 temperature and humidity sensors. For a more in-depth analysis of these sensors, please check the sensors&#8217; datasheet. <\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><\/td><td><center><span class=\"rnthl rntclblue\"><strong>DHT11<\/strong><\/span><\/center><\/td><td><center><span class=\"rnthl rntcgray\"><strong>DHT22<\/strong><\/span><\/center><\/td><\/tr><tr><td><\/td><td><center><img data-recalc-dims=\"1\" decoding=\"async\" width=\"40\" height=\"57\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht11_bb.png?resize=40%2C57&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-84265\"><\/center><\/td><td><center><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"40\" height=\"57\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht22_bb.png?resize=40%2C57&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"\" class=\"wp-image-84270\"><\/center><\/td><\/tr><tr><td><strong>Temperature range<\/strong><\/td><td>0 to 50 \u00baC <sup>+\/-2 \u00baC<\/sup><\/td><td>-40 to 80 \u00baC <sup>+\/-0.5\u00baC<\/sup><\/td><\/tr><tr><td><strong>Humidity range<\/strong><\/td><td>20 to 90% <sup>+\/-5%<\/sup><\/td><td>0 to 100% <sup>+\/-2%<\/sup><\/td><\/tr><tr><td><strong>Resolution<\/strong><\/td><td>Humidity: 1%<br>Temperature: 1\u00baC <\/td><td>Humidity: 0.1%<br>Temperature: 0.1\u00baC<\/td><\/tr><tr><td><strong>Operating voltage<\/strong><\/td><td>3 &#8211; 5.5 V DC<\/td><td>3 &#8211; 6 V DC <\/td><\/tr><tr><td><strong>Current supply<\/strong><\/td><td>0.5 &#8211; 2.5 mA<\/td><td>1 &#8211; 1.5 mA<\/td><\/tr><tr><td><strong>Sampling period<\/strong><\/td><td>1 second<\/td><td>2 seconds<\/td><\/tr><tr><td><strong>Price<\/strong><\/td><td>$1 to $5<\/td><td>$4 to $10<\/td><\/tr><tr><td><strong>Where to buy<\/strong><\/td><td><a href=\"https:\/\/makeradvisor.com\/tools\/dht11-temperature-humidity-sensor\/\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Check prices<\/a><\/td><td><a href=\"https:\/\/makeradvisor.com\/tools\/dht22-temperature-humidity-sensor\/\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Check prices<\/a><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The DHT22 sensor has a better resolution and a wider temperature and humidity measurement range. However, it is a bit more expensive, and you can only request readings with 2 seconds interval. <\/p>\n\n\n\n<p>The DHT11 has a smaller range and it&#8217;s less accurate. However, you can request sensor readings every second. It&#8217;s also a bit cheaper. <\/p>\n\n\n\n<p>Despite their differences, they work in a similar way, and you can use the same code to read temperature and humidity. You just need to select in the code the sensor type you&#8217;re using.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">DHT Pinout<\/h2>\n\n\n\n<p>DHT sensors have four pins as shown in the following figure. However, if you get your DHT sensor in a breakout board, it comes with only three pins and with an internal pull-up resistor on pin 2.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"138\" height=\"300\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/04\/dht22-pinout.png?resize=138%2C300&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DHT22 Temperature and Humidity Sensor using Arduino IDE\" class=\"wp-image-84280\"\/><\/figure><\/div>\n\n\n<p>The following table shows the DHT22 and DHT11 pinout. When the sensor is facing you, pin numbering starts at 1 from left to right<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>DHT pin<\/strong><\/td><td><strong>Connect to<\/strong><\/td><\/tr><tr><td><strong>1<\/strong><\/td><td><span class=\"rnthl rntcred\">3.3V<\/span><\/td><\/tr><tr><td><strong>2<\/strong><\/td><td>Any digital GPIO; also connect a 4.7k Ohm pull-up resistor<\/td><\/tr><tr><td><strong>3<\/strong><\/td><td>Don&#8217;t connect<\/td><\/tr><tr><td><strong>4<\/strong><\/td><td><span class=\"rnthl rntcblack\">GND<\/span><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">DHT Sensor Breakout Board<\/h3>\n\n\n\n<p>If you got a DHT11 or DHT22 sensor on a breakout board, they only come with three pins and have an internal pull-up resistor on the data pin.<\/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=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/dht22-sensor-transparent.png?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"DHT22 sensor\" class=\"wp-image-132939\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/dht22-sensor-transparent.png?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/07\/dht22-sensor-transparent.png?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p>In this case, wiring is even simpler and you don&#8217;t need to wire an external resistor. The DHT breakout boards usually have labels on the pins: GND, VCC, and DATA.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>DHT pin<\/strong><\/td><td><strong>Connect to<\/strong><\/td><\/tr><tr><td><strong>GND<\/strong><\/td><td><span class=\"rnthl rntcblack\">GND<\/span><\/td><\/tr><tr><td><strong>VCC<\/strong><\/td><td><span class=\"rnthl rntcred\">3V3 (OUT)<\/span><\/td><\/tr><tr><td><strong>DAT<\/strong><\/td><td><span class=\"rnthl rntcblue\">GPIO 4<\/span> (or any other digital pin)<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Parts Required<\/h2>\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=\"422\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit.jpg?resize=750%2C422&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi with DHT22 Circuit\" class=\"wp-image-134403\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit.jpg?resize=300%2C169&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 list of parts you need to build the circuit (if you don&#8217;t have a DHT breakout board, you need a 4.7kOhm resistor):<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/raspberry-pi-board\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Raspberry Pi board<\/a> &#8211; read <a href=\"https:\/\/makeradvisor.com\/best-raspberry-pi-starter-kits\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Best Raspberry Pi Starter Kits<\/a><\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/dht11-temperature-humidity-sensor\/\" target=\"_blank\">DHT11 <\/a>or <a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/dht22-temperature-humidity-sensor\/\" target=\"_blank\">DHT22 <\/a>temperature and humidity sensor<\/li>\n\n\n\n<li><a aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/resistors-kits\/\" target=\"_blank\" rel=\"noreferrer noopener\">4.7k Ohm resistor<\/a> or similar value (not needed if you have a DHT breakout board)<\/li>\n\n\n\n<li><a rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\" href=\"https:\/\/makeradvisor.com\/tools\/mb-102-solderless-breadboard-830-points\/\" target=\"_blank\">Breadboard<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/makeradvisor.com\/tools\/jumper-wires-kit-120-pieces\/\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\" (opens in a new tab)\">Jumper wires<\/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=\"dht-sensor-raspberry-pi-wiring\">Wiring the DHT11\/DHT22 Sensor to the Raspberry Pi<\/h2>\n\n\n\n<p>Wire the DHT22 or DHT11 sensor to the Raspberry Pi as shown in the following schematic diagram. If you have a DHT breakout board, ignore the resistor.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><a href=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit_bb.png?quality=100&#038;strip=all&#038;ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"816\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit_bb.png?resize=1024%2C816&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi DHT Sensor Wiring\" class=\"wp-image-134406\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit_bb.png?resize=1024%2C816&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit_bb.png?resize=300%2C239&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit_bb.png?resize=768%2C612&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Circuit_bb.png?w=1230&amp;quality=100&amp;strip=all&amp;ssl=1 1230w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure><\/div>\n\n\n<p>In this example, we&#8217;re connecting the DHT data pin to <span class=\"rnthl rntcblue\">GPIO 4<\/span>. However, you can use any other suitable digital GPIO. <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\" title=\"\">Learn more about the Raspberry Pi GPIOs here<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Getting DHT11\/22 Temperature and Humidity<\/h2>\n\n\n\n<p>There are different ways to get temperature and humidity readings from the DHT11 or DHT22 sensors using the Raspberry Pi with Python. We&#8217;ll use the <strong><a href=\"https:\/\/github.com\/adafruit\/Adafruit_CircuitPython_DHT\" target=\"_blank\" rel=\"noopener\" title=\"\">Adafruit_CircuitPython_DHT<\/a><\/strong> Python library.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Update your Raspberry Pi<\/h3>\n\n\n\n<p>First, update and upgrade your Raspberry Pi, if any updates are available. Run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt update &amp;&amp; sudo apt upgrade<\/code><\/pre>\n\n\n\n<p>If there&#8217;s a need to update, it will ask you if you want to continue. Click <strong>Y<\/strong> and <strong>Enter <\/strong>to proceed. You may need to wait a few minutes if it needs to update.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Create a Virtual Environment<\/h3>\n\n\n\n<p>We&#8217;ll install the DHT library in a virtual environment. Creating a virtual environment will isolate the Python libraries we&#8217;re using, in this case, the DHT library, from the rest of the system.<\/p>\n\n\n\n<p>We&#8217;ll create our virtual environment on a directory on our <em>Desktop<\/em>. Enter the following command on a Terminal window to move to the Desktop:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cd ~\/Desktop<\/code><\/pre>\n\n\n\n<p>Create a folder for your project. This is where we&#8217;ll create the virtual environment and install the library. We&#8217;ll create a folder called <em>dht_test<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mkdir dht_test<\/code><\/pre>\n\n\n\n<p>Move to the newly created folder:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cd ~\/Desktop\/dht_test<\/code><\/pre>\n\n\n\n<p>Create a virtual environment for this directory called <span class=\"rnthl rntliteral\">myenv<\/span>. This must be the same directory where we&#8217;ll install the DHT library. Replace <span class=\"rnthl rntliteral\">myenv<\/span> with the desired name for your virtual environment.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python3 -m venv myenv<\/code><\/pre>\n\n\n\n<p>Then, you can run the following command to check that the virtual environment is there.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ls -l<\/code><\/pre>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"427\" height=\"136\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/create-virtual-environment.png?resize=427%2C136&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Create a Virtual Environment Raspberry Pi Python\" class=\"wp-image-145917\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/create-virtual-environment.png?w=427&amp;quality=100&amp;strip=all&amp;ssl=1 427w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/create-virtual-environment.png?resize=300%2C96&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 427px) 100vw, 427px\" \/><\/figure><\/div>\n\n\n<p>Activate the virtual environment:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>source myenv\/bin\/activate<\/code><\/pre>\n\n\n\n<p>Your prompt should change to indicate that you are now in the virtual environment.<\/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=\"482\" height=\"50\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/virtual-environment.png?resize=482%2C50&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Activate Python Virtual Environment\" class=\"wp-image-145918\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/virtual-environment.png?w=482&amp;quality=100&amp;strip=all&amp;ssl=1 482w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/virtual-environment.png?resize=300%2C31&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 482px) 100vw, 482px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">Installing the Adafruit_CircuitPython_DHT Library<\/h3>\n\n\n\n<p>Now that we are in our virtual environment, we can install the library. Run the following command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python3 -m pip install adafruit-circuitpython-dht<\/code><\/pre>\n\n\n\n<p>After a few seconds, the library will be installed (ignore any yellow warnings about deprecated packages).<\/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=\"652\" height=\"274\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/installing-circuitpython-dht.png?resize=652%2C274&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Installing the Adafruit_CircuitPython_DHT Library\" class=\"wp-image-145919\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/installing-circuitpython-dht.png?w=652&amp;quality=100&amp;strip=all&amp;ssl=1 652w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/installing-circuitpython-dht.png?resize=300%2C126&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 652px) 100vw, 652px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\" id=\"raspberry-pi-DHT-python-code\">Python Code for Raspberry Pi DHT11\/DHT22<\/h3>\n\n\n\n<p>The following script gets temperature and humidity from the DHT sensors and prints the readings on the Python shell. Create a new Python file with a name of your choice, for example, <em>dht_basic.py<\/em>, 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-dht11-dht22-python\/\n# Based on Adafruit_CircuitPython_DHT Library Example\n\nimport time\nimport board\nimport adafruit_dht\n\n# Sensor data pin is connected to GPIO 4\nsensor = adafruit_dht.DHT22(board.D4)\n# Uncomment for DHT11\n#sensor = adafruit_dht.DHT11(board.D4)\n\nwhile True:\n    try:\n        # Print the values to the serial port\n        temperature_c = sensor.temperature\n        temperature_f = temperature_c * (9 \/ 5) + 32\n        humidity = sensor.humidity\n        print(&quot;Temp={0:0.1f}\u00baC, Temp={1:0.1f}\u00baF, Humidity={2:0.1f}%&quot;.format(temperature_c, temperature_f, humidity))\n\n    except RuntimeError as error:\n        # Errors happen fairly often, DHT's are hard to read, just keep going\n        print(error.args[0])\n        time.sleep(2.0)\n        continue\n    except Exception as error:\n        sensor.exit()\n        raise error\n\n    time.sleep(3.0)\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\/new_dht_basic.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<p>To create and run Python scripts on the Raspberry Pi, we like to use VS Code with an SSH extension: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\" title=\"\">Programming Raspberry Pi Remotely using VS Code (Remote-SSH)<\/a>. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Continue reading to learn how the code works, or skip to the <a href=\"#demonstration\" title=\"Demonstration\">Demonstration<\/a> section.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Importing libraries<\/h4>\n\n\n\n<p>Start by importing the required libraries: the <span class=\"rnthl rntliteral\">time<\/span> module to add delays to our code, the <span class=\"rnthl rntliteral\">board<\/span> module to interact with the Raspberry Pi GPIOs and the <span class=\"rnthl rntliteral\">adafruit_dht<\/span> to read from the DHT sensor.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import time\nimport board\nimport adafruit_dht<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">DHT Sensor<\/h4>\n\n\n\n<p>On the following line, we initialize our DHT sensor. We are using a DHT22 connected to GPIO 4 (you can use any other suitable GPIO as long as you change the code on the following line):<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sensor = adafruit_dht.DHT22(board.D4)\n<\/code><\/pre>\n\n\n\n<p>If you&#8217;re using a DHT11, it should be like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>sensor = adafruit_dht.DHT11(board.D4)<\/code><\/pre>\n\n\n\n<p>From now on, we&#8217;ll refer to our DHT sensor as <span class=\"rnthl rntliteral\">sensor<\/span> in our code.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">While loop<\/h4>\n\n\n\n<p>Then, we have a loop that keeps the program running indefinitely, until you stop the program. Inside the loop we&#8217;ll try to read the sensor and display the readings.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while True:\n    try:<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Reading Temperature and Humidity<\/h4>\n\n\n\n<p>Getting temperature in Celsius degrees and humidity is as easy as using the <span class=\"rnthl rntliteral\">temperature<\/span> and <span class=\"rnthl rntliteral\">humidity<\/span> properties of the <span class=\"rnthl rntliteral\">sensor<\/span> object. So, you can get temperature like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>temperature_c = sensor.temperature<\/code><\/pre>\n\n\n\n<p>By default, it will get the temperature in Celsius degrees. We add a line to convert it to Fahrenheit degrees.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>temperature_f = temperature_c * (9 \/ 5) + 32<\/code><\/pre>\n\n\n\n<p>We save the humidity value on the <span class=\"rnthl rntliteral\">humidity<\/span> variable:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>humidity = sensor.humidity<\/code><\/pre>\n\n\n\n<p>After getting sensor readings, we&#8217;ll display them on the shell using the <span class=\"rnthl rntliteral\">print()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>print(\"Temp={0:0.1f}\u00baC, Temp={1:0.1f}\u00baF, Humidity={2:0.1f}%\".format(temperature_c, temperature_f, humidity))<\/code><\/pre>\n\n\n\n<div class=\"wp-block-group rntbox rntclblue\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<p><strong>Formatting the printing output<\/strong><\/p>\n\n\n\n<p><span class=\"rnthl rntliteral\">Temp={0:0.1f}\u00baC<\/span>, <span class=\"rnthl rntliteral\">Temp={1:0.1f}\u00baF<\/span>, <span class=\"rnthl rntliteral\">Humidity={2:0.1f}%<\/span>: This is the format string that defines how the output will be displayed. The format string contains placeholders indicated by curly braces <span class=\"rnthl rntliteral\">{}<\/span> that will be filled in with actual values using the <span class=\"rnthl rntliteral\">.format()<\/span> method.<\/p>\n\n\n\n<p><span class=\"rnthl rntliteral\">Temp={0:0.1f}\u00baC<\/span> indicates the placeholder for the first value (<span class=\"rnthl rntliteral\">temperature<\/span>). It specifies how the value will be formatted:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><span class=\"rnthl rntliteral\">{0}<\/span>: This specifies the index of the value to be inserted (<span class=\"rnthl rntliteral\">0<\/span> refers to the first value provided to the <span class=\"rnthl rntliteral\">.format()<\/span> method).<\/li>\n\n\n\n<li><span class=\"rnthl rntliteral\">:0.1f<\/span>: This is a formatting specification that specifies how the value should be displayed. The <span class=\"rnthl rntliteral\">0<\/span> represents the minimum number of digits, and the <span class=\"rnthl rntliteral\">.1f<\/span> means that it will display the value as a floating-point number with one digit after the decimal point.<\/li>\n<\/ul>\n\n\n\n<p><span class=\"rnthl rntliteral\">Temp={1:0.1f}\u00baF<\/span>: This part of the format string follows the same structure as above but refers to the second value (<span class=\"rnthl rntliteral\">temperature_f<\/span>).<\/p>\n\n\n\n<p><span class=\"rnthl rntliteral\">Humidity={2:0.1f}%<\/span>: This part of the format string refers to the third value (<span class=\"rnthl rntliteral\">humidity<\/span>).\n\n\n\n<p>Finally, <span class=\"rnthl rntliteral\">.format(temperature_c, temperature_f, humidity)<\/span> inserts the actual values into the placeholders within the format string. The values provided in the parentheses are inserted into the placeholders according to their respective indexes (0, 1, 2).<\/p>\n<\/div><\/div>\n\n\n\n<p>If we can&#8217;t get valid temperature and humidity readings, we handle the exceptions on the except blocks:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except RuntimeError as error:\n    # Errors happen fairly often, DHT's are hard to read, just keep going\n    print(error.args&#091;0])\n    time.sleep(2.0)\n    continue\nexcept Exception as error:\n    sensor.exit()\n    raise error\n<\/code><\/pre>\n\n\n\n<p>We get new temperature readings every three seconds. You can adjust the delay time by changing the argument of the <span class=\"rnthl rntliteral\">sleep()<\/span> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>time.sleep(3)<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"demonstration\">Demonstration<\/h2>\n\n\n\n<p>Save your Python file on the same folder of your virtual environment (in our case <em>Desktop\/dht_test<\/em>). Then run it on your Raspberry Pi. Run the following command (make sure you are on the correct path\u2014the same folder of the virtual environment):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><em>python dht-basic.py<\/em><\/pre>\n\n\n\n<p>The virtual environment must be active to run the script. If the virtual environment is not active, you can rerun the following command to activate <span class=\"rnthl rntliteral\">myenv<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>source myenv\/bin\/activate<\/code><\/pre>\n\n\n\n<p>You should get new temperature and humidity readings on the Python Shell or on the Raspberry Pi Terminal every three seconds.<\/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=\"710\" height=\"414\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/dht-print-sensor-readings-raspberry-pi.png?resize=710%2C414&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Print Temperature and Humidity DHT22 DHT11 Sensor\" class=\"wp-image-134418\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/dht-print-sensor-readings-raspberry-pi.png?w=710&amp;quality=100&amp;strip=all&amp;ssl=1 710w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/dht-print-sensor-readings-raspberry-pi.png?resize=300%2C175&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 710px) 100vw, 710px\" \/><\/figure><\/div>\n\n\n<p>You can stop the execution of the program by pressing <strong>CTRL<\/strong>+<strong>C<\/strong>.<\/p>\n\n\n\n<p class=\"rntbox rntclgray\">You may also like reading: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-bme280-python\/\" title=\"\">Raspberry Pi: BME280 Temperature, Humidity and Pressure Sensor (Python)<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to interface the DHT11 and DHT22 digital temperature and humidity sensors with the Raspberry Pi and how to write a Python program to get and display readings. This is one of the most basic projects to get you started with the DHT11 or DHT22 sensor.<\/p>\n\n\n\n<p>We hope you found this tutorial useful. If you&#8217;re a beginner to the Raspberry Pi, you can get started with the following tutorials:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/getting-started-with-raspberry-pi\/\">Getting Started with Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pinout-gpios\/\" title=\"\">Raspberry Pi Pinout Guide<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-remote-ssh-vs-code\/\">Programming Raspberry Pi Remotely using VS Code (Remote-SSH)<\/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>Finally, if you would like to interface the DHT11\/22 sensor with other microcontrollers, we have tutorials for ESP32, ESP8266, and Arduino:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-dht11-dht22-temperature-humidity-sensor-arduino-ide\/\" title=\"\"><strong>ESP32<\/strong>: Getting Started with the DHT11\/DHT22 Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp8266-dht11dht22-temperature-and-humidity-web-server-with-arduino-ide\/\" title=\"\"><strong>ESP8266<\/strong>: Getting Started with the DHT11\/DHT22 Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/complete-guide-for-dht11dht22-humidity-and-temperature-sensor-with-arduino\/\" title=\"Arduino: Getting Started with the DHT11\/22 Sensor\"><strong>Arduino<\/strong>: Getting Started with the DHT11\/DHT22 Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/esp32-esp8266-dht11-dht22-micropython-temperature-humidity-sensor\/\" title=\"\"><strong>ESP32\/ESP8266 (MicroPython)<\/strong>: Getting Started with the DHT11\/DHT22 Sensor<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-pico-dht11-dht22-micropython\/\"><strong>Raspberry Pi Pico<\/strong>: DHT11\/DHT22 Temperature and Humidity Sensor (MicroPython)<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to interface the DHT11 and DHT22 digital temperature sensors with the Raspberry Pi to get temperature and humidity readings. You&#8217;ll learn how to connect the sensors to the &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi: DHT11\/DHT22 Temperature and Humidity (Python)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-dht11-dht22-python\/#more-134396\" aria-label=\"Read more about Raspberry Pi: DHT11\/DHT22 Temperature and Humidity (Python)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":134402,"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,268,190],"tags":[],"class_list":["post-134396","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-raspberrypi","category-project","category-raspberry-pi-project","category-raspberry-pi"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial.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\/134396","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=134396"}],"version-history":[{"count":33,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/134396\/revisions"}],"predecessor-version":[{"id":145943,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/134396\/revisions\/145943"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/134402"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=134396"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=134396"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=134396"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}