Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Raspberry Pi
80 min
Share

How to controll a servo motor with raspberry pi 5 ?

A servo motor is just a simple DC motor with certain modifications. When you look at it, you’ll notice that it has several gears and an electronic circuit. These improvements provide the motor with new capabilities, such as precise control of the shaft’s speed and direction.

Project Video

Overview

In this tutorial, we will use the Raspberry pi 5 to control the servo motor shaft to sweep back and forth across 180 degrees.

Getting the Items

Raspberry Pi 5 Single Board Computer
Get Item
SG90 Servo -Positional Rotation
Get Item
Jumper Wires – Male to Female (40 Pack)
Get Item

Steps

Wiring it Up

Connections from the servo motor:


• Servo GND pin→ Raspberry pi 5 GPIO GND pin


• Servo VCC pin→ Raspberry pi 5 GPIO 5V pin


• Servo signal pin → Raspberry pi 5 GPIO pin 18

Coding

Now on your Raspberry Pi, click on the menu, then choose programming, then open the Thonny ide program.

Now copy that code into it, The function of this code is to control the servo motor shaft to sweep back and forth across 180 degrees.

Each type of servo motor has a specific duty cycle, which you will find in the datasheet of your servo and which must be set in the programming code. Therefore, be sure to change the duty cycle through the variables (min_pulse_width, max_pulse_width) in the programming code to be compatible with the datasheet.

from gpiozero import AngularServo

from time import sleep

# Create an AngularServo object with the specified GPIO pin,

# minimum pulse width, and maximum pulse width

servo = AngularServo(18, min_pulse_width=0.0006, max_pulse_width=0.0023)

try:

   while True:

       # Set the servo angle to 90 degrees

       servo.angle = 90

       sleep(1)  # Delay for 1 second

       # Set the servo angle to 0 degrees

       servo.angle = 0

       sleep(1)  # Delay for 1 second

       # Set the servo angle to -90 degrees

       servo.angle = -90

       sleep(1)  # Delay for 1 second

finally:

   # Set the servo angle to 0 degrees before exiting

   servo.angle = 0

Testing it Out

Now run the code, you will find that the Raspberry pi 5 control the servo motor shaft to sweep back and forth across 180 degrees.

Resources

No items found.