const int servoPin = 18; // Servo on GPIO 18
// Converts pulse width (in µs) to 16-bit duty cycle
int pulseWidthToDuty(int pulseWidth) {
return (pulseWidth * 65535) / 20000; // 50 Hz -> 20 ms period
}
void setup() {
ledcAttach(servoPin, 50, 16); // PWM on GPIO 18, 50 Hz, 16-bit resolution
}
void loop() {
// Move servo from 0 to 180 degrees (500 µs to 2500 µs)
for (int pulseWidth = 500; pulseWidth <= 2500; pulseWidth += 100) {
ledcWrite(servoPin, pulseWidthToDuty(pulseWidth));
delay(200);
}
// Move servo back from 180 to 0 degrees
for (int pulseWidth = 2500; pulseWidth >= 500; pulseWidth -= 100) {
ledcWrite(servoPin, pulseWidthToDuty(pulseWidth));
delay(200);
}
}