SunFounder ESP32 Starter Kit
Once you finish uploading the code, you can see the servo arm rotating in the range 0°~180°.
How it works?
1. Include the library: This line imports the ESP32Servo library, which is required to control the servo motor.
#include <ESP32Servo.h>
2. Define the servo and the pin it is connected to: This section declares a Servo object (myServo) and a constant
integer (servoPin) to represent the pin that the servo motor is connected to (pin 25).
// Define the servo and the pin it is connected to
Servo myServo;
const int servoPin = 25;
3. Define the minimum and maximum pulse widths for the servo: This section sets the minimum and maximum
pulse widths for the servo motor (0.5 ms and 2.5 ms, respectively).
// Define the minimum and maximum pulse widths for the servo
const int minPulseWidth = 500; // 0.5 ms
const int maxPulseWidth = 2500; // 2.5 ms
4. The setup function initializes the servo motor by attaching it to the specified pin and setting its pulse width
range. It also sets the PWM frequency for the servo to the standard 50Hz.
void setup() {
// Attach the servo to the specified pin and set its pulse width range
myServo.attach(servoPin, minPulseWidth, maxPulseWidth);
// Set the PWM frequency for the servo
myServo.setPeriodHertz(50); // Standard 50Hz servo
}
• attach (int pin, int min, int max): This function attaches the servo motor to the spec-
ified GPIO pin and sets the minimum and maximum pulse widths for the servo.
60 Chapter 1. For Arduino User