// 1. Include the necessary library for the DHT sensor
#include <DHT.h>
// 2. Define hardware connections and sensor type
#define DHTPIN 4 // GPIO pin connected to the DHT22 DATA pin
#define DHTTYPE DHT22 // Specify the sensor type (DHT22/AM2302)
// 3. Instantiate the DHT sensor object
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize serial communication for debugging output
Serial.begin(115200);
// Initialize the DHT sensor hardware
dht.begin();
Serial.println("Smart Campus: DHT22 Sensor Initialized");
Serial.println("--------------------------------------");
}
void loop() {
// 4. Read temperature (Celsius) and humidity (Percentage)
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// 5. CRITICAL: Data Validation (Error Checking)
// If the sensor disconnects or fails, it returns NaN (Not a Number).
// We MUST catch this to prevent feeding garbage data to our future AI models
if (isnan(temperature) || isnan(humidity)) {
Serial.println("ERROR: Sensor read failure! Check wiring.");
return; // Exit the current loop iteration and try again
}
// 6. Display valid data
Serial.print("Temp: ");
Serial.print(temperature);
Serial.print(" °C | Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// 7. Blocking delay (Wait 2 seconds before next reading)
delay(2000);
}