Raspberry Pi Program to Read DHT11 Sensor Data
Adafruit_DHT Python library on Raspberry Pi with Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, pin) to read DHT11 sensor data; for example, humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 4) reads from GPIO pin 4.Examples
How to Think About It
Algorithm
Code
import Adafruit_DHT sensor = Adafruit_DHT.DHT11 pin = 4 # GPIO pin where the sensor is connected humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) if humidity is not None and temperature is not None: print(f"Temp={temperature:.1f}*C Humidity={humidity:.1f}%") else: print("Failed to get reading. Try again!")
Dry Run
Let's trace reading from a DHT11 sensor connected to GPIO pin 4 with example values humidity=60.0 and temperature=24.0.
Import library and set sensor
sensor = Adafruit_DHT.DHT11, pin = 4
Call read_retry function
humidity, temperature = 60.0, 24.0
Check if values are valid
humidity=60.0 is not None and temperature=24.0 is not None
Print results
Output: Temp=24.0*C Humidity=60.0%
| Step | Humidity | Temperature | Output |
|---|---|---|---|
| 1 | - | - | Set sensor and pin |
| 2 | 60.0 | 24.0 | Read sensor values |
| 3 | 60.0 | 24.0 | Check values valid |
| 4 | 60.0 | 24.0 | Print Temp=24.0*C Humidity=60.0% |
Why This Works
Step 1: Importing the sensor library
The Adafruit_DHT library provides functions to communicate with the DHT11 sensor easily.
Step 2: Reading sensor data
The read_retry function tries multiple times to get a stable reading of humidity and temperature from the sensor.
Step 3: Checking and printing results
If the sensor returns valid numbers, the program prints them formatted; otherwise, it shows an error message.
Alternative Approaches
from gpiozero import CPUTemperature from time import sleep # gpiozero does not support DHT11 directly, so use other libraries or custom code print('gpiozero does not support DHT11 directly; use Adafruit_DHT instead.')
# Manual reading requires complex timing and bit reading, not recommended for beginners. print('Manual reading of DHT11 is complex; use Adafruit_DHT library for ease.')
Complexity: O(1) time, O(1) space
Time Complexity
Reading the sensor is a fixed-time operation with a few retries, so it runs in constant time.
Space Complexity
The program uses a small fixed amount of memory for variables and library overhead.
Which Approach is Fastest?
Using the Adafruit_DHT library is fastest and simplest compared to manual bit-banging or unsupported libraries.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Adafruit_DHT library | O(1) | O(1) | Easy and reliable sensor reading |
| Manual bit-banging | O(1) | O(1) | Learning sensor protocol but complex |
| gpiozero library | N/A | N/A | Not suitable for DHT11 directly |