#include <Servo.h>
#define trigPin 9 // Trig pin of HC-SR04
#define echoPin 10 // Echo pin of HC-SR04
#define relayPin 5 // Relay control pin (connected to Arduino)
#define servoPin 6 // Servo motor signal pin
#define eyeBlinkButton 7 // Eye blink button pin
#define buzzer 8 // Buzzer pin
Servo myServo; // Create Servo object
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(relayPin, OUTPUT);
pinMode(eyeBlinkButton, INPUT_PULLUP); // Use internal pull-up resistor
pinMode(buzzer, OUTPUT);
myServo.attach(servoPin); // Attach servo to pin 6
myServo.write(0); // Set servo to 0° initially
digitalWrite(relayPin, LOW); // Ensure relay is off initially
digitalWrite(buzzer, LOW); // Ensure buzzer is off initially
Serial.begin(9600);
}
void loop() {
detectObstacle(); // Function to handle obstacle detection
checkEyeBlink(); // Function to handle eye blink detection
}
// Function to detect obstacle using ultrasonic sensor
void detectObstacle() {
long duration;
float distance;
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Receive echo
duration = pulseIn(echoPin, HIGH);
distance = (duration * 0.0343) / 2; // Convert time to distance in cm
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance <= 20 && distance > 0) { // If obstacle is within 20 cm
digitalWrite(relayPin, HIGH); // Activate relay
myServo.write(90); // Turn servo to 90°
Serial.println("Obstacle detected! Servo rotated & Relay activated.");
} else {
digitalWrite(relayPin, LOW); // Deactivate relay
myServo.write(0); // Reset servo to 0°
Serial.println("Path Clear! Servo at 0° & Relay deactivated.");
}
delay(500); // Short delay to stabilize readings
}
// Function to check eye blink button press and activate buzzer
void checkEyeBlink() {
if (digitalRead(eyeBlinkButton) == LOW) { // If button is pressed
Serial.println("Buzzer ON");
digitalWrite(buzzer, HIGH); // Turn on buzzer
unsigned long buzzerStartTime = millis(); // Record start time
while (millis() - buzzerStartTime < 4000) {
// Keep buzzer on for 4 seconds without blocking other processes
}
digitalWrite(buzzer, LOW); // Turn off buzzer
Serial.println("Buzzer OFF");
// Wait for button release with debounce
while (digitalRead(eyeBlinkButton) == LOW);
delay(50); // Small debounce delay
}
}