You will learn how to control a standard miniature servo in this scenario. Standard miniature, so-called “analogue” servo is controlled with a PWM signal of 50Hz with a duty cycle between 1 ms (rotate to 0) and 2 ms (rotate to 180 degrees), where 1.5 ms corresponds to 90 degrees.
A servo has a red arrow presenting the gauge's current position.
The servo is an actuator. It requires a time to operate. So, you should give it time to operate between consecutive changes of the control PWM signal (requests to change its position). Moreover, because of the observation via camera, too quick rotation may not be observable at all depending on the video stream fps. A gap of 2s between consecutive rotations is usually a reasonable choice.
To ease servo control, instead of use of ledc
we will use a dedicated library:
ib_deps = dlloydev/ESP32 ESP32S2 AnalogWrite@^5.0.2
This library requires minimum setup but, on the other hand, supports, i.e. fine-tuning of the minimum and maximum duty cycle as some servos tend to go beyond 1ms and above 2ms to achieve a full 180-degree rotation range. It is usually provided in the technical documentation accompanying the servo.
Rotate the servo to the following angles: 0, 90, 180, 135, 45 and back to 0 degrees.
Check if the servo is in the camera view. The servo is controlled with GPIO 37.
Write your application all in the setup()
function, leaving loop()
empty.
Include servo control library, specific for ESP32 and declare GPIO, minimum and maximum duty cycle values:
#include <Servo.h> #define SRV_PIN 37
MG 90 servos that we use in our lab are specific. As mentioned above, to achieve a full 180-degree rotation range, their minimum and maximum duty cycle timings go far beyond standards. Here, we declare minimum and maximum values for the duty cycle (in microseconds) and a PWM control channel (2):
#define PWMSRV_Ch 2 #define srv_min_us 550 #define srv_max_us 2400
Define a servo controller object:
static Servo srv;
Initialise parameters (duty cycle, channel, GPIO):
srv.attach(SRV_PIN, PWMSRV_Ch,srv_min_us, srv_max_us);
50Hz frequency is standard, so we do not need to configure it.
Rotating a servo is as easy as writing the desired angle to the controller class, e.g.:
srv.write(SRV_PIN,180); delay(2000);
How do I know minimum and maximum values for the timings for servo operation?: Those parameters are provided along with servo technical documentation, so you should refer to them. Our configuration reflects the servos we use (MG90/SG90), and as you can see, it goes far beyond the standard servo rotation control that is a minimum of 1000us and a maximum of 2000us. Using standard configuration, your servo won't rotate at full 180 degrees but at a shorter rotation range.
Observe the red arrow to rotate accordingly. Remember to give the servo some time to operate.