Page 69 - Computing Book 8
P. 69
Programming Robots and Single-Board Computers Class 8
After executing this program, we will start getting the readings from SONAR Sensor in a list form.
These readings will vary if we place our hand or any object in front of the SONAR Sensor.
Practical Task: Perform the above-mentioned program using raspberry pi and necessary equipment
as mentioned above.
Interfacing Servo Motor:
A servo motor is an electrical device that can push or rotate an object with
great precision. If you want to rotate and object at some specific angles or
distance, then you use a servo motor. It is just made up of a simple motor
and the servo mechanism.
In this program, we will work with the concept of Pulse-Width Modulation as it is one of the basic
operating principles of a servo motor. We will learn how to control servo motors. These motors have
its application where an object must be pushed or rotated at a precise angle.
We will use the Pi Shield on the top of the GPIO pins of Pi as a stack and connect the Servo motor on
the Pi shield. And this time we will also power the Pi via power adapter or battery outlet available on
the Pi Shield. Colour codes are marked on the Pi Shield (B for brown, R for Red, and Y for Yellow).
Make sure to connect the correct wire on the header.
Enter the code below on Python IDLE:
import RPi.GPIO as GPIO
import time as t
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(13,GPIO.OUT)
Servo Motor
p= GPIO.PWM(13,250) Connector
p.start(24)
while True: Things Needed for this Program:
t.sleep(1) • Servo Motor
p.ChangeDutyCycle(37) • Pi Shield
t.sleep(1) • Raspberry Pi
p.ChangeDutyCycle(75) • Power Adapter / Battery
t.sleep(1) • Keyboard, Mouse & LCD
p.ChangeDutyCycle(24)
Servo motors are controlled by PWM (Pulse Width Modulation). PWM is like a switch works like On-
time and Off-time of a signal. On-time represents the active time of the signal required to power the
servo motor whereas the Off-time is for the inactive time of a signal.
In the code, we are instructing the Pi to start the wave at 24% using the start command. Then we use
the command "ChangeDutyCycle()" which understands the value in percentage format, referring to
the on-time of signal or to change the angle. We just have to input the percentage of on-time signal
to rotate servo motor to a particular angle. This is the standard method to program a servo motor.
The "ChangeDutyCycle()" is in while True loop which means that the servo motor will keep changing
its angle after a particular time.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 68 of 75

