// Servo Control using LEDC PWM - XIAO ESP32-S3
// Servo signal on D2
const int SERVO_PIN = D2;
// LEDC channel and frequency
const int CHANNEL = 0;
const int FREQ = 50; // Standard servo frequency
const int RES = 16; // High resolution for smooth motion
// Servo pulse range (microseconds)
const int MIN_US = 500;
const int MAX_US = 2400;
void setup() {
ledcSetup(CHANNEL, FREQ, RES);
ledcAttachPin(SERVO_PIN, CHANNEL);
}
void writeServo(int angle) {
int us = map(angle, 0, 180, MIN_US, MAX_US);
int duty = (us * ((1 << RES) - 1)) / 20000; // 20ms period
ledcWrite(CHANNEL, duty);
}
void loop() {
for (int angle = 0; angle <= 180; angle++) {
writeServo(angle);
delay(10);
}
for (int angle = 180; angle >= 0; angle--) {
writeServo(angle);
delay(10);
}
}