// Include the DHT sensor library (Adafruit DHT library)
#include "DHT.h"
// Define the digital pin connected to the DATA pin of DHT22
#define DHTPIN 10 // Arduino UNO digital pin 10
// Define the type of DHT sensor
#define DHTTYPE DHT22 // Using DHT22 sensor
// Create a DHT object with specified pin and sensor type
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Start serial communication at 9600 baud rate
Serial.begin(9600);
// Initialize the DHT sensor
dht.begin();
}
void loop() {
// Wait 2 seconds between readings
// DHT22 requires minimum 2 seconds delay
delay(2000);
// Read temperature value in Celsius
float temperature = dht.readTemperature();
// Read humidity value in percentage
float humidity = dht.readHumidity();
// Check if sensor reading failed
// isnan() checks for invalid (Not a Number) values
if (isnan(temperature) || isnan(humidity)) {
// Print error message if reading fails
Serial.println("Failed to read from DHT sensor!");
return;
}
// Print temperature value
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
// Print humidity value
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}