#include <Servo.h>
#include <DHT.h>
// === Pin Configuration ===
const int trigPin = 5; // Ultrasonic sensor - trig
const int echoPin = 6; // Ultrasonic sensor - echo
const int servoPin = 9; // Servo motor
const int ldrPin = A0; // LDR sensor
const int ledBuzzerPin = 2; // LED & Buzzer on the same pin
#define DHTPIN 7 // DHT11 data pin
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
// === Threshold Configuration ===
const int lightThreshold = 900; // Light threshold
const float tempThreshold = 30.0; // Temperature threshold (°C)
const int openDistance = 9; // Distance threshold for door open (cm)
// === State Variables ===
long duration;
int distance;
unsigned long lastDetectedTime = 0;
const int closeDelay = 2000; // 2-second delay before closing door
// === Servo Initialization ===
Servo doorServo;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ldrPin, INPUT);
pinMode(ledBuzzerPin, OUTPUT);
dht.begin();
doorServo.attach(servoPin);
doorServo.write(0); // Ensure door is closed at startup
digitalWrite(ledBuzzerPin, LOW);
}
void playFunnyMelody() {
int melody[] = {
262, 294, 330, 262,
392, 330, 440, 392,
523, 494, 587, 494,
330, 392, 440, 392,
262, 330, 294, 262
};
int noteDurations[] = {
150, 150, 300, 150,
150, 300, 200, 200,
400, 300, 250, 250,
200, 250, 200, 300,
250, 200, 150, 400
};
for (int i = 0; i < 9; i++) {
tone(ledBuzzerPin, melody[i]);
delay(noteDurations[i]);
noTone(ledBuzzerPin);
digitalWrite(ledBuzzerPin, HIGH);
delay(50); // LED blink between notes
digitalWrite(ledBuzzerPin, LOW);
}
}
void loop() {
// === Read LDR Value ===
int lightValue = analogRead(ldrPin);
Serial.print("Cahaya: ");
Serial.println(lightValue);
// === Read Temperature ===
float temperature = dht.readTemperature();
Serial.print("Suhu: ");
Serial.print(temperature);
Serial.println(" °C");
// === Read Distance from Ultrasonic ===
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
Serial.print("Jarak: ");
Serial.print(distance);
Serial.println(" cm");
// === Door Open Logic ===
if (temperature > tempThreshold || lightValue < lightThreshold || (distance > 0 && distance < openDistance)) {
doorServo.write(90);
digitalWrite(ledBuzzerPin, HIGH);
playFunnyMelody(); // Play melody when door opens
Serial.println("Pintu Terbuka");
lastDetectedTime = millis();
}
// === Door Close Logic ===
else if (millis() - lastDetectedTime >= closeDelay) {
doorServo.write(0);
digitalWrite(ledBuzzerPin, LOW);
Serial.println("Pintu Tertutup");
}
delay(500);
}