// Define pin numbers
const int trigPin = 9;
const int echoPin = 10;
const int greenLedPin = 5; // New Green LED Pin
const int redLedPin = 6; // New Red LED Pin
const int buzzerPin = 7; // New Buzzer Pin
// Define variables
long duration;
int distance;
// Define safety threshold (half of max 400cm range)
const int safetyThreshold = 200;
void setup() {
// Set pin modes for ultrasonic sensor
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Set pin modes for new alert hardware
pinMode(greenLedPin, OUTPUT);
pinMode(redLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
// Initialize serial communication
Serial.begin(9600);
Serial.println("Ultrasonic Distance Sensor with Alerts Initialized!");
}
void loop() {
// Clear the trigPin by pulling it LOW
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by sending a 10-microsecond HIGH pulse
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin; returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.0343 / 2;
// Print the distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if something is in the half-range zone
// Note: pulseIn can return 0 if out of range, so we ensure distance > 0
if (distance > 0 && distance <= safetyThreshold) {
// ALERT CONDITION: Object is close!
digitalWrite(redLedPin, HIGH); // Turn ON Red LED
digitalWrite(greenLedPin, LOW); // Turn OFF Green LED
digitalWrite(buzzerPin, HIGH); // Turn ON Buzzer
} else {
// NORMAL CONDITION: Path is clear
digitalWrite(redLedPin, LOW); // Turn OFF Red LED
digitalWrite(greenLedPin, HIGH); // Turn ON Green LED
digitalWrite(buzzerPin, LOW); // Turn OFF Buzzer
}
// Wait half a second before the next reading
delay(500);
}