Raspberry Pi - Button - Servo Motor
This tutorial instructs you how to control a servo motor using an Raspberry Pi and a button. Here's how it works:
When you press the button, the servo motor will rotate 90 degrees.
When you press the button again, the motor will return to its original position of 0 degrees.
The same procedure is repeated infinitely.
Or you can buy the following sensor kits:
Disclosure: Some of the links provided in this section are Amazon affiliate links. We may receive a commission for any purchases made through these links at no additional cost to you.
Additionally, some of these links are for products from our own brand, DIYables.
If you are unfamiliar with servo motors and buttons (including pinouts, how they work, and how to program them), the following tutorials can help:
This image is created using Fritzing. Click to enlarge image
To simplify and organize your wiring setup, we recommend using a Screw Terminal Block Shield for Raspberry Pi. This shield ensures more secure and manageable connections, as shown below:
Please note that the wiring diagram shown above is only suitable for a servo motor with low torque. In case the motor vibrates instead of rotating, an external power source must be utilized to provide more power for the servo motor. The below demonstrates the wiring diagram with an external power source for servo motor.
TO BE ADD IMAGE
Please do not forget to connect GND of the external power to GND of Arduino Raspberry Pi.
Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
Make sure your Raspberry Pi is connected to the same local network as your PC.
Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
sudo apt-get update
sudo apt-get install python3-rpi.gpio
import RPi.GPIO as GPIO
import time
BUTTON_PIN = 18
SERVO_PIN = 12
angle = 0
prev_button_state = None
button_state = None
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(SERVO_PIN, GPIO.OUT)
servo_pwm = GPIO.PWM(SERVO_PIN, 50)
servo_pwm.start(0)
try:
while True:
prev_button_state = button_state
button_state = GPIO.input(BUTTON_PIN)
if prev_button_state == GPIO.HIGH and button_state == GPIO.LOW:
print("The button is pressed")
if angle == 0:
angle = 90
else:
angle = 0
duty_cycle = (angle / 18) + 2.5
servo_pwm.ChangeDutyCycle(duty_cycle)
time.sleep(0.1)
except KeyboardInterrupt:
servo_pwm.stop()
GPIO.cleanup()
The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.