#include <ESP32Servo.h>
Servo myservo; // Create servo object to control a servo
int pos = 0; // Variable to store the servo position
int servoPin = 13; // Servo GPIO pin
int led1 = 17; // LED1 GPIO pin
int led2 = 18; // LED2 GPIO pin
void setup() {
// Allow allocation of all timers
ESP32PWM::allocateTimer(0);
ESP32PWM::allocateTimer(1);
ESP32PWM::allocateTimer(2);
ESP32PWM::allocateTimer(3);
myservo.setPeriodHertz(50); // Standard 50 Hz servo
myservo.attach(servoPin, 500, 2400); // Attach the servo on pin 13 with pulse width settings
// Set LED pins as output
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
// Initialize Serial Monitor
Serial.begin(9600);
while (!Serial); // Wait for Serial to initialize
Serial.println("Servo control initialized. Sweeping from 0 to 180 degrees...");
}
void loop() {
// Sweep from 0 to 180 degrees
for (pos = 0; pos <= 180; pos += 1) {
myservo.write(pos); // Move servo to the position in variable 'pos'
Serial.print("Servo position: ");
Serial.println(pos); // Output current position to Serial Monitor
// Control LEDs based on servo position
if (pos >= 0 && pos <= 90) {
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
} else {
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
}
delay(15); // Wait for servo to reach the position
}
// Sweep from 180 to 0 degrees
for (pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos); // Move servo to the position in variable 'pos'
Serial.print("Servo position: ");
Serial.println(pos); // Output current position to Serial Monitor
// Control LEDs based on servo position
if (pos >= 0 && pos <= 90) {
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
} else {
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
}
delay(15); // Wait for servo to reach the position
}
}