ESP32 Servo Programming Example

This little example demonstrate how simple it is to create a Servo using the build in LED PWM. ESP32 comes with 16 channels of PWM, so in setup we asscociate channel 0 with pin 14 and set pin 14 to OUTPUT. We also set channel 0 to 50Hz 16 bit PWM. The example will sweep 0-180 degrees using GPIO14 as signal.

#define SERVO_PIN 14

void setup()
{
   pinMode(SERVO_PIN,OUTPUT);
   ledcSetup(0,50,16);
   ledcAttachPin(SERVO_PIN,0);
}

void loop()
{
   for(int x=0;x<180;x++)
   {
      SetServoPos(x);
      delay(10);
   }
   delay(100);
}

void SetServoPos(float pos)
{
    uint32_t duty = (((pos/180.0)
              *2000)/20000.0*65536.0) + 1634;
         // convert 0-180 degrees to 0-65536

    ledcWrite(0,duty);
        // set channel to pos
}

A servo signal is a 20ms pulse (50Hz) with the signal as a 500uS – 2500uS width to indicate servo angle.

Leave a Reply