#define ECHO_PIN 2
#define TRIG_PIN 15
#define LED_RED 5
#define LED_ORANGE 21
#define LED_GREEN 25
#define BUZZER_PIN 19 // Only one buzzer pin
const long interval = 1000; // Interval for distance measurements
const unsigned long buzzDuration = 15000; // 15 seconds
const unsigned long cooldownDuration = 1800000; // 30 minutes
unsigned long lastYellowBuzzTime = 0;
unsigned long lastRedBuzzTime = 0;
unsigned long lastCooldownTime = 0;
bool yellowInCooldown = false;
bool redInCooldown = false;
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(LED_RED, OUTPUT);
pinMode(LED_ORANGE, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT); // Only one buzzer pin
}
void loop() {
static unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
// Trigger the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echo time
int duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.println(distance);
// Check if cooldowns are over
if (yellowInCooldown && currentMillis - lastCooldownTime >= cooldownDuration) {
yellowInCooldown = false;
}
if (redInCooldown && currentMillis - lastCooldownTime >= cooldownDuration) {
redInCooldown = false;
}
if (distance > 200) {
Serial.println("Safe Zone...");
digitalWrite(LED_GREEN, HIGH);
digitalWrite(LED_ORANGE, LOW);
digitalWrite(LED_RED, LOW);
noTone(BUZZER_PIN); // Turn off buzzer
}
else if (distance <= 200 && distance > 100) {
Serial.println("Warning Zone!");
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_ORANGE, HIGH);
digitalWrite(LED_RED, LOW);
// Yellow buzzer logic
if (!yellowInCooldown) {
tone(BUZZER_PIN, 1000); // Activate buzzer
lastYellowBuzzTime = currentMillis;
yellowInCooldown = true; // Start cooldown for yellow
lastCooldownTime = currentMillis;
}
// Stop buzzing after 15 seconds
if (currentMillis - lastYellowBuzzTime >= buzzDuration) {
noTone(BUZZER_PIN); // Stop buzzer after 15 seconds
}
}
else if (distance <= 100) {
Serial.println("Danger Zone! Alarm Activated!!!");
digitalWrite(LED_GREEN, LOW);
digitalWrite(LED_ORANGE, LOW);
digitalWrite(LED_RED, HIGH);
// Red buzzer logic
if (!redInCooldown) {
tone(BUZZER_PIN, 1000); // Activate buzzer for red zone
lastRedBuzzTime = currentMillis;
redInCooldown = true; // Start cooldown for red
lastCooldownTime = currentMillis; // Reset cooldown
}
// Stop buzzing after 15 seconds
if (currentMillis - lastRedBuzzTime >= buzzDuration) {
noTone(BUZZER_PIN); // Stop buzzer after 15 seconds
}
}
}
}