Programming
Programming
The Arduino IDE can be used to write, compile, and upload the program to the ESP32. The program begins by defining the DHT sensor type and the GPIO pin connected to its DATA line. During startup, the ESP32 initializes the DHT sensor so it is ready to collect temperature and humidity measurements.
The program then periodically requests data from the DHT sensor. It reads both temperature and relative humidity values and stores them in variables. A suitable delay between readings helps ensure that the sensor is not queried too frequently.
Before using the measurements, the ESP32 checks whether the returned sensor data is valid. If the sensor fails to provide a valid reading, the program can display an error message instead of using incorrect values. This makes the monitor more reliable and easier to troubleshoot.
After obtaining valid measurements, the ESP32 displays the temperature and humidity in the Arduino IDE Serial Monitor. The program can also be extended to create a simple Wi-Fi web dashboard, allowing a phone or computer on the same network to view the readings through a web browser.
#include <DHT.h>
// DHT sensor configuration
#define DHT_PIN 4
#define DHT_TYPE DHT11 // Change to DHT22 if using a DHT22
DHT dht(DHT_PIN, DHT_TYPE);
void setup() {
Serial.begin(115200);
// Initialize DHT sensor
dht.begin();
Serial.println("Temperature & Humidity Monitor");
Serial.println("--------------------------------");
}
void loop() {
// Read humidity
float humidity = dht.readHumidity();
// Read temperature in Celsius
float temperature = dht.readTemperature();
// Check whether the readings are valid
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Error: Failed to read from DHT sensor!");
delay(2000);
return;
}
// Display measurements
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.println("-----------------------------");
// Wait before taking the next reading
delay(2000);
}