// ultrasonic sensor code
// declaring vairable for duration and distance
float distance;
float duration;
void setup() {
// begins serail communication with the baud rate of 9600 bits
Serial.begin(9600);
// trig pin(triggers the ultrasonic sensor to throw waves)
pinMode(12, OUTPUT);
//echo pin(a singal is sent to the arduino if any obstruction is found in the waves)
pinMode(13, INPUT);
// led
pinMode(2, OUTPUT);
}
void loop() {
digitalWrite(12, HIGH);
delay(10); // wait for 10 microseconds
digitalWrite(12, LOW);
// calculates the duration of the wave after obstruction
duration = pulseIn(13, HIGH);
// calculates the distance between the object that obstructed and the sensor
distance = duration * 0.017;
if(distance < 120)
{
digitalWrite(2, HIGH); // if distance is lower that 120, led is turned on
}
else
{
digitalWrite(2, LOW); // if distance is higher than 120, led is turned off
}
// prints the distance
Serial.print("distance: ");
Serial.print(distance);
Serial.println("cm");
delay(1000);
}
//Module link
// https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json