Roborear

How to Control Servo Motors with ESP32 using VS Code & PlatformIO | Robotics for Beginners

A professional YouTube thumbnail featuring a blue SG90 micro servo motor and an ESP32 development board against a vibrant blue background. Large white text reads "Course Control SERVO MOTORS," and a smiling man with glasses is pictured on the right, representing the content creator for Roborear.
A high-angle shot of a desktop workspace showing an ESP32 microcontroller on a transparent breadboard connected to a blue SG90 micro servo. In the background, a large monitor displays VS Code with C++ code specifically written to control servo motor functions using the ESP32Servo library.

The “It Moves!” Moment | Control Servo Motors

There’s something magical about making things move.

LEDs blink. Sensors read. But a servo motor? It physically moves. It turns exactly where you tell it to. It holds position. It obeys commands.

It’s the closest thing to bringing a machine to life.

I remember the first time I made a servo sweep back and forth. I sat there watching it like a kid with a new toy. Back and forth. Back and forth. For ten minutes.

My roommate thought I’d lost my mind.

But that was the moment I realized: I can build robots that actually move.

Today, you’ll learn how to control servo motors with ESP32 using a professional development environment: VS Code with PlatformIO. No outdated tutorials. No Arduino IDE limitations. Just real robotics coding.

What is a Servo Motor? Control Servo Motors?

Unlike regular DC motors that just spin continuously, a servo motor rotates to a specific angle and holds there.

 
 
FeatureRegular DC MotorServo Motor
RotationContinuous0 to 180 degrees (usually)
Position control❌ No✅ Yes (you tell it exactly where to go)
Hold position❌ No✅ Yes (resists external force)
Speed controlYes (PWM)Yes (limited range)
Best forWheels, fansRobot arms, steering, camera gimbals

How a servo works:

Inside the servo:

  • DC motor (spins fast)

  • Gear train (reduces speed, increases torque)

  • Potentiometer (measures current position)

  • Control circuit (compares target vs actual position)

You send a PWM signal (pulse width). The control circuit reads the potentiometer, calculates the difference, and drives the motor until the position matches.

Gemini Generated Image xaqe1lxaqe1lxaqe

What You’ll Need to Control Servo Motors

 
 
ComponentSpecs / NotesPrice (USD)
ESP32 Development BoardAny 30-pin version$5.00 – $7.00
Servo Motor (SG90 or MG995)SG90 (small), MG995 (larger, metal gears)$3.00 – $8.00
Jumper WiresFemale-to-female (servo to ESP32)$2.00 – $4.00
External Power Supply (for larger servos)5V, 2A+ (or 18650 battery)$5.00 – $10.00
Breadboard (optional)400 points$1.00 – $2.00

Total (without external power): ~$11.00 – $21.00 USD

SG90 (small servo): $3-4, works directly from ESP32’s 5V pin for testing

MG995 (large servo): $6-8, requires external 5V power supply (ESP32 can’t provide enough current)

Quick Buy Links (Affiliate)

 
 
ComponentWhere to Find
ESP32 Development BoardAliExpress
SG90 Servo (small)AliExpress
MG995 Servo (large)AliExpress
Potentiometer (10kΩ)AliExpress
Jumper Wires (F-F)AliExpress
External 5V Power SupplyAliExpress
A side-by-side comparison of two popular hobby motors: a small blue plastic SG90 micro servo and a larger black metal-geared MG995 high-torque servo. A metal ruler is placed next to them for scale on a light gray surface, highlighting the physical dimensions needed to control servo motor hardware in robotics.

Wiring to Control Servo Motor with ESP32

To control servo motors, first you need to know the wiring. Servo motors have three wires:

 
 
Wire ColorFunctionConnect to ESP32
Brown or BlackGround (GND)GND pin
RedPower (VCC)For testing: 5V / For large servos: External 5V
Orange or YellowSignal (PWM)GPIO pin (e.g., GPIO 13)

Power note: The ESP32’s 5V pin can power one small servo (SG90) for testing. For any real project or larger servo, use an external 5V power supply.

Setting Up VS Code + PlatformIO to Control Servo Motors

If you haven’t already:

  1. Download Visual Studio Code from code.visualstudio.com

  2. Install PlatformIO extension (click Extensions icon, search “PlatformIO IDE”)

  3. Create a new project:

    • Click the PlatformIO icon (ant)

    • “New Project”

    • Name: Servo_Control

    • Board: DOIT ESP32 DEVKIT V1

    • Framework: Arduino

  4. Install ESP32Servo library:

    • Click PlatformIO icon → Libraries

    • Search “ESP32Servo”

    • Click “Add to Project”

Setting up VS Code and PlatformIO to Control Servo Motors – Robotics for Beginners: Learn ESP32 PlatformIO with VS Code | Blink LED Tutorial

A screenshot of an IDE "Add project dependency" window. The interface shows the official Arduino Servo library by Michael Margolis being added to a project directory. A dropdown menu lists various folders including "Projects\Servo Motors," "Projects\ESP32_UltraSonic," and "ESP32 Car\Normal RC Car Controller," demonstrating the software steps required to control servo motor hardware.

The Code to Control Servo Motors

Basic Sweep to Control Servo Motor (Test Your Servo)

➕➕
filename.cpp
// ============================================================
// ESP32 Servo Sweep - Test your servo
// Moves servo from 0 to 180 degrees and back
// ============================================================

#include <ESP32Servo.h>

// Create servo object
Servo myServo;

// Define the GPIO pin connected to the servo
#define SERVO_PIN 13

void setup() {
  // Attach the servo to the pin
  myServo.attach(SERVO_PIN);
  
  // (Optional) Set minimum and maximum pulse widths (in microseconds)
  // Standard servos use 500-2500µs
  // myServo.setPeriodHertz(50);      // Standard 50Hz servo
  // myServo.attach(SERVO_PIN, 500, 2500);
}

void loop() {
  // Sweep from 0 to 180 degrees
  for (int angle = 0; angle <= 180; angle++) {
    myServo.write(angle);
    delay(15);  // Wait for servo to reach position
  }
  
  // Sweep back from 180 to 0 degrees
  for (int angle = 180; angle >= 0; angle--) {
    myServo.write(angle);
    delay(15);
  }
}

Control Servo Motor with Serial Monitor

➕➕
filename.cpp
// ============================================================
// ESP32 Servo Control via Serial Monitor
// Type a number (0-180) and press Enter
// ============================================================

#include <ESP32Servo.h>

Servo myServo;
#define SERVO_PIN 13

void setup() {
  Serial.begin(115200);
  myServo.attach(SERVO_PIN);
  Serial.println("ESP32 Servo Controller");
  Serial.println("Enter an angle between 0 and 180:");
}

void loop() {
  if (Serial.available()) {
    int angle = Serial.parseInt();
    if (angle >= 0 && angle <= 180) {
      myServo.write(angle);
      Serial.print("Servo moved to: ");
      Serial.print(angle);
      Serial.println(" degrees");
    } else {
      Serial.println("Invalid angle. Please enter 0-180.");
    }
    // Clear the serial buffer
    while (Serial.available()) Serial.read();
  }
}
A close-up of a laptop screen showing the Arduino Serial Monitor window where the value "90" is being entered into the input field. The output log shows a history of angles including 45, 90, and 180 degrees. To the right of the laptop, an SG90 micro servo motor is wired to a microcontroller on a white breadboard, ready to move to the commanded angle.

Control Servo Motor with a Potentiometer

Add a potentiometer to control servo motor manually:

Additional component: 10kΩ potentiometer

Wiring: Potentiometer middle pin → GPIO 34, outer pins → 3.3V and GND

➕➕
filename.cpp
// ============================================================
// ESP32 Servo Controlled by Potentiometer
// Turn the knob = servo moves
// ============================================================

#include <ESP32Servo.h>

Servo myServo;
#define SERVO_PIN 13
#define POT_PIN 34

void setup() {
  myServo.attach(SERVO_PIN);
  Serial.begin(115200);
}

void loop() {
  // Read potentiometer (0-4095)
  int potValue = analogRead(POT_PIN);
  
  // Map to servo angle (0-180)
  int angle = map(potValue, 0, 4095, 0, 180);
  
  // Move servo
  myServo.write(angle);
  
  // Optional: print to Serial Monitor
  Serial.print("Pot: ");
  Serial.print(potValue);
  Serial.print(" | Angle: ");
  Serial.println(angle);
  
  delay(15);  // Smooth movement
}

 

Understanding the Code to Control Servo Motor 

 
 
CodeWhat It Does
#include <ESP32Servo.h>Includes the servo library (ESP32-compatible)
Servo myServo;Creates a servo object named myServo
myServo.attach(SERVO_PIN);Tells the ESP32 which pin the servo is connected to
myServo.write(angle);Moves the servo to the specified angle (0-180)
myServo.writeMicroseconds(1500);Alternative: set pulse width (500-2500µs)
myServo.detach();Releases the pin (turns off signal)

Important: The ESP32Servo library is different from the standard Arduino Servo library. The ESP32 has 16 hardware timers, so you can control up to 16 servos simultaneously without performance issues.

A top-down view of a green cutting mat featuring an ESP32 development board on a white breadboard. Two blue SG90 micro servo motors are secured with tape at the top, with their wiring connected to the ESP32. A white USB cable powers the board, and a hand is visible at the bottom left adjusting a connection. The text "WIRING" is overlaid in the bottom right corner.

Powering Multiple Servos | Control Servo Motor

The ESP32’s 5V pin can only provide about 500mA. This is enough for:

 
 
Servo ConfigurationCan ESP32 Power It?
1 SG90 (small servo)✅ Yes (for testing)
2-3 SG90 (occasional movement)⚠️ Maybe (risk of brownout)
Any MG995 (large servo)❌ No (needs external power)
4+ servos❌ No (needs external power)

For multiple or large servos, use an external 5V power supply:

  • USB phone charger (5V, 2A) – good for 2-3 small servos

  • 18650 battery + boost converter – portable option

  • 5V power supply module – bench power for testing

External power wiring:

  1. Connect external power positive to servo red wires

  2. Connect external power negative to ESP32 GND (common ground!)

  3. Servo signal wires go to ESP32 GPIO pins

Common Servo Problems to Control Servo Motor

 
 
ProblemLikely CauseFix
Servo jitters or twitchesPower supply insufficientUse external power
Servo doesn’t move at allWrong pin or missing attach()Check myServo.attach(pin)
Servo moves only one directionSignal wire looseCheck connection to GPIO pin
Servo buzzes but doesn’t turnMechanical obstruction or low powerClear obstruction, check power
ESP32 resets when servo movesPower brownoutExternal power for servo

platformio.ini Configuration to Control Servo Motor

Your platformio.ini should look like this:

➕➕
filename.cpp
[env:doit_esp32_devkit_v1]
platform = espressif32
board = doit_esp32_devkit_v1
framework = arduino
monitor_speed = 115200
lib_deps = 
    madhephaestus/ESP32Servo@^2.0.3

The lib_deps line tells PlatformIO to automatically download the ESP32Servo library.

Identifying resistor values – How To Read Resistor Color Codes (And Never Burn an LED Again) | 4 Easy Steps


What’s Next to Control Servo Motor? Project Ideas

 
 
ProjectWhat You’ll Need
Robot arm3-4 servos, 3D printed arm frame
Camera pan-tilt2 servos, ESP32-CAM module
RC car steering1 servo, DC motor + driver
Servo walker robot6-8 servos, external power
Analog gauge1 servo, sensor (temperature, distance)

🎥 Watch the Complete Video Tutorial

See servos in action with step-by-step wiring and code explanation:

📺 How to Control Servo Motors with ESP32 using VS Code & PlatformIO | Robotics for Beginners

👉 Don’t forget to Subscribe to Roborear on YouTube for more robotics tutorials every week!

Control servo motor with a joystick – How to Use a Joystick with ESP32: Complete Beginner’s Guide (Wiring + Code)


Your Turn

Servos are the muscles of robotics. They make things move. They make robots real.

Start with the sweep example. Watch the servo move back and forth. Then try the potentiometer control. Then build something.

A robot arm. A pan-tilt camera. A walking robot. Hope you liked the tutorial – Control Servo Motors

The possibilities are endless.

FAQs

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Roborear Logo
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.