
Arduino Quick Start
The demo board includes one 0-180 degree servo. The servo is normally powered from an independent 5 V supply and controlled through a single PWM signal line. The control signal runs at 50 Hz with a 20 ms period. A HIGH pulse width of 0.5-2.5 ms corresponds to approximately 0-180 degrees of servo travel, with a duty cycle of approximately 2.5%-12.5%.
Connect control pin PIN15 to the servo's SIGNAL input and turn on the independent power supply.
This example uses the Arduino-ESP32 3.x LEDC API to rotate the servo to 0, 90, and 180 degrees in sequence.
#include <M5Unified.h>
constexpr uint8_t SERVO_PIN = 15;
constexpr uint8_t SERVO_CHANNEL = 0; // 仅 Arduino-ESP32 2.x 使用
constexpr uint32_t PWM_FREQ_HZ = 50;
constexpr uint8_t PWM_RES_BITS = 14;
constexpr uint32_t PWM_PERIOD_US = 1000000UL / PWM_FREQ_HZ; // 20000 us
bool servoPwmAttach() {
#if defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR >= 3
// Arduino-ESP32 3.x
return ledcAttach(SERVO_PIN, PWM_FREQ_HZ, PWM_RES_BITS);
#else
// Arduino-ESP32 2.x
ledcSetup(SERVO_CHANNEL, PWM_FREQ_HZ, PWM_RES_BITS);
ledcAttachPin(SERVO_PIN, SERVO_CHANNEL);
return true;
#endif
}
void servoWriteDuty(uint32_t duty) {
#if defined(ESP_ARDUINO_VERSION_MAJOR) && ESP_ARDUINO_VERSION_MAJOR >= 3
ledcWrite(SERVO_PIN, duty);
#else
ledcWrite(SERVO_CHANNEL, duty);
#endif
}
void servoWriteAngle(uint8_t angle) {
if (angle > 180) {
return;
}
const uint32_t pulse_us = 500UL + 2000UL * angle / 180UL;
const uint32_t duty =
(pulse_us * (1UL << PWM_RES_BITS) + PWM_PERIOD_US / 2) /
PWM_PERIOD_US;
servoWriteDuty(duty);
}
void setup() {
M5.begin();
M5.Lcd.setCursor(120, 110, 4);
M5.Lcd.println("SERVO");
if (!servoPwmAttach()) {
M5.Lcd.println("LEDC init failed");
while (true) {
delay(1000);
}
}
}
void loop() {
servoWriteAngle(0); // 0°
delay(1000);
servoWriteAngle(90); // 90°
delay(1000);
servoWriteAngle(180); // 180°
delay(1000);
}After uploading the program, you should see the following result.