#include <Arduino.h>
#include <ESP32Servo.h> // Ensure this is the correct include
#define TRIG_PIN 5
#define ECHO_PIN 18
#define SERVO_PIN 19
Servo myServo;
void init_ultrasonic() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(TRIG_PIN, LOW);
}
long get_distance() {
long duration, distance;
// Clear the TRIG_PIN
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
// Set the TRIG_PIN high for 10 microseconds
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the ECHO_PIN, pulseIn() returns the duration (microseconds) of the pulse
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance
distance = duration * 0.0343 / 2;
return distance;
}
void setup() {
Serial.begin(115200);
init_ultrasonic();
myServo.attach(SERVO_PIN);
myServo.write(90); // Initialize the servo to stop (assuming 90 is the stop position for a continuous rotation servo)
}
void loop() {
long distance = get_distance();
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Rotate the servo in one direction
myServo.write(180); // Assuming 180 causes the servo to rotate in one direction
delay(1000); // Adjust the delay as needed to achieve a 360-degree rotation
myServo.write(90); // Stop the servo
delay(500); // Wait for half a second
// Rotate the servo in the opposite direction
myServo.write(0); // Assuming 0 causes the servo to rotate in the opposite direction
delay(1000); // Adjust the delay as needed to achieve a 360-degree rotation
myServo.write(90); // Stop the servo
delay(500); // Wait for half a second
}