Code:
/*
* Made by KinCony IoT: https://www.kincony.com
*
* This program reads temperature and humidity values from a DHT11 sensor
* connected to GPIO2 of an ESP32 board, and prints the readings to the serial monitor.
*
* The DHT11 sensor measures the relative humidity and temperature in the environment.
* This data is then read by the ESP32 and displayed in the serial monitor.
*
* Requirements:
* - ESP32 microcontroller
* - DHT11 temperature and humidity sensor
* - DHT sensor library by Adafruit (Install in Arduino IDE)
*
* Connections:
* - DHT11 Data Pin -> GPIO2 on ESP32
* - DHT11 VCC Pin -> 3.3V on ESP32
* - DHT11 GND Pin -> GND on ESP32
*/
#include <DHT.h> // Import the DHT library
// Define the GPIO pin where the DHT11 sensor is connected
#define DHTPIN 2 // DHT11 data pin is connected to GPIO2 on ESP32
// Define the type of DHT sensor being used (DHT11)
#define DHTTYPE DHT11 // DHT11 sensor type
// Create a DHT object to read temperature and humidity
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize serial communication for debugging at a baud rate of 115200
Serial.begin(115200);
Serial.println("DHT11 Sensor Test - Made by KinCony IoT: https://www.kincony.com");
// Initialize the DHT sensor
dht.begin();
}
void loop() {
// Wait for 2 seconds between each reading to ensure stable data
delay(2000);
// Read humidity value from the DHT11 sensor
float humidity = dht.readHumidity();
// Read temperature value from the DHT11 sensor in Celsius
float temperature = dht.readTemperature();
// Check if there was an error reading the data
if (isnan(humidity) || isnan(temperature)) {
// Print error message if the sensor reading failed
Serial.println("Failed to read from DHT11 sensor!");
return; // Exit loop iteration and try again after delay
}
// Print the humidity value to the serial monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("%");
// Print the temperature value to the serial monitor
Serial.print(" Temperature: ");
Serial.print(temperature);
Serial.println("°C");
}