#include <ESP32Servo.h>
// Define pins
const int trigPin = 14;
const int echoPin = 12;
const int ledPin = 13;
Servo myServo;
// Variables for distance measurement
long duration;
int distance;
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Set pin modes
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
// Attach the servo to pin 11
myServo.attach(15);
}
void loop() {
// Sweep the servo from 0 to 180 degrees
for (int pos = 0; pos <= 180; pos += 1) {
myServo.write(pos);
delay(15);
measureDistance();
}
// Sweep the servo from 180 to 0 degrees
for (int pos = 180; pos >= 0; pos -= 1) {
myServo.write(pos);
delay(15);
measureDistance();
}
}
void measureDistance() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Set the trigPin on HIGH state for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
// Turn on the LED if an object is within 50 cm
if (distance < 50) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
servo1:GND
servo1:V+
servo1:PWM
ultrasonic1:VCC
ultrasonic1:TRIG
ultrasonic1:ECHO
ultrasonic1:GND
led1:A
led1:C
r1:1
r1:2