#define trigPin 2 // TRIG pin of ultrasonic sensor
#define echoPin 3 // ECHO pin of ultrasonic sensor
#define buzzerPin A3 // pin for the buzzer
#define motorPin 4 //pin for the vibration motor
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(motorPin, OUTPUT);
}
void loop() {
long duration, distance;
// Clear the trig pin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Send 10us pulse to trigger the ultrasonic sensor
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo signal
duration = pulseIn(echoPin, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If an object is detected within a range of (30cm), activate the buzzer and vibration motor
if (distance > 0 && distance < 30) {
tone(buzzerPin, 100); // atart the buzzer tone at 1000Hz
digitalWrite(motorPin, HIGH); // activate the vibration motor
} else {
noTone(buzzerPin); // stop the buzzer tone
digitalWrite(motorPin, LOW); // deactivate the vibration motor
}
delay(0); // duration time before taking another measurement, i put Zero to make it no delay
}