Skip to main content

Build. Learn.
Innovate.

Controlling a Servo Motor

Written By:

Published on:

Project Overview

This project teaches how to control the position of a servo motor, which is useful for tasks requiring precise angular movement. Students will learn about the control signal required for servo motors.

Educational Goals

  • Understand how servo motors work and their applications.
  • Learn about the control signal used for servo motors (PWM with specific pulse lengths).
  • Control the angular position of a servo motor using MicroPython.

Detailed Parts List

  • ESP32 – 1
  • Sg90 9g Micro Servo Motor – 1
  • Breadboard – 1
  • Jumper Wires – Male-to-Male

Circuit Diagram Description

Connect the brown wire of the SG90 servo to the GND pin on the ESP32. Connect the red wire to the 5V or 3.3V pin on the ESP32 (5V is typical for the SG90, ensure your ESP32 can supply enough current, or use an external 5V power supply). Connect the orange or yellow wire (control signal) to a PWM-capable GPIO pin on the ESP32.

Software Functionality

The MicroPython code will use the PWM functionality of the ESP32 to generate the control signal for the servo. By varying the pulse length of the PWM signal, the code will set the servo to different angular positions (typically between 0 and 180 degrees). The code will demonstrate moving the servo to a few different predefined angles.

Web Interface Features

A web interface could allow users to input a desired angle or use a slider to control the servo’s position in real-time.

Implementation Steps

  • Set up the MicroPython environment on the ESP32.
  • Connect the servo motor circuit as described.
  • Write the MicroPython code to control the servo’s position.
  • Upload and run the code on the ESP32.
  • Observe the servo moving to different angles.

Extensions and Challenges

  • Sweep the servo back and forth automatically.
  • Use a sensor (like the ultrasonic sensor or photoresistor) to control the servo’s position.
  • Attach a simple arm to the servo to perform a task (e.g., pushing a button).

Troubleshooting Guide

  • Servo not moving or moving erratically: Check the power supply to the servo; it may require more current than the ESP32 can provide, necessitating an external supply. Verify the control signal wire is connected to a PWM-capable pin and configured correctly in the code. Ensure the pulse lengths in the code correspond to the desired angles for the SG90 servo.
  • Servo buzzing: This can sometimes indicate insufficient power or the servo trying to reach a position it can’t.

STEM Benefits

Science:

  • Rotary Motion: Understanding angular movement.
  • Feedback Systems (implicit): Servo motors use internal feedback to maintain a desired position.

Technology:

  • Actuators: Using a servo motor for precise angular positioning.
  • PWM for Servos: Learning that servo motors are controlled by specific pulse lengths of a PWM signal, not just the duty cycle percentage in the same way as DC motor speed control.

Engineering:

  • Precision Control: Implementing code to achieve specific angular positions.
  • Mechanical Linkages (optional extension): Designing simple arms or mechanisms to be moved by the servo.

Mathematics:

  • Angles and Degrees: Working with angular measurements (0-180 degrees).
  • Timing and Pulse Lengths: Understanding the relationship between pulse duration and the servo’s angle.

Project Code

# This script demonstrates controlling the angular position of an SG90 micro servo motor
# using the ESP32's PWM capabilities.

from machine import Pin, PWM  # Import Pin for GPIO and PWM for generating PWM signals
import time                   # Import the time module for delays

# Define the GPIO pin number connected to the servo's control wire (orange/yellow).
# Replace 19 with the actual PWM-capable GPIO pin you are using on your ESP32.
# Consult your ESP32 board's pinout to find available PWM pins.
servo_pin = 19

# Create a Pin object for the servo pin.
servo_gpio = Pin(servo_pin)

# Create a PWM object associated with the servo pin.
# Servo motors typically require a PWM frequency of 50 Hz.
pwm_servo = PWM(servo_gpio, freq=50)

# Function to set the servo angle.
# The angle is expected to be between 0 and 180 degrees.
def set_servo_angle(angle):
    # Ensure the requested angle is within the standard range for SG90 servos.
    angle = max(0, min(180, angle))

    # Map the angle (0-180 degrees) to the corresponding PWM pulse width.
    # Servo position is controlled by the duration of the high pulse, typically
    # around 500 microseconds (us) for 0 degrees and 2500 us for 180 degrees.
    # For a 50Hz frequency (20ms or 20000 us period), this corresponds to:
    # 0 degrees: 500 us pulse / 20000 us period = 2.5% duty cycle
    # 180 degrees: 2500 us pulse / 20000 us period = 12.5% duty cycle
    #
    # MicroPython's duty_u16() method takes a value from 0 to 65535.
    # 2.5% of 65535 is approximately 1638.
    # 12.5% of 65535 is approximately 8192.
    # These values (1638 and 8192) represent the duty cycle values for 0 and 180 degrees respectively
    # when using duty_u16() with a 50Hz frequency.
    # You might need to fine-tune these values for your specific SG90 servo for best results.

    min_duty_u16 = 1638  # Duty cycle_u16 value for 0 degrees (approx 500us)
    max_duty_u16 = 8192  # Duty cycle_u16 value for 180 degrees (approx 2500us)

    # Calculate the target duty cycle value using linear interpolation
    # between the minimum and maximum duty cycle values based on the desired angle.
    # The formula maps the angle (0-180) to the duty cycle range (min_duty_u16 - max_duty_u16).
    duty = int(min_duty_u16 + (max_duty_u16 - min_duty_u16) * (angle / 180))

    # Set the PWM duty cycle using the duty_u16() method.
    pwm_servo.duty_u16(duty)
    print(f"Setting servo to angle: {angle} degrees (duty_u16: {duty})")

# --- Main part of the script ---
print("Starting servo control script...")

# Example usage:
# Move the servo to a few different predefined angles with delays between movements.

# Move servo to the 0-degree position.
set_servo_angle(0)
time.sleep(2) # Wait for 2 seconds to allow the servo to move

# Move servo to the 90-degree position (center).
set_servo_angle(90)
time.sleep(2)

# Move servo to the 180-degree position.
set_servo_angle(180)
time.sleep(2)

# Move servo back to the 0-degree position.
set_servo_angle(0)
time.sleep(2)

print("Servo control demonstration finished.")

# Optional: Add a continuous loop here to sweep the servo or control it
# based on sensor input or other logic.
# Example of sweeping back and forth:
# while True:
#     # Sweep from 0 to 180 degrees
#     for angle in range(0, 181, 5): # Steps of 5 degrees
#         set_servo_angle(angle)
#         time.sleep(0.05) # Small delay between steps
#     # Sweep from 180 back to 0 degrees
#     for angle in range(180, -1, -5): # Steps of -5 degrees
#         set_servo_angle(angle)
#         time.sleep(0.05) # Small delay between steps

# This main block of code executes the example movements once.
# If you add the 'while True' loop above, it will run continuously.

STEM Benefits

Science:

  • Rotary Motion: Understanding angular movement.
  • Feedback Systems (implicit): Servo motors use internal feedback to maintain a desired position.

Technology:

  • Actuators: Using a servo motor for precise angular positioning.
  • PWM for Servos: Learning that servo motors are controlled by specific pulse lengths of a PWM signal, not just the duty cycle percentage in the same way as DC motor speed control.

Engineering:

  • Precision Control: Implementing code to achieve specific angular positions.
  • Mechanical Linkages (optional extension): Designing simple arms or mechanisms to be moved by the servo.

Mathematics:

  • Angles and Degrees: Working with angular measurements (0-180 degrees).
  • Timing and Pulse Lengths: Understanding the relationship between pulse duration and the servo’s angle.

Projects
ShowCase

Real-World Projects
with Code & Hardware

Insights, Ideas
& How-Tos

Help, Support, and
Common Questions

What types of projects can I find on your website?

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.

You can explore a wide range of microcontroller and electronics projects, including Arduino, ESP32, IoT, and more. Each project comes with downloadable code, detailed guides, and the necessary hardware list.