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 |
|---|---|
- |
|
Raspberry Pi |
- |
Circuit Diagram
The circuit diagram below shows the connections required for controlling the servo motor.
Wiring Diagram
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:
The servo moves from -90 degrees to 90 degrees in 10-degree increments.
It pauses for 0.1 seconds between each movement.
It then reverses the direction and moves from 90 degrees to -90 degrees in 10-degree increments.
The process repeats indefinitely.
Understanding the Code
Library Import
The
fusion_hatlibrary simplifies GPIO interactions, while thetimelibrary 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
Servo Initialization
The
Servoobject is initialized with PWM 0.servo = Servo(0)
Servo Movement
The servo is moved to different angles in a loop. The
anglemethod sets the servo’s position, andsleeppauses 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
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.
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
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)
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.