#define buzz 12
#define trig 21
#define echo 5
#define pot 14
#define soundspeed 0.0356
long duration;
float distance;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(pot, INPUT);
pinMode(buzz, OUTPUT);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
// Serial.println("Hello, ESP32!");
}
void loop() {
int potdist = analogRead(pot);
Serial.print("slider potentinmeter value: ");
Serial.println(potdist);
delay(2000);
// maximum value detected = 4095
// divided into three levels > 1365 for each
// level 1: 0-1364
// level 2: 1365-2729
// level 3: 2730-4095
int lvl1 = 1364;
int lvl2 = 2729;
int lvl3 = 4095;
// Clear the trigPin
//GENERATE TRIGGER PART
digitalWrite(trig, LOW);
delayMicroseconds(10);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Read the duration of the echo signal in microseconds
duration = pulseIn(echo, HIGH);
// Calculate the distance
distance = (duration*soundspeed)/2;
//LEVEL 1 ////////////////////
if(potdist<=lvl1){
if( distance <=100){
tone(buzz, 1000); // Send 1KHz sound signal
delay(1000);
Serial.println("CASE 1: an object within 1 meter detected and in LEVEL 1!");
Serial.print("Distance: ");
Serial.print (distance);
Serial.println(" cm");
delay(1000);
}
else
Serial.println("out of the range");
}
//LEVEL 2 ////////////////////
else if(potdist<=lvl2){
if (distance<=200){
tone(buzz, 1000); // Send 1KHz sound signal
delay(1000);
Serial.println("CASE 2: an object within 2 meter detected and in LEVEL 2!");
Serial.print("Distance: ");
Serial.print (distance);
Serial.println(" cm");
delay(1000);
}
else
Serial.println("out of the range");
}
//LEVEL 3 ////////////////////
else if(potdist<=lvl3 ){
if (distance <=300){
tone(buzz, 1000); // Send 1KHz sound signal
delay(1000);
Serial.println("CASE 3: an object within 3 meter detected and in LEVEL 2!");
Serial.print("Distance: ");
Serial.print (distance);
Serial.println(" cm");
delay(1000);
}
else
Serial.println("out of the range");
}
}