#define TRIG_PIN 18
#define ECHO_PIN 19
#define LED_PIN 23
#define BUZZER_PIN 32
float measureDistance(){
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH);
float distance = duration*0.034/2;
return distance;
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN,OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
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(250);
}