In this tutorial, we will learn how to use DHT11/ DHT22/AM2302 with Raspberry Pi 4. Also see how to log sensor data in raspberry pi 4. Once you learn how to log data you can log any sensor data in same the fashion. For this tutorial we are logging DHT22 sensor data to .txt file but you can also use .csv extension file to export data directly in .csv file or change .txt file extension to .csv extension. So let’s get started.

Components Required:
  1. Raspberry pi 4,
  2. Dual Fan Heat Sink aluminium Armor Case. (Optional)
  3. 4.7K ohms Resistor,
  4. DHT22 sensor,
  5. Breadboard,
  6. Jumper Wire.
Installing DHT11/ DHT22 Library for Raspberry PI 4:

Step 1: Create a folder for Libraries. As you will need to install file there. I am creating folder on Desktop.

Step 2: Open terminal and enter following.

sudo apt update
sudo apt install build-essential python-dev

Step 3: Navigate to libraries folder and clone the library by following command.

pi@raspberrypi:~/Desktop/Libraries $ git clone https://github.com/adafruit/Adafruit_Python_DHT.git

You can copy git URL from github website.

Step 4: Move to Adafruit_Python_ DHT directory and type this command to install library.

pi@raspberrypi:~/Desktop/Libraries $ cd Adafruit_Python_DHT
pi@raspberrypi:~/Desktop/Libraries/Adafruit_Python_DHT $ sudo python setup.py install

Installing DHT Library to raspberry pi 4

ImportError: No module named ‘Adafruit_DHT’:

ImportError No module named ‘Adafruit_DHT’ error

You did all the thing properly to install DHT library. But still you are getting error “ImportError: No module named ‘Adafruit_DHT’” while running the code. Here is the solution for this error.

Step 1: Open terminal & navigate to the same folder where you installed the library. In our case it is libraries folder & move to Adafruit_Python_DHT directory.

pi@raspberrypi:~/Desktop/Libraries $ cd Adafruit_Python_DHT

Step 2: This step is important for solving this problem. Install library with Python3.

pi@raspberrypi:~/Desktop/Libraries/Adafruit_Python_DHT $ sudo python3 setup.py install

Run the script or DHT example files again to see if errors are gone. Now you can see, No errors with DHT11/ DHT22 sensor values in shell. This is how you can fix the issue.

No Module named Adafruit DHT- Error solved

Circuit diagram for DHT11/DHT22  to Raspberry Pi 4:

DHT11-DHT22 with Raspberry Pi 4 data logger

Code Raspberry Pi 4 Data Logger:
import Adafruit_DHT
import time

#comment and uncomment the lines below depending on your sensor
#sensor = Adafruit_DHT.DHT11
sensor = Adafruit_DHT.DHT22
#sensor = Adafruit_DHT.AM2302

#DHT pin connects to GPIO 4
sensor_pin = 4

#create a variable to control the while loop
running = True

#new .txt file created with header
file = open('sensor_readings.txt', 'w')
file.write('time and date, temperature (C),temperature (F), humidity\n')

#loop forever
while running:

    try:
        #read the humidity and temperature
        humidity, temperature = Adafruit_DHT.read_retry(sensor, sensor_pin)

        #uncomment the line below to convert to Fahrenheit
        temperature_f = temperature * 9/5.0 + 32

        #sometimes you won't get a reading and
        #the results will be null
        #the next statement guarantees that
        #it only saves valid readings
        if humidity is not None and temperature is not None:

            #print temperature and humidity
            print('Temperature = ' + str(temperature) +','+ 'Temperature Fahrenheit = ' + str(temperature_f) +',' + 'Humidity = ' + str(humidity))
            #save time, date, temperature in Celsius, temperature in Fahrenheit and humidity in .txt file
            file.write(time.strftime('%H:%M:%S %d/%m/%Y') + ', ' + str(temperature) + ', '+ str(temperature_f)+',' + str(humidity) + '\n')
            time.sleep(1)

        else:
            print('Failed to get reading. Try again!')
            time.sleep(1)

    except KeyboardInterrupt:
        print ('Program stopped')
        running = False
        file.close()
Code explanation:

Uncomment the DHT type you are using. Comment out rest of type.

#sensor = Adafruit_DHT.DHT11
sensor = Adafruit_DHT.DHT22
#sensor = Adafruit_DHT.AM2302

DHT pin connects to GPIO 4

sensor_pin = 4

the open() function takes two parameters; filename and mode. First parameter, file name is sensor_readings.txt, it is txt file. Second parameter, ‘w’ opens a file for writing, creates the file if it does not exist and it will overwrite any existing content. As a result it will create and overwrite content every time you run the script. So make sure you change the file name every time you run the code or move the file to other location, otherwise it will overwrite content with new content.

file = open('sensor_readings.txt', 'w')

write the time and date, temperature humidity in file. The \n tells Python to start the next display text on the next line, known as a newline.

file.write('time and date, temperature (C),temperature (F), humidity\n')

It will read the humidity and temperature.

humidity, temperature = Adafruit_DHT.read_retry(sensor, sensor_pin)

This line will convert from temperature in degree Celsius to Fahrenheit.

temperature_f = temperature * 9/5.0 + 32

Sometimes we don’t get readings from DHT11/DHT22 and We don’t want to print the null values, so this line will make sure it will print only valid sensor values.

if humidity is not None and temperature is not None:

Print temperature and humidity values in shell.

print('Temperature = ' + str(temperature) +','+ 'Temperature Fahrenheit = ' + str(temperature_f) +',' + 'Humidity = ' + str(humidity))

log the time, date, temperature in Celsius, temperature in Fahrenheit and humidity in .txt file in every 1 second.

file.write(time.strftime('%H:%M:%S %d/%m/%Y') + ', ' + str(temperature) + ', '+ str(temperature_f)+',' + str(humidity) + '\n')
time.sleep(1)

if sensor value is null, it will print only in shell “failed to get reading”, it will not write any data to .txt file.

else:
print('Failed to get reading. Try again!')
time.sleep(1)

if KeyboardInterrupt triggered, it will stop the loop and close .txt file. For stopping the loop you will need to press CTRL + C on keyboard.

except KeyboardInterrupt:
print ('Program stopped')
running = False
file.close()
Open .txt File/ .CSV File:

After closing program you can change file extension to .csv file or keep it .txt file. Open it in Libre Calc or Microsoft Excel. Finally you can see all the sensor data with time and date. You can use this data to analysis or do whatever your goals for logging this data.

Temperature ChartHumidity Chart

Video:

I hope you learned a lot with this DHT11/DHT22 sensor data logging with Raspberry Pi 4. For latest content. Make sure you subscribe to my YouTube Channel. Till then Keep Learning Keep Making.