const int trig = 33;
const int echo = 25;
const int buzzer = 32;
const int btn = 35;
long duration;
int distance;
int threshold;
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
pinMode(buzzer, OUTPUT);
pinMode(btn, INPUT);
Serial.begin(9600);
}
void loop() {
// Gets the Threshold
int press = digitalRead(btn);
if (press == HIGH){
threshold = distance;
Serial.println("press");
}
// Clears the trigPin
digitalWrite(trig, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echo, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Checks the Threshold
if (distance <= threshold){
digitalWrite(buzzer, HIGH);
}
else{
digitalWrite(buzzer, LOW);
}
Serial.print("Distance: ");
Serial.println(distance);
}