#include <Servo.h>
#include "DHT.h"
#define DHTPIN 15 // Pin where DHT22 data is connected
#define DHTTYPE DHT22
#define ECHO_PIN 4 // HC-SR04 Echo pin
#define TRIG_PIN 5 // HC-SR04 Trigger pin
#define SERVO_PIN 2 // Servo motor control pin
#define BUTTON_PIN 14 // Push button pin
#define LED_PIN 13 // LED pin
DHT dht(DHTPIN, DHTTYPE);
Servo myServo;
void setup() {
Serial.begin(115200);
// Initialize components
dht.begin();
myServo.attach(SERVO_PIN);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // Set button as input with internal pull-up resistor
pinMode(LED_PIN, OUTPUT); // Set LED as output
}
void loop() {
// Read temperature and humidity
float h = dht.readHumidity();
float t = dht.readTemperature();
// Check if readings are valid
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Display data in Serial Monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C ");
// Read ultrasonic sensor (HC-SR04)
long duration, distance;
digitalWrite(TRIG_PIN, LOW); // Clear the trigger
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); // Sets the trigger to HIGH for 10 microseconds
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echo pin and calculate the distance
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration / 2) / 29.1; // Distance in cm
// Print distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Button control
if (digitalRead(BUTTON_PIN) == LOW) {
Serial.println("Button Pressed!");
digitalWrite(LED_PIN, HIGH); // Turn on the LED
myServo.write(90); // Rotate servo to 90 degrees
} else {
digitalWrite(LED_PIN, LOW); // Turn off the LED
myServo.write(0); // Reset servo to 0 degrees
}
delay(2000); // Wait for 2 seconds before next loop
}