avr-dht

DHT11 / AM2302 (DHT22) temperature and humidity sensor driver for AVR microcontrollers.

ci

Features

Supported MCUs and toolchain

Any AVR with PORTx / DDRx / PINx registers.
Verified on ATmega328P (default, DIP-28) and ATmega32.
Toolchain: avr-gcc with -std=gnu99.
Default F_CPU is 8 MHz; the datasheet windows are generous enough that anything from 1 MHz upwards works unmodified.

Wiring (default demo, ATmega328P DIP-28)

Signal Device pin AVR pin DIP-28 Config Description
DATA DHT22 pin 2 PD2 4 #define DHT_PIN D, 2 Bidirectional data line; 4.7 kOhm pull-up to VDD (5.1 kOhm for AM2302 on long cables)
VDD DHT22 pin 1 VCC 7 — 3.3-5.5 V
GND DHT22 pin 4 GND 8 — Common ground
UART TX SerialTerm RX PD1 3 — Demo prints readings at 9600 baud, 8N1

DHT22 pin 3 (NC) is not connected. If you are using a 3-pin breakout board, the pull-up resistor is already on the board.

Quick start

#include <util/delay.h>
#include "dht.h"

int main(void)
{
    // Idle the data pin and wait for the sensor to settle.
    dht_init();

    dht_reading reading;
    while (1) {
        // Trigger a read; status carries any timeout, checksum, or range error.
        dht_status status = dht_read(&reading);
        if (status == DHT_OK) {
            // reading.temperature_celsius_x10 == 257 means 25.7 C.
            // reading.humidity_percent_x10    == 658 means 65.8 %.
        }

        // DHT22: minimum 2 s between reads. DHT11: minimum 1 s.
        for (uint8_t i = 0; i < 20; i++) {
            _delay_ms(100);
        }
    }
}

Need Fahrenheit or Kelvin? One line each.

int16_t fahrenheit_x10 = (int16_t)((int32_t)reading.temperature_celsius_x10 * 9 / 5 + 320);
int16_t kelvin_x10     = (int16_t)(reading.temperature_celsius_x10 + 2732);

API

dht_init

dht_read

dht_read_raw

dht_decode_frame

dht_status

Sensor type constants

Configuration

DHT_TYPE

DHT_PIN

DHT_ATOMIC

DHT_INIT_DELAY_MS

Memory usage

Build.ps1 writes build/size.txt;
Before/after comparison on ATmega32 (v1’s historical target).

Build Flash / RAM
v1 (ATmega32, -Os) did not build
v2 (ATmega32, -Os) 2698 B / 0 B

Build, test, simulate

.\Build.ps1
.\Build.ps1 -AllMcus -DebugBuild
.\Build.ps1 -Test
.\Simulate.ps1
.\Simulate.ps1 -NoLaunch

Build.ps1 and Simulate.ps1 install the AVR toolchain (and host gcc for -Test, SimulIDE for .\Simulate.ps1) into a shared per-user cache folder on first run — no admin, no system-wide PATH changes.
Pass -RemoveTools to uninstall what the scripts installed when the run ends.
Pass -NoInstall to fail loudly instead if the tools are missing.

Limitations

Changelog and license

See CHANGELOG.md.
MIT — see LICENSE.