// defines pins numbers
const int trigPin = 2;
const int echoPin = 3;
const int buzzer = 4;
const int ledPin = 5;
// defines variables
long duration;
int distance;
int safetyDistance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(buzzer, OUTPUT); // Buzzer pin
pinMode(ledPin, OUTPUT); // LED pin
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.0343 / 2; // Conversion to cm
// Safety distance check
safetyDistance = distance;
if (safetyDistance <= 200) {
tone(buzzer, 1000); // Generate a 1 kHz tone
digitalWrite(ledPin, HIGH); // Turn on LED
} else {
noTone(buzzer); // Stop the tone
digitalWrite(ledPin, LOW); // Turn off LED
}
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Short delay to stabilize the loop
delay(200);
}