#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
// DHT11 connection - connect to PORTD pin 2 (PD2)
#define DHT11_PIN PD2
#define DHT11_PORT PORTD
#define DHT11_DDR DDRD
#define DHT11_PIN_IN PIND
// Function prototypes
uint8_t dht11_read(uint8_t* temperature, uint8_t* humidity);
static uint8_t read_dht11_byte(void);
uint8_t dht11_read(uint8_t* temperature, uint8_t* humidity) {
uint8_t data[5] = {0, 0, 0, 0, 0};
uint8_t i, checksum;
// Initial state
DHT11_DDR |= (1 << DHT11_PIN); // Set as output
DHT11_PORT |= (1 << DHT11_PIN); // Pull high
_delay_ms(100); // Wait for sensor to stabilize
// Send start signal
DHT11_PORT &= ~(1 << DHT11_PIN); // Pull low
_delay_ms(18); // Wait at least 18ms
DHT11_PORT |= (1 << DHT11_PIN); // Pull high
_delay_us(40); // Wait 20-40us
// Set as input to read data
DHT11_DDR &= ~(1 << DHT11_PIN);
// Check sensor response
if ((DHT11_PIN_IN & (1 << DHT11_PIN))) {
return 1; // Sensor not responding
}
_delay_us(80); // Wait for sensor response
if (!(DHT11_PIN_IN & (1 << DHT11_PIN))) {
return 1; // Sensor not responding
}
_delay_us(80);
// Read 40 bits (5 bytes)
for (i = 0; i < 5; i++) {
data[i] = read_dht11_byte();
}
// Verify checksum
checksum = data[0] + data[1] + data[2] + data[3];
if (checksum != data[4]) {
return 1; // Checksum error
}
*humidity = data[0]; // Integer part of humidity
*temperature = data[2]; // Integer part of temperature
return 0; // Success
}
static uint8_t read_dht11_byte(void) {
uint8_t i, result = 0;
for (i = 0; i < 8; i++) {
// Wait for pin to go high
while (!(DHT11_PIN_IN & (1 << DHT11_PIN)));
_delay_us(30);
// Check if bit is 1 or 0
if (DHT11_PIN_IN & (1 << DHT11_PIN)) {
result |= (1 << (7 - i));
}
// Wait for pin to go low
while (DHT11_PIN_IN & (1 << DHT11_PIN));
}
return result;
Serial.print(": result");
}
int main(void) {
uint8_t temperature, humidity;
Serial.begin(9600);
// Initialize ports
DHT11_DDR |= (1 << DHT11_PIN); // Set as output initially
DHT11_PORT |= (1 << DHT11_PIN); // Pull high
while (1) {
if (dht11_read(&temperature, &humidity) == 0) {
// Data read successfully
// Add your code here to use temperature and humidity values
// For example, send to UART or display on LCD
}
_delay_ms(2000); // Wait 2 seconds before next reading
}
return 0;
}