{"id":134432,"date":"2024-01-25T14:06:36","date_gmt":"2024-01-25T14:06:36","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=134432"},"modified":"2024-01-29T10:56:42","modified_gmt":"2024-01-29T10:56:42","slug":"raspberry-pi-temperature-humidity-data-logger","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/raspberry-pi-temperature-humidity-data-logger\/","title":{"rendered":"Raspberry Pi with DHT11\/DHT22: Temperature and Humidity Data Logger (Python)"},"content":{"rendered":"\n<p>In this project, you&#8217;re going to build a data logger with the Raspberry Pi and the DHT11\/DHT22 sensor that automatically stores temperature, humidity, and the corresponding timestamp on a <em>.txt<\/em> file. This project gives you the basics of data collection, which is useful in many different applications that use sensors. You can apply the concepts from this project to any sensor.<\/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-Datalogger.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi with DHT11 DHT22 Temperature and Humidity Data Logger Python\" class=\"wp-image-134434\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial-Datalogger.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-Datalogger.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-Datalogger.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-Datalogger.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<p><strong>New to the DHT11 or DHT22 temperature sensor?<\/strong> Read our getting started guide: <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-dht11-dht22-python\/\">Raspberry Pi: DHT11\/DHT22 Temperature and Humidity (Python)<\/a><\/p>\n\n\n\n<p><strong>Table of Contents<\/strong><\/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=\"#dht11-dht22-intro\" title=\"\">DHT11\/DHT22 Introduction<\/a><\/li>\n\n\n\n<li><a href=\"#parts-required\" title=\"\">Parts Required<\/a><\/li>\n\n\n\n<li><a href=\"#dht-sensor-raspberry-pi-wiring\" title=\"\">Wiring the DHT11\/DHT22 Sensor to the Raspberry Pi<\/a><\/li>\n\n\n\n<li><a href=\"#DHT-library\" title=\"\">Installing Libraries<\/a><\/li>\n\n\n\n<li><a href=\"#rpi-datalogger-python-code\" title=\"\">Raspberry Pi DHT Datalogger 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=\"dht11-dht22-intro\">Introducing the DHT11\/DHT22 Sensor<\/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<p>For a more detailed introduction to the DHT11\/DHT22 sensor, read our getting started guide:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-dht11-dht22-python\/\" title=\"\">Raspberry Pi: DHT11\/DHT22 Temperature and Humidity (Python)<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"parts-required\">Parts Required<\/h2>\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\/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\"><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\" \/><\/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\" id=\"DHT-library\">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<p>Now, you have everything ready to start writing your Python code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"rpi-datalogger-python-code\">Raspberry Pi DHT Datalogger Python Script<\/h2>\n\n\n\n<p>Create a new Python file on your Raspberry Pi called <em>dht-datalogger.py<\/em> and copy the following code. It must be saved on the same folder where you created the virtual environment (in our case <em>Desktop\/dht_test<\/em>)<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-python\"># Complete Project Details: https:\/\/RandomNerdTutorials.com\/raspberry-pi-temperature-humidity-data-logger\/\n\nimport adafruit_dht\nimport board\nimport time\nimport os\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\n# create a variable to control the while loop\nrunning = True\n\n# Check if the file exists before opening it in 'a' mode (append mode)\nfile_exists = os.path.isfile('sensor_readings.txt')\nfile = open('sensor_readings.txt', 'a')\n\n# Write the header to the file if the file does not exist\nif not file_exists:\n    file.write('Time and Date, temperature (\u00baC), temperature (\u00baF), humidity (%)\\n')\n\n# loop forever\nwhile running:\n    try:\n        # read the humidity and temperature\n        temperature_c = sensor.temperature\n        temperature_f = temperature_c * (9 \/ 5) + 32\n        humidity = sensor.humidity\n\n        #print readings on the shell\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        # save time, date, temperature, and humidity in .txt file\n        file.write(time.strftime('%H:%M:%S %d\/%m\/%Y') + ', {:.2f}, {:.2f}, {:.2f}\\n'.format(temperature_c, temperature_f, humidity))\n\n        # log new readings every 10 seconds\n        time.sleep(10)\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\n    except KeyboardInterrupt:\n        print('Program stopped')\n        running = False\n        file.close()\n\n    except Exception as e:\n        print('An unexpected error occurred:', str(e))\n        running = False\n        file.close()\n        sensor.exit()\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\/dht_data_logger.py\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How the Code Works<\/h2>\n\n\n\n<p>Here&#8217;s a quick description of what the code does:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>it saves sensor readings and the corresponding timestamp to a file called <em>sensor_readings.txt<\/em>.<\/li>\n\n\n\n<li>but first, it checks if a file called <em>sensor_readings.txt<\/em> already exists (this is to prevent writing the file header multiple times when the program resets or stops\/starts).<\/li>\n\n\n\n<li>if the file doesn&#8217;t exist, it will create a new file.<\/li>\n\n\n\n<li>there&#8217;s an infinite loop, in which you get temperature and humidity readings and write those to the file with the corresponding timestamp.<\/li>\n\n\n\n<li>the program keeps running and writing to the file until you tell the program to stop with a keyboard interrupt or until the program stops for any other reason. In that case, we close the file.<\/li>\n<\/ul>\n\n\n\n<p>Continue reading for a more detailed explanation of the code, or skip to the <a href=\"#demonstration\" title=\"\">demonstration section<\/a>,<\/p>\n\n\n\n<p>The code is very similar to the one in <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-dht11-dht22-python\/\" title=\"\">this guide<\/a> (but it adds some lines for datalogging).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Import the Required Libraries<\/h3>\n\n\n\n<p>First, you need to import the required libraries. The <span class=\"rnthl rntliteral\">adafruit_dht<\/span> to get readings from the DHT sensor, the <span class=\"rnthl rntliteral\">board<\/span> module to interact with the GPIOs, the <span class=\"rnthl rntliteral\">time<\/span> module to get timestamps and add delays to your code, and the <span class=\"rnthl rntliteral\">os<\/span> module that will allow us to interact with the operating system (in our case, we need to check if a file already exists on the filesystem).<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import adafruit_dht\nimport board\nimport time\nimport os<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">DHT Sensor<\/h3>\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 data pin is connected to GPIO 4\nsensor = adafruit_dht.DHT22(board.D4)<\/code><\/pre>\n\n\n\n<p>If you\u2019re 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<h3 class=\"wp-block-heading\">File Handling<\/h3>\n\n\n\n<p>The following line, checks if a file called <em>sensor_readings.txt<\/em> already exists (it will look for in the project folder path). If the file already exists, the <span class=\"rnthl rntliteral\">file_exists<\/span> variable will be <span class=\"rnthl rntliteral\">True<\/span>. Otherwise, it will be <span class=\"rnthl rntliteral\">False<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>file_exists = os.path.isfile('sensor_readings.txt')<\/code><\/pre>\n\n\n\n<p>Then, it opens the file in <span class=\"rnthl rntliteral\">&#8216;a&#8217;<\/span> (append) mode. If the file doesn&#8217;t exist yet, it will automatically create the file before opening it.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>file = open('sensor_readings.txt', 'a')<\/code><\/pre>\n\n\n\n<p>When using the <span class=\"rnthl rntliteral\">open()<\/span> function, you can specify different modes to control how the file is accessed and used. When writing to the file, the most popular methods are <span class=\"rnthl rntliteral\">&#8216;w&#8217;<\/span> (write) and <span class=\"rnthl rntliteral\">&#8216;a&#8217;<\/span> (append).<\/p>\n\n\n\n<p class=\"rntbox rntclgreen\"><strong>Write vs Append mode<\/strong>: the write mode opens the file for writing and empties the file if it already exists. The append mode opens the file for writing and it appends new data to the end of the file. If you want to have a record of your readings over time, the best mode is append so that you can keep all your previous data.<\/p>\n\n\n\n<p>If the file doesn&#8217;t exist yet, the code writes a header line to the file, containing the column names. We&#8217;ll save date and time first, then, temperature in Celsius and Fahrenheit, and finally the humidity.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>if not file_exists:\n    file.write('Time and Date, temperature (\u00baC), temperature (\u00baF), humidity (%)\\n')<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Getting Sensor Readings and Data Logging<\/h3>\n\n\n\n<p>Then, we have a while loop that is always running as long as the <span class=\"rnthl rntliteral\">running<\/span> variable is <span class=\"rnthl rntliteral\">True<\/span>. We have set that variable to <span class=\"rnthl rntliteral\">True<\/span> at the beginning of the code. The <span class=\"rnthl rntliteral\">running<\/span> variable will change to <span class=\"rnthl rntliteral\">False<\/span>, when the execution of the program is stopped by a keyboard interrupt, or when an unexpected error occurs.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>while running:\n    try:<\/code><\/pre>\n\n\n\n<p>Inside the loop, the <span class=\"rnthl rntliteral\">try<\/span> block attempts to read the humidity and temperature from the DHT sensor and saves the readings in the <span class=\"rnthl rntliteral\">humidity<\/span> and <span class=\"rnthl rntliteral\">temperature_c<\/span> variables. We also convert the temperature to Fahrenheit.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code> temperature_c = sensor.temperature\n temperature_f = temperature_c * (9 \/ 5) + 32\n humidity = sensor.humidity<\/code><\/pre>\n\n\n\n<p>All readings are printed in the shell.<\/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<p>Then, we use the <span class=\"rnthl rntliteral\">write()<\/span> function on the <span class=\"rnthl rntliteral\">file<\/span> object to write data to the file. We print the timestamp, temperature in Celsius, temperature in Fahrenheit, and humidity.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>file.write(time.strftime('%H:%M:%S %d\/%m\/%Y') + ', {:.2f}, {:.2f}, {:.2f}\\n'.format(temperature_c, temperature_f, humidity))<\/code><\/pre>\n\n\n\n<p>To get a timestamp, we use <span class=\"rnthl rntliteral\">time.strftime(&#8220;%H:%M:%S %d\/%m\/%Y&#8221;)<\/span>\u2014the argument in the parentheses here indicates the format you want the time and date to appear in: hours, minutes, seconds, day, month, and year, respectively.<\/p>\n\n\n\n<p>This script reads and records the temperature and humidity every 10 seconds, but you can change that by changing the delay time. The sensor is capable of taking readings every 2 seconds, but<br>no faster than that.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code> time.sleep(10)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Interrupt and Exception Handling<\/h3>\n\n\n\n<p>In case there is an error reading from the DHT sensor, we print the error message, pause for two seconds, and use the <span class=\"rnthl rntliteral\">continue<\/span> statement to go to the next iteration of the <span class=\"rnthl rntliteral\">try<\/span> block.<\/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<\/code><\/pre>\n\n\n\n<p>If you interrupt the program by pressing <strong>Ctrl<\/strong>+<strong>C<\/strong>, the code catches the <span class=\"rnthl rntliteral\">KeyboardInterrupt<\/span> exception, prints a message indicating program termination, and then closes the file before setting <span class=\"rnthl rntliteral\">running<\/span> to <span class=\"rnthl rntliteral\">False<\/span> to exit the loop. <\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except KeyboardInterrupt:\n    print('Program stopped')\n    running = False\n    file.close()<\/code><\/pre>\n\n\n\n<p><strong>Important<\/strong>: you need to call <span class=\"rnthl rntliteral\">file.close()<\/span> so that all data is written to the file.<\/p>\n\n\n\n<p>We proceed similarly if any other error or exception occurs.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>except Exception as e:\n    print('An unexpected error occurred:', str(e))\n    running = False\n    file.close()<\/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 directory of your virtual environment. Then run it on your Raspberry Pi. Run the following command (on the same path of the virtual environment):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><em>python dht-datalogger.py<\/em><\/pre>\n\n\n\n<p>You&#8217;ll start getting new temperature and humidity readings on the terminal window, and a new file called <em>sensors_readings.txt<\/em> will be created in your project folder. If you&#8217;re using VS Code, you&#8217;ll see the newly created file on the file explorer (don&#8217;t open it yet). <\/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=\"1021\" height=\"811\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/RPi-Datalogger-DHT-New-File-Created-2.png?resize=1021%2C811&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Datalogger VS Code\" class=\"wp-image-145936\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/RPi-Datalogger-DHT-New-File-Created-2.png?w=1021&amp;quality=100&amp;strip=all&amp;ssl=1 1021w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/RPi-Datalogger-DHT-New-File-Created-2.png?resize=300%2C238&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/RPi-Datalogger-DHT-New-File-Created-2.png?resize=768%2C610&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1021px) 100vw, 1021px\" \/><\/figure><\/div>\n\n\n<p>Let the code run for a while so it gathers a considerable amount of data. Then, stop the execution of the code by pressing<strong> CTRL+C<\/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=\"634\" height=\"290\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/program-stopped-keyboard-interrupt-2.png?resize=634%2C290&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi DHT datalogger keyboard interrupt\" class=\"wp-image-145937\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/program-stopped-keyboard-interrupt-2.png?w=634&amp;quality=100&amp;strip=all&amp;ssl=1 634w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/program-stopped-keyboard-interrupt-2.png?resize=300%2C137&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 634px) 100vw, 634px\" \/><\/figure><\/div>\n\n\n<p>Now, you can open the <em>sensors_readings.txt<\/em> file and see all the data it collected. You can run the program again to gather more data and it won&#8217;t overwrite the previous data.<\/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=\"651\" height=\"493\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/sensor-readings-data-logger-Raspberry-Pi-DHT-2.png?resize=651%2C493&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Sensor Readings Data Logger Raspberry Pi VS Code\" class=\"wp-image-145935\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/sensor-readings-data-logger-Raspberry-Pi-DHT-2.png?w=651&amp;quality=100&amp;strip=all&amp;ssl=1 651w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/sensor-readings-data-logger-Raspberry-Pi-DHT-2.png?resize=300%2C227&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 651px) 100vw, 651px\" \/><\/figure><\/div>\n\n\n<p>If you&#8217;re using PuTTY, navigate to your project folder. List all files inside the project folder using the <span class=\"rnthl rntliteral\"><strong>ls<\/strong><\/span> command and note that a file called <em>sensor_readings.txt<\/em> is listed.<\/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\/2024\/01\/datalogger-file-created-putty-1.png?resize=661%2C418&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Datalogger List Files PuTTY\" class=\"wp-image-145939\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/datalogger-file-created-putty-1.png?w=661&amp;quality=100&amp;strip=all&amp;ssl=1 661w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2024\/01\/datalogger-file-created-putty-1.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>To open that file, use the following command:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">cat sensor_readings.txt<\/pre>\n\n\n\n<p>Then, you&#8217;ll see all data gathered by your sensor with the corresponding timestamps.<\/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=\"597\" height=\"633\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/sensor-readings-file-putty-raspberry-pi.png?resize=597%2C633&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Raspberry Pi Datalogger File txt Putty\" class=\"wp-image-134456\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/sensor-readings-file-putty-raspberry-pi.png?w=597&amp;quality=100&amp;strip=all&amp;ssl=1 597w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/08\/sensor-readings-file-putty-raspberry-pi.png?resize=283%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 283w\" sizes=\"(max-width: 597px) 100vw, 597px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this project, you\u2019ve learned a very useful concept: data logging. Now you can use data logging in other monitoring projects. Here are some ideas:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use a<a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-detect-motion-pir-python\/\" title=\"\"> PIR motion sensor<\/a> that saves a timestamp every time it detects movement;<\/li>\n\n\n\n<li>Duplicate this project, but use a different sensor\u2014 <a href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-bme280-python\/\" title=\"\">we have an example for the BME280<\/a>;<\/li>\n\n\n\n<li>Build a weather station data logger using more sensors;<\/li>\n\n\n\n<li>Search for other monitoring sensor applications, for example, soil moisture, rain, and light sensors to build a greenhouse data logger.<\/li>\n<\/ul>\n\n\n\n<p>We hope you found this tutorial useful. If you&#8217;re quite new to the Raspberry Pi, check 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","protected":false},"excerpt":{"rendered":"<p>In this project, you&#8217;re going to build a data logger with the Raspberry Pi and the DHT11\/DHT22 sensor that automatically stores temperature, humidity, and the corresponding timestamp on a .txt &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Raspberry Pi with DHT11\/DHT22: Temperature and Humidity Data Logger (Python)\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/raspberry-pi-temperature-humidity-data-logger\/#more-134432\" aria-label=\"Read more about Raspberry Pi with DHT11\/DHT22: Temperature and Humidity Data Logger (Python)\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":134434,"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-134432","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\/08\/Raspberry-Pi-DHT-Temperature-Humidity-Tutorial-Datalogger.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\/134432","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=134432"}],"version-history":[{"count":19,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/134432\/revisions"}],"predecessor-version":[{"id":146396,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/134432\/revisions\/146396"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/134434"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=134432"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=134432"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=134432"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}