DHT12 sensor driver
This module provides a MicroPython driver for the Aosong DHT12 temperature and humidity sensor, which communicates over I2C. It includes classes and methods for reading temperature and humidity data from the sensor.
Classes
DHTBaseI2C
: Base class for handling low-level I2C communication with the DHT12 sensor.DHT1
: Extends DHTBaseI2C to provide methods for reading temperature and humidity values.
Attributes
SENSOR_ADDR
: The default I2C address (0x5c) of the DHT12 sensor.
Example
from dht12 import DHT12
from machine import I2C, Pin
# Initialize I2C interface
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# Create an instance of the DHT12 sensor
sensor = DHT12(i2c)
# Read and print temperature and humidity values
temperature, humidity = sensor.read_values()
print(f"Temperature: {temperature} °C, Humidity: {humidity} %")
Modification history
2024-11-11 : Added Sphinx comments.
2024-11-02 : Added read_values method.
2023-11-10 : Added scan method.
- class dht12.DHT12(i2c, addr=92)[source]
Bases:
DHTBaseI2C
- humidity()[source]
Calculates and returns the humidity as a floating-point value, using data previously read into the buffer (self.buf) by the measure method.
- Returns:
The current humidity as a percentage.
- Example:
sensor = DHT12(i2c) sensor.measure() # Read data from sensor humidity = sensor.humidity() print(f"Humidity: {humidity} %")
- read_values()[source]
Read temperature and humidity from the sensor.
- Returns:
A tuple containing the temperature (float) and humidity (float) values.
- temperature()[source]
Calculates and returns the temperature in degrees Celsius as a floating-point value, using data stored in the buffer (self.buf) by the measure method. It interprets both positive and negative temperatures.
- Returns:
The current temperature in degrees Celsius.
- Example:
sensor = DHT12(i2c) sensor.measure() # Read data from sensor temperature = sensor.temperature() print(f"Temperature: {temperature} °C")
- class dht12.DHTBaseI2C(i2c, addr=92)[source]
Bases:
object
- measure()[source]
Reads 5 bytes of data from the DHT12 sensor’s memory and performs a checksum validation to ensure data integrity. The retrieved data is stored in the buffer (self.buf). If the checksum validation fails, an exception is raised.
- Raises:
Exception – If the checksum validation fails, indicating potential data corruption.
- Example:
sensor = DHT12(i2c) try: sensor.measure() print("Data read successfully.") except Exception as e: print("Checksum error:", e)
- scan()[source]
Checks if the DHT12 sensor is available on the I2C bus by scanning for its specified address (SENSOR_ADDR). If the sensor is not found, it raises an exception.
- Raises:
Exception – If the sensor address (SENSOR_ADDR) is not detected on the I2C bus.
- Example:
sensor = DHT12(i2c) try: sensor.scan() print("Sensor detected.") except Exception as e: print(e)