#define PIN_TRIG 2
#define PIN_ECHO 3
#define buzz 12
void setup() {
Serial.begin(9600);
pinMode(PIN_TRIG, OUTPUT);
pinMode(PIN_ECHO, INPUT );
pinMode(buzz, OUTPUT );
}
void loop(){
Serial.println(Ultrasonic());
int cm = Ultrasonic();
if (cm < 18 && cm != 0){
digitalWrite(buzz, HIGH);
delay(100);
digitalWrite(buzz, LOW);
delay(100);
tone(buzz,300,1000);
}
else{
digitalWrite(buzz,HIGH );
}
}
int Ultrasonic(){
long duration, distance;
digitalWrite(PIN_TRIG,LOW);
delayMicroseconds(2);
digitalWrite(PIN_TRIG,HIGH );
delayMicroseconds(10);
digitalWrite(PIN_TRIG,LOW);
duration = pulseIn(PIN_ECHO,HIGH );
distance = duration / 58;
return distance;
}