Before you start
To understand how a servo motor works (motor, PWM signal, power), see the reference The servo motor. The details of the code functions are gathered in the reference Servo / ESP32Servo library.
Install the library, then command a servo to a position
Driving a servo motor with Arduino
Install the ESP32Servo library, then drive one or more servo motors to a position, with the Arduino IDE or PlatformIO.
Prerequisites:
Machines/Tools:
In this tutorial, you will install the library and then drive a servo motor to a position from the Arduino IDE or PlatformIO.
Before driving servo motors with Arduino, you need to install a library developed for the ESP32. Here, you can use the ESP32Servo library, created by Kevin Harrington and John K. Bennett. The procedure depends on the environment you use.
Go to the Library Manager tab on the left, search for ESP32Servo in the search bar, then select the library created by Kevin Harrington and John K. Bennett. Then click Install to add it to your project.
In PlatformIO, libraries are declared directly in the project configuration file rather than through a graphical manager. Add ESP32Servo to lib_deps in your platformio.ini file:
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps =
madhephaestus/ESP32Servo
This library works exactly like the classic Arduino Servo library, but it is specially adapted to ESP32-type microcontrollers.
In practice, two functions are enough to get started: attach(pin) to bind the servo to a pin, and write(angle) to give it a position between 0° and 180°.
Here is a simple example that moves the servo from 0° to 180° in a loop:
#include <ESP32Servo.h>
Servo monServo;
void setup() {
monServo.attach(D7); // Attaches the servo to pin D7
}
void loop() {
monServo.write(0); // Moves the servo to 0°
delay(1000); // 1 second pause
monServo.write(180); // Moves the servo to 180°
delay(1000); // 1 second pause
}
You will have to come up with walking sequences, and many others, for your robot. To do this, we will use functions as seen in the previous chapters. The aim from here is therefore to develop walking sequences and test them. For example, you can start by creating a void walk() function that makes the robot walk.
void walk(){
FootLeft.write(90));
LegLeft.write(90);
FootRight.write(90);
Legright.write(90);
delay(1000);
FootLeft.write(45);
LegLeft.write(90);
FootRight.write(90);
Legright.write(90);
//etc...
}
This example is very basic, and you will quickly find that modifying this kind of sequence can become tedious as your project grows more complex.
To go further, it would be worth adding functions that drive several servo motors at different speeds, or that make sequences simpler to create and manage. This will make your code more readable, modular and scalable for more advanced applications.