Note

Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.

Why Join?

  • Expert Support: Solve post-sale issues and technical challenges with help from our community and team.

  • Learn & Share: Exchange tips and tutorials to enhance your skills.

  • Exclusive Previews: Get early access to new product announcements and sneak peeks.

  • Special Discounts: Enjoy exclusive discounts on our newest products.

  • Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.

👉 Ready to explore and create with us? Click [here] and join today!

1.7 Servo

Introduction

In this project, we will learn how to control a servo motor using a Raspberry Pi. Servo motors are commonly used in robotics and automation for precise control of angular motion.


What You’ll Need

To complete this project, you will need the following components:

COMPONENT

PURCHASE LINK

Servo

BUY

Fusion HAT+

-

Raspberry Pi

-


Circuit Diagram

The circuit diagram below shows the connections required for controlling the servo motor.

../_images/1.3.2_sch.png

Wiring Diagram

../_images/1.3.2_bb.png

Running the Example

All example code used in this tutorial is available in the ai-lab-kit directory. Follow these steps to run the example:

cd ~/ai-lab-kit/python/
sudo python3 1.7_Servo.py

After running the script, the servo connected to PWM 0 smoothly sweeps from −90° to 90° in 10-degree steps, pausing briefly at each position. It then moves back from 90° to −90° in the same way. This back-and-forth motion repeats continuously.


Code

The following Python code demonstrates how to control the servo motor by moving it between various angles:

#!/usr/bin/env python3
from fusion_hat.servo import Servo   # Import Servo class
from time import sleep               # Import sleep for delays

# Initialize servo on channel 0
servo = Servo(0)

try:
   while True:
      # Sweep from -90° to +90° in steps of 10°
      for angle in range(-90, 91, 10):
            servo.angle(angle)
            sleep(0.1)   # Smooth movement delay

      # Sweep back from +90° to -90° in steps of 10°
      for angle in range(90, -91, -10):
            servo.angle(angle)
            sleep(0.1)

except KeyboardInterrupt:
   # Stop the program safely when Ctrl+C is pressed
   servo.angle(0)        # Return servo to center position
   sleep(0.1)

This Python script controls a servo motor connected to PWM 0. When executed:

  1. The servo moves from -90 degrees to 90 degrees in 10-degree increments.

  2. It pauses for 0.1 seconds between each movement.

  3. It then reverses the direction and moves from 90 degrees to -90 degrees in 10-degree increments.

  4. The process repeats indefinitely.


Understanding the Code

  1. Library Import

    The fusion_hat library simplifies GPIO interactions, while the time library provides delay functions.

    from fusion_hat.servo import Servo   # Import the Servo class for controlling servos
    from time import sleep               # Import sleep for timing delays
    
  2. Servo Initialization

    The Servo object is initialized with PWM 0.

    servo = Servo(0)
    
  3. Servo Movement

    The servo is moved to different angles in a loop. The angle method sets the servo’s position, and sleep pauses the loop for a specified duration.

    while True:
       # Sweep from -90° to +90° in steps of 10°
       for angle in range(-90, 91, 10):
             servo.angle(angle)
             sleep(0.1)   # Smooth movement delay
    
       # Sweep back from +90° to -90° in steps of 10°
       for angle in range(90, -91, -10):
             servo.angle(angle)
             sleep(0.1)
    

Troubleshooting

  1. Servo Does Not Move

    • Cause: Incorrect GPIO pin connection or power supply issues.

    • Solution: Ensure the servo is connected to PWM 0 and verify the power supply.

  2. Servo Movement is Erratic or Unresponsive

    • Cause: Insufficient power supply to the servo.

    • Solution: Use an external power source for the servo if the Fusion HAT+ does not provide enough power.


Extendable Ideas

  1. User-Controlled Servo

    Allow users to control the servo position interactively through keyboard input:

    while True:
       position = float(input("Enter position (-90 to 90): "))
       servo.angle(position)
    
  2. Servo Position Tracking

    Record the servo position over time and plot the trajectory:

    positions = []
    for i in range(-90, 91, 10):
       servo.angle(i)
       sleep(0.1)
       positions.append(servo.angle())
    plt.plot(positions)
    plt.show()
    

Conclusion

This project demonstrates how to control a servo motor. Understanding servo control opens the door to building robots, mechanical arms, and other motion-based projects.