Skip to main content

Build. Learn.
Innovate.

Reading Temperature and Humidity with DHT11

Written By:

Published on:

Project Overview

This project teaches how to interface with a digital sensor to read environmental data like temperature and humidity. Students will learn about digital sensor communication protocols.

Educational Goals

  • Understand how digital sensors work.
  • Learn about the DHT11 sensor and its single-wire protocol.
  • Read temperature and humidity data using MicroPython.
  • Introduce basic data handling and display.

Detailed Parts List

  • ESP32 – 1
  • DHT11 Temperature Humidity Sensor Module – 1
  • Breadboard – 1
  • Jumper Wires – Male-to-Male

Circuit Diagram Description

Connect the VCC pin of the DHT11 module to the 3.3V or 5V pin on the ESP32 (check the module’s voltage requirements; it often works with both). Connect the GND pin to GND on the ESP32. Connect the DATA pin of the DHT11 module to a digital GPIO pin on the ESP32. The DHT11 typically has an internal pull-up resistor, but if not, a 10k ohm pull-up resistor between the DATA pin and VCC is recommended.

Software Functionality

The MicroPython code will use a library (often available for MicroPython) to communicate with the DHT11 sensor. The code will initiate a reading from the sensor, wait for the data, and then parse the received data to obtain the temperature and humidity values. These values will be printed to the console.

Web Interface Features

A web interface could display the current temperature and humidity readings, potentially with a timestamp.

Implementation Steps

  • Set up the MicroPython environment on the ESP32 and install the DHT11 library if necessary.
  • Connect the DHT11 sensor circuit as described.
  • Write the MicroPython code to read data from the DHT11.
  • Upload and run the code on the ESP32.
  • Observe the temperature and humidity readings in the console.

Extensions and Challenges

  • Display the readings on an OLED screen.
  • Log temperature and humidity data to a file or send it over Wi-Fi.
  • Trigger an action (e.g., turn on a fan using a relay) based on temperature or humidity thresholds.

Troubleshooting Guide

  • Incorrect or no readings: Double-check the connections to the DHT11 module. Ensure the correct GPIO pin is used in the code and configured correctly. Verify that the DHT11 MicroPython library is installed and imported correctly. The timing of communication with the DHT11 is critical, so ensure the code adheres to the sensor’s protocol (the library should handle this).
  • Checksum errors: This indicates corrupted data transmission. Check connections and ensure proper power supply to the sensor.

Project Code

# This script reads temperature and humidity from a DHT11 sensor
# and displays the readings on an OLED screen.

from machine import Pin, I2C # Import Pin and I2C
import time                   # Import time

# Import DHT11 and SSD1306 libraries.
try:
    import dht
except ImportError:
    print("DHT library not found. Please upload 'dht.py'.")
    class MockDHT11:
        def __init__(self, pin): print(f"MockDHT11 initialized on pin {pin}")
        def measure(self): print("MockDHT11 measure() called. (DHT library not available)")
        def temperature(self): return -999
        def humidity(self): return -999
    dht = type('dht', (object,), {'DHT11': MockDHT11})()

try:
    import ssd1306
except ImportError:
    print("ssd1306.py library not found. Please upload it.")
    class MockSSD1306:
        def __init__(self, width, height, i2c): print(f"MockSSD1306 initialized ({width}x{height}).")
        def fill(self, color): pass
        def text(self, text, x, y, color): pass
        def show(self): print(f"OLED display content not shown (ssd1306 library missing): {text}")
    ssd1306 = type('ssd1306', (object,), {'SSD1306_I2C': MockSSD1306})()


# --- DHT11 Setup ---
dht_pin = 2
sensor = dht.DHT11(Pin(dht_pin))

# --- OLED Setup ---
i2c_sda = 21
i2c_scl = 22
oled_width = 128
oled_height = 32

i2c = I2C(0, sda=Pin(i2c_sda), scl=Pin(i2c_scl), freq=400000)
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)


print("Starting DHT11 monitoring with OLED display...")

# Start an infinite loop to continuously read and display sensor data.
while True:
    try:
        # Perform a measurement.
        sensor.measure()

        # Get the readings.
        temperature_c = sensor.temperature()
        humidity = sensor.humidity()

        # --- Display on OLED ---
        oled.fill(0) # Clear display

        # Display temperature and humidity.
        # With a 128x32 screen, we have about 4 lines of text.
        oled.text("Temp: {:.1f} C".format(temperature_c), 0, 0, 1)
        oled.text("Humidity: {:.1f} %".format(humidity), 0, 16, 1) # Second line

        # Update the OLED display.
        oled.show()

        # Print to console as well.
        print("Temperature: {:.1f}°C, Humidity: {:.1f}%".format(temperature_c, humidity))

    except OSError as e:
        print("Failed to read from DHT11 sensor:", e)
        # Optionally display error on OLED
        oled.fill(0)
        oled.text("DHT11 Error!", 0, 0, 1)
        oled.text(str(e), 0, 16, 1)
        oled.show()


    # Wait before the next reading.
    time.sleep(5) # DHT11 requires at least 1-2 seconds between readings

# This loop will run forever.

# Troubleshooting notes:
# - See troubleshooting notes from Project 6 and Project 2 (OLED).
# - Ensure both dht.py and ssd1306.py are on the ESP32.

STEM Benefits

Science:

  • Meteorology (basic): Concepts of temperature and humidity as atmospheric properties.
  • Sensors: Understanding how the DHT11 measures temperature and humidity (involves thermistor and capacitive humidity sensor principles internally).

Technology:

  • Digital Sensors: Interfacing with a sensor that provides data in a digital format.
  • Communication Protocols (basic): Learning that the DHT11 uses a specific single-wire protocol for data transfer.
  • Data Acquisition: Reading and processing data from a sensor.

Engineering:

  • Sensor Interfacing: Connecting the sensor to the microcontroller.
  • Data Processing: Writing code to interpret the raw data from the sensor according to its protocol.

Mathematics:

  • Data Measurement: Obtaining numerical values for temperature and humidity.
  • Units: Working with units like degrees Celsius/Fahrenheit and percentage relative humidity (%RH).
  • Data Interpretation: Understanding what the measured values mean in the context of environmental conditions.

Projects
ShowCase

Real-World Projects
with Code & Hardware

Insights, Ideas
& How-Tos

Help, Support, and
Common Questions

What types of projects can I find on your website?

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.