webwinkelkeur logo

4.7 avg.

5101+ reviews
webwinkelkeur logoView all

5101+ reviews

5101+ reviews

Order by 16:00 for same day shipping

14 days return

EN

Individual

Business

Raspberry Pi project: Servo Control

Beginner
15
111,00

Connect

To start we first need to connect the servo motor to the Raspberry Pi . You do this by connecting the jumper wires to the Servo Motor. Then we connect the jumper wire that is connected to the servo motor to the Raspberry Pi 4B. Connect the wires to the following pins: The red jumper wire to PIN 2 (5volt). The black jumper wire to PIN 6 (Ground) and the last jumper wire to PIN 12 (BCM 18).

Programming

Once everything is connected and your Pi is working properly, we can start writing the code to make the Servo run. On your Raspberry Pi open the Thonny programming environment. Then create a new file called servo_project.py (you can name it whatever you want, as long as it has “.py” at the end!) Save this file and start writing the following code:

from gpiozero import AngularServo
from time import sleep


 



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

 

while (True):
servo.angle = 90
sleep(2)
servo.angle = 0
sleep(2)
servo.angle = -90

sleep(2)

With this code you control your servo motor. Let's look at the code line by line and see which line does what!

The code starts by importing the AngularServo and Sleep libraries.

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

Using this piece of code, we create a variable called servo. In this case, we say the data pin is GPIO 18. And we say what the min and max pulse width is, which is 0.0006 and 0.0023.

while (True):
servo.angle = 90
sleep(2)
servo.angle = 0
sleep(2)
servo.angle = -90

sleep(2)

Here we create an endless loop using a “While (True)” statement. The servo goes from the 90 degree angle to the 0 degree angle to the -90 degree angle. With a 2 second pause in between.

Result

You have now connected the Servo to your Raspberry Pi and written the code that will make the Servo turn. Save your file and click “Run” (big green button in “Thonny” with a play button in it) And see what happens! Is your servo not working? Then take a look at the previous steps and try again!

Did you like this project? Check out one of our other projects!