#define TRIGGER_PIN 18
#define ECHO_PIN 5
#define LED_PIN 23
#define BUZZER_PIN 32
float measureDistance(){
digitalWrite(TRIGGER_PIN,LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN,HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN,LOW);
long duration = pulseIn(ECHO_PIN,HIGH);
float distance = duration*0.034/2;
return distance;
}
void setup() {
pinMode(LED_PIN,OUTPUT);
pinMode(TRIGGER_PIN,OUTPUT);
pinMode(BUZZER_PIN,OUTPUT);
pinMode(ECHO_PIN,INPUT);
Serial.begin(9600);
}
void loop() {
float distance = measureDistance();
if (distance<50){
digitalWrite(LED_PIN,LOW);
tone(BUZZER_PIN,500);
}
else{
digitalWrite(LED_PIN,HIGH);
noTone(BUZZER_PIN);
}
Serial.print("Distance :");
Serial.print(distance);
Serial.println(" cm");
delay(1000);
}