#define TRIG_PIN 26
#define ECHO_PIN 25
#define BUZZER_PIN 18
#define LED_PIN 5
#define DISTANCE_THRESHOLD 50 // centimeters
// variables will change:
float duration_us, distance_cm;
void setup() {
Serial.begin(9600);
pinMode (TRIG_PIN, OUTPUT);
pinMode (ECHO_PIN, INPUT);
pinMode (BUZZER_PIN, OUTPUT);
pinMode (LED_PIN, OUTPUT);
}
void loop() {
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds (10);
digitalWrite (TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
duration_us = pulseIn (ECHO_PIN, HIGH);
// calculate the distance
distance_cm= 0.017 * duration_us;
if (distance_cm< DISTANCE_THRESHOLD)
digitalWrite(BUZZER_PIN, HIGH); // turn on Piezo Buzzer
else
digitalWrite(BUZZER_PIN, LOW); // turn off Piezo Buzzer
digitalWrite(LED_PIN, HIGH); // turn off Piezo Buzzer Serial.print ("distance: ");
Serial.print ("distance: ");
Serial.print (distance_cm);
Serial.println(" cm");
delay(500);
}