#include "DHTesp.h"
// Pin Definitions
const int DHT_PIN = 15; // Pin for the DHT sensor
const int TRIGGER_PIN = 27; // Pin for the ultrasonic sensor trigger
const int ECHO_PIN = 14; // Pin for the ultrasonic sensor echo
const int LED_PIN = 12; // Pin for the LED
DHTesp dhtSensor;
void setup() {
Serial.begin(115200);
// Initialize DHT sensor
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
// Initialize pins
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
Serial.println("---ULTRASONIC SENSOR---");
// Trigger the ultrasonic sensor
digitalWrite(TRIGGER_PIN, HIGH);
delay(10); // Trigger pulse duration
digitalWrite(TRIGGER_PIN, LOW);
// Measure the echo response time
int reading = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance (in mm)
int distance = (reading * 0.034 / 2);
// Print distance
Serial.println("Distance: " + String(distance) + " mm");
// Control the LED based on distance
if (distance > 200) {
digitalWrite(LED_PIN, HIGH); // Turn LED on
} else {
digitalWrite(LED_PIN, LOW); // Turn LED off
}
Serial.println("---DHT SENSOR---");
// Get temperature and humidity data
TempAndHumidity data = dhtSensor.getTempAndHumidity();
// Print temperature and humidity
Serial.println("Temp: " + String(data.temperature, 2) + " °C");
Serial.println("Humidity: " + String(data.humidity, 1) + " %");
Serial.println("----------------------");
delay(2000); // Delay before next reading
}