#define SWITCH_PIN 14 // Pin connected to the NO pin of the switch
#define LED_PIN 33 // Pin connected to the LED
#define BUZZER_PIN 32 // Pin connected to the buzzer
#define TRIG_PIN 25 // Ultrasonic sensor Trig pin
#define ECHO_PIN 26 // Ultrasonic sensor Echo pin
#define MAX_DISTANCE 300 // Maximum distance in cm (300 cm = 3 meters)
#define RESET_DISTANCE 50 // Reset distance in cm (50 cm = 0.5 meters)
// Function to measure distance using HC-SR04
float measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = (duration * 0.034) / 2; // Convert to cm
return distance;
}
void setup() {
pinMode(SWITCH_PIN, INPUT_PULLUP); // Use pull-up for switch stability
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(LED_PIN, LOW); // Initially, turn off LED
digitalWrite(BUZZER_PIN, LOW); // Initially, turn off buzzer
Serial.begin(115200); // For debugging
}
void loop() {
int switchState = digitalRead(SWITCH_PIN);
// If the switch is OFF, turn off LED and buzzer, then skip the loop
if (switchState == LOW) {
digitalWrite(LED_PIN, LOW);
digitalWrite(BUZZER_PIN, LOW);
return; // Exit the loop
}
// If the switch is ON
digitalWrite(LED_PIN, HIGH); // Turn on LED to indicate the system is active
// Measure the distance
float distance = measureDistance();
Serial.print("Distance: ");
Serial.println(distance);
// Logic for the buzzer behavior
if (distance >= MAX_DISTANCE) {
// Dog is far away (300 cm or more), beep every second
digitalWrite(BUZZER_PIN, HIGH);
delay(500); // Buzzer ON for 500ms
digitalWrite(BUZZER_PIN, LOW);
delay(500); // Buzzer OFF for 500ms
} else if (distance <= RESET_DISTANCE) {
// Dog is close (50 cm or less), turn off the buzzer
digitalWrite(BUZZER_PIN, LOW);
} else {
// Keep the buzzer off if the distance is between 50 and 300 cm
digitalWrite(BUZZER_PIN, LOW);
}
}