Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
Lesson 19: Temperature and Humidity Sensor Module (DHT11)
In this lesson, you will learn how to connect and read data from a DHT11 temperature and humidity sensor using a Raspberry Pi. You will learn how to set up the sensor, read temperature in both Celsius and Fahrenheit, and obtain humidity readings. This project introduces you to working with external sensors, handling real-time data, and basic exception handling in Python.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
|---|---|---|
Universal Maker Sensor Kit |
94 |
You can also buy them separately from the links below.
Component Introduction |
Purchase Link |
|---|---|
Raspberry Pi 5 |
|
Wiring
Note
The kit may contain different versions of the DHT11 module. Please confirm the wiring method according to the module you have.0
Install Library
Note
The adafruit-circuitpython-dht library relies on Blinka, so please ensure that Blinka has been installed. To install libraries, refer to Insatll Adafruit_Blinka (CircuitPython) - Optional.
Before installing the library, please make sure that the virtual Python environment is activated:
source ~/env/bin/activate
Install adafruit-circuitpython-dht library:
pip install adafruit-circuitpython-dht
Code
Note
Please ensure that you have installed the Python library required for running the code according to the “Install Library” steps.
Before running the code, please make sure that you have activated the virtual Python environment with blinka installed. You can activate the virtual environment using a command like this:
source ~/env/bin/activate
Find the code for this lesson in
universal-maker-sensor-kit-main/pi/directory, or directly copy and paste the code below. Execute the code by running the following commands in terminal:python 19_dht11_module.py
import time
import board
import adafruit_dht
# Initial the dht device, with data pin connected to:
dhtDevice = adafruit_dht.DHT11(board.D17)
while True:
try:
# Print the values to the serial port
temperature_c = dhtDevice.temperature
temperature_f = temperature_c * (9 / 5) + 32
humidity = dhtDevice.humidity
print(
"Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(
temperature_f, temperature_c, humidity
)
)
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error
time.sleep(2.0)
Code Analysis
Importing Libraries:
The code begins by importing necessary libraries.
timefor handling delays,boardfor accessing Raspberry Pi GPIO pins, andadafruit_dhtfor interacting with the DHT11 sensor. For more detail about theadafruit_dhtlibrary, please refer to adafruit/Adafruit_CircuitPython_DHT.import time import board import adafruit_dht
Initializing the Sensor:
The DHT11 sensor is initialized with the data pin connected to GPIO 17 of the Raspberry Pi. This setup is crucial for the sensor to communicate with the Raspberry Pi.
dhtDevice = adafruit_dht.DHT11(board.D17)
Reading Sensor Data in a Loop:
The
while Trueloop allows the program to continuously check the sensor for new data.while True:
Try-Except Blocks:
Within the loop, a try-except block is used to handle potential runtime errors. Reading from DHT sensors can often result in errors due to timing issues or sensor quirks.
try: # Sensor data reading code here except RuntimeError as error: # Handling common sensor reading errors print(error.args[0]) time.sleep(2.0) continue except Exception as error: # Handling other exceptions and exiting dhtDevice.exit() raise error
Reading and Printing Sensor Data:
The temperature and humidity are read from the sensor and converted into human-readable formats. The temperature is also converted from Celsius to Fahrenheit.
temperature_c = dhtDevice.temperature temperature_f = temperature_c * (9 / 5) + 32 humidity = dhtDevice.humidity print("Temp: {:.1f} F / {:.1f} C Humidity: {}% ".format(temperature_f, temperature_c, humidity))
Handling Read Errors:
The DHT11 sensor can often return errors, so the code uses a try-except block to handle these. If an error occurs, the program waits for 2 seconds before attempting to read from the sensor again.
except RuntimeError as error: print(error.args[0]) time.sleep(2.0) continue
General Exception Handling:
Any other exceptions that might occur are handled by safely exiting the sensor and re-raising the error. This ensures the program doesn’t continue in an unstable state.
except Exception as error: dhtDevice.exit() raise error
Delay Between Readings:
A 2-second delay is added at the end of the loop to avoid constant polling of the sensor, which can lead to erroneous readings.
time.sleep(2.0)