Code -
int trigger_pin = 2;
int echo_pin = 3;
int buzzer_pin = 11;
int time;
int distance;
void setup ( ) {
Serial.begin (9600);
pinMode (trigger_pin, OUTPUT);
pinMode (echo_pin, INPUT);
pinMode (buzzer_pin, OUTPUT);
}
void loop ( ) {
digitalWrite (trigger_pin, HIGH);
delayMicroseconds (10);
digitalWrite (trigger_pin, LOW);
time = pulseIn (echo_pin, HIGH);
distance = (time * 0.034) / 2;
if (distance <= 15)
{
Serial.println (" object is near ");
Serial.print (" Distance= ");
Serial.println (distance);
digitalWrite (buzzer_pin, HIGH);
delay (1000); }
else {
Serial.println (" object is far ");
Serial.print (" Distance= ");
Serial.println (distance);
digitalWrite (buzzer_pin, LOW);
delay (1000);
}
}
Secondly, we will make the circuit.
1.Connections : Ultrasonic sensor
- Gnd to Gnd
- Vcc to 3.3 v
- Echo to digital pin 3
- trig to digital pin 2
2. Connections : Buzzer
- Negative to Gnd
- Positive to digital pin 11
3.Connections : Battery
- Negative : Gnd
- Positive : 5v
After completing the connections as per the circuit diagram attach the circuit to the band .