How to Interface Servo Motor With an ESP32

Here’s a simple guide with code and wiring connections to interface a servo motor with an ESP32

Components:

  • ESP32
  • Servo Motor
  • External Power Source (for the servo motor, depending on its requirements)
  • Jumper Wires

Wiring Connections:

  1. Servo Motor to ESP32:
    • GND (Servo) -> GND (ESP32)
    • VCC (Servo) -> 5V
    • Signal (Servo) -> GPIO 18 (ESP32)

Code:

#include <ESP32Servo.h>

// Define the servo pin
int servoPin = 18;  // Connect the servo signal wire to GPIO18

// Create a Servo object
Servo myServo;

void setup() {
  // Initialize servo on the defined pin
  myServo.attach(servoPin);
}

void loop() {
  // Sweep the servo from 0 to 180 degrees
  for (int pos = 0; pos <= 180; pos++) {
    myServo.write(pos);              // Move the servo to 'pos' degrees
    delay(15);                        // Wait for the servo to reach the position
  }

  // Sweep the servo from 180 to 0 degrees
  for (int pos = 180; pos >= 0; pos--) {
    myServo.write(pos);              // Move the servo to 'pos' degrees
    delay(15);                        // Wait for the servo to reach the position
  }
}

Explanation:

  • Servo Library: We use the Servo library to easily control the servo motor.
  • Pin 18: You can use any available GPIO pin, but GPIO 18 is chosen in this example.
  • Servo Control: The code sweeps the servo from 0° to 180° and back in a loop.

Notes:

  • Make sure to power the servo properly (use an external power supply if needed).
  • The ESP32 GPIO pins work at 3.3V, but many servos can work at 5V for the signal as well. Just ensure you’re using the correct power level for your servo.

That’s it! You’ve now interfaced a servo motor with the ESP32.