Engineering · Raspberry Pi · Project 8 of 47 · Motion · Beginner
Servo motor sweep
A hobby servo turns to an angle you choose. Step it through left, centre and right like a radar or a robot arm joint.

Parts in this circuit
| Part | Type |
|---|---|
| Micro servo | Servo |
Wiring, pin by pin
Red = 5 V, orange = 3.3 V, black = GND, other colours = signals. “Pin” is the position on the 40-pin header; the GPIO number is what the code uses. Power the Pi from a 5.1 V supply and wire with the power off.
| # | Colour | From (part and leg) | To (header pin) |
|---|---|---|---|
| 1 | Coloured | Micro servo - signal | Pin 11 (GPIO17) |
| 2 | Red | Micro servo - 5 V | Pin 2 (5V) |
| 3 | Black | Micro servo - GND | Pin 6 (GND) |
Python code (gpiozero)
from gpiozero import AngularServo
from time import sleep
servo = AngularServo(17, min_angle=-90, max_angle=90)
while True:
for angle in (-90, -45, 0, 45, 90, 45, 0, -45):
servo.angle = angle
print("Angle:", angle)
sleep(0.8)
How the code works
- A servo expects a pulse every 20 ms. The pulse is 1 ms for one end and 2 ms for the other. gpiozero makes the pulses.
- AngularServo lets you give a real angle between min_angle and max_angle.
- The for loop walks through the angles in the tuple one by one.
You will learn
- Servo control by pulse width
- Looping over a list of values
- Angles in a range
Try this
- Sweep smoothly: step one degree at a time with a short sleep.
- Return to 0 degrees at the end with servo.angle = 0.
- Add a button that sends the servo to 0.
On a real Pi
- Power the servo from a separate 5 V supply and join the grounds. A stalled servo can reset the Pi.
- Jitter is common with software PWM. A pigpio or hardware PWM setup is steadier.
Parts to buy
The links open a search on each store, so you see what is in stock today. Check the model, voltage and price before you order.
| # | Item | Qty | Buy / compare |
|---|---|---|---|
| 1 | Raspberry Pi 4 Model B about 4000 to 9000 INR | 1 | Robu.in Amazon.in ThinkRobotics |
| 2 | Official 15 W USB-C power supply (5.1 V, 3 A) Do not use an old phone charger | 1 | Robu.in Amazon.in ThinkRobotics |
| 3 | microSD card 32 GB, class 10 / A1 (with Raspberry Pi OS) And a card reader to write it | 1 | Robu.in Amazon.in ThinkRobotics |
| 4 | SG90 micro servo | 1 | Robu.in Amazon.in ThinkRobotics |
| 5 | Dupont jumper wires, male-to-female, 20 cm (pack of 40) | 1 | Robu.in Amazon.in ThinkRobotics |
| 6 | Breadboard 830 points For resistors and shared GND / 5 V | 1 | Robu.in Amazon.in ThinkRobotics |
This is a learning tool. The simulator checks the program logic, not the electrical design. Never put more than 3.3 V on a GPIO pin.