/*
* 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 18 // ESP32 pin GIOP23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 5 // ESP32 pin GIOP22 connected to Ultrasonic Sensor's ECHO pin
float duration_us, distance_cm;
#include <ESP32Servo.h>
const int servoPin = 19;
Servo servo;
void setup() {
servo.attach(servoPin, 500, 2400);
// begin serial port
Serial.begin (9600);
// configure the trigger pin to output mode
pinMode(TRIG_PIN, OUTPUT);
// configure the echo pin to input mode
pinMode(ECHO_PIN, INPUT);
}
int pos=0;
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;
// ligt up led if distance under limit
// print the value to Serial Monitor
servo.write(0);
if(distance_cm <=30){
for (pos = 0; pos <= 180; pos += 1) {
servo.write(pos);
delay(15);
}
delay(5000);
for (pos = 180; pos >= 0; pos -= 1) {
servo.write(pos);
delay(15);
}
delay(10000);
}
// servo.Write(0);
}