/*
Project: Ultrasonic Alarm
Description: Lights an LED if an object gets too close.
Creation date: 5/15/23
Author: AnonEngineering
License: Beerware
Originally from:
This ESP32 code is created by esp32io.com
This ESP32 code is released in the public domain
For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-ultrasonic-sensor
*/
#define TRIG_PIN 23 // ESP32 pin GPIO23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 22 // ESP32 pin GPIO22 connected to Ultrasonic Sensor's ECHO pin
#define LED_PIN 21 // ESP32 pin GPIO21 connected to LED
const int ALARM_DISTANCE = 200; // set alarm distance in cm here
unsigned long duration_us = 0;
float distance_cm = 0.0;
float last_distance_cm = 0.0;
void setup()
{
// begin serial port
Serial.begin (9600);
pinMode(LED_PIN, OUTPUT);
// configure the trigger pin to output mode
pinMode(TRIG_PIN, OUTPUT);
// make sure trigger is LOW
digitalWrite(TRIG_PIN, LOW);
// configure the echo pin to input mode
pinMode(ECHO_PIN, INPUT);
}
void loop()
{
// generate 10-microsecond pulse to TRIG pin
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;
// print - if the distance has changed
if (distance_cm != last_distance_cm) {
last_distance_cm = distance_cm; // save the current distance
// print the value to Serial Monitor
Serial.print("Distance is now ");
Serial.print(distance_cm, 1); // print only 1 decimal place
Serial.println(" cm. ");
// light up led if distance under limit
if (distance_cm < ALARM_DISTANCE - 1)
{
digitalWrite(LED_PIN, HIGH);
Serial.print("Distance < ");
}
else
{
digitalWrite(LED_PIN, LOW);
Serial.print("Distance > ");
}
Serial.print(ALARM_DISTANCE);
Serial.println(" cm.");
Serial.println();
}
delay(50); // slow measurements a little
}