Page 68 - Computing Book 8
P. 68
Programming Robots and Single-Board Computers Class 8
We have also used the conditional statements in while loop. According to the if condition, if the
voltage is detected on the GPIO18, then the Pi will turn on the LED, which is connected to GPIO23.
The voltages will be detected on GPIO18 when the button is pressed.
Practical Task: Perform the above-mentioned program using raspberry pi
and necessary equipment as mentioned above.
Interfacing with SONAR Sensor:
In this program, we will understand the SONAR Sensor and its
working. SONAR is an acronym of Sound Navigation &
Ranging. It is used for measuring distance regardless of the
shape colour and surface of the object.
Hardware of this project is made simpler for your handling and
does not require any soldering or messy wiring. We will use the SONAR Sensor
Pi Shield on the top of the GPIO pins of Pi as a stack and connect Connector
the SONAR sensor on the Pi shield. But this time we will power the Pi via power adapter or battery
outlet available on the Pi Shield.
Things Needed for this Program:
• Sonar Sensor
Enter the code below on Python IDLE: • Pi Shield
import RPi.GPIO as gpio • Raspberry Pi
import time as t
• Power Adapter / Battery
gpio.setmode(gpio.BCM) • Keyboard, Mouse & LCD
gpio.setwarnings(False)
Trigger= 17
Echo= 27
gpio.setup(Trigger,gpio.OUT)
gpio.setup(Echo,gpio.IN)
def distance():
gpio.output(Trigger,True)
t.sleep(0.0001)
gpio.output(Trigger,False)
while gpio.input(Echo)==0: In this program we are determining distance by using
StartTime=t.time() a Sonar Sensor. This explains the application of
sensors and they talk to the real world. We have
while gpio.input(Echo)==1: created the function by the name of Distance. This
StopTime=t.time() function will control voltages to trigger pin which will
TimeElapsed=StopTime-StartTime cause Sonar Sensor to transmit the ultrasonic sound
dis= (TimeElasped/2)*34300 wave, which is inaudible to human ear, for 0.0001
return dis seconds. The transmitted wave will bounce back when
while True: it hits the object and will be received by the echo pin.
D=distance() We have included two libraries in this code as well.
D=int(D) First is the RPi.GPIO and second is the time library.
print("Measured Distance =",D,"cm") Distance is the product of Speed into time.
t.sleep(0.5)
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 67 of 75

