The City School 2021-2022
5.1. Single-Board Computers
A single-board computer (SBC) is a complete computer built on a single circuit board,
with microprocessor(s), memory, input/output (I/O), and other features required
of a functional computer. Single board computers were made as demonstration or
development systems, for educational systems, or as embedded computer controllers.
Many types of home computers or portable computers integrate all their functions
onto a single printed circuit board.
Unlike a desktop personal computer, single board computers often do not rely on
expansion slots for peripheral functions or expansion. Single board computers have
been built using a wide range of microprocessors.
Simple designs, such as those built by computer hobbyists, often use static RAM and
low-cost 8- or 16-bit processors. Other types, such as blade servers, would perform
similar to a server computer, only in a more compact format.
5.2. Introduction to Raspberry Pi
The Raspberry Pi, which is a single board computer (SBC), is a small credit card sized
computing device that can be used for a variety of purposes that include but not
limited to:
• experimentation
• learning how to program,
• building a media player or NAS drive, robotics
• home automation
• performing computing tasks such as web browsing or word processing.
SBCs are also increasingly used for a wide range of industrial applications in areas
that include robotics and the Internet of things (IoT).
101
The City School 2021-2022
Exploring the Raspberry Pi
Besides having all the essential components of a traditional
computer Raspberry Pi has one special feature that normal
computers don’t: General Purpose Input Output (GPIO) Pins.
Thus, allowing you to connect with the real world.
102
The City School 2021-2022
Components of Raspberry Pi
• GPIOS: to connect devices to real world, for instance, sensors, LEDs, motors etc.
• USB Port: to connect a mouse, a keyboard, or other peripherals.
• Ethernet Port: to connect to the internet using an Ethernet cable.
• Audio Jack: to connect an audio device.
• CSI Connector: to connect a camera with a Camera Serial Interface ribbon.
• HDMI Connector: to connect a monitor or TV.
• Power Port: to power up your Pi.
• DSI Connector: to connect Display Serial Interface compatible display. Programming Robots & Single-Board Computers
Accessories Needed for Raspberry Pi
When you buy a Raspberry Pi board, you only get a bare electronic board that doesn’t
do much on its own. You need several accessories to get started. There are a lot of
accessories for the Raspberry Pi, but you need at least a microSD card and a power
supply. Without these accessories your Raspberry Pi is useless.
Power Adapter: you’ll need one that provides 2.5 amperes and 5 volts.
Micro SD Card: you’ll need one with at least 8GB storage, speed class 10.
SD You need a microSD card to store your files and the Pi’s operating system.
8 Gb The Pi doesn’t have hard drive, so everything you do on your Pi is saved on
the microSD card, even the operating system. You can get a microSD card with the
operating system preloaded or install the operating system yourself.
There are also useful accessories you may consider important such as an HDMI
cable to connect an LCD. A spare mouse and keyboard can also be useful to set your
Raspberry Pi as a desktop computer.
103
The City School 2021-2022
5.3. Raspberry Pi Architecture
The Raspberry Pi has an ARM Architecture based Processor. With a high-speed
processor and 1 GB RAM, the PI can be used for many demanding projects like digital
image processing and many IoT and connected projects. The Raspberry Pi also
consists of a set of pins that allow it to communicate with other nearby electronic
devices.
General purpose input-output (GPIO)
A powerful feature of Raspberry Pi is the set of GPIO pins along the top edge of the
board. GPIO pins can simply be used to turn devices on and off. GPIO pins allow the
Raspberry pi to be configured for different purposes, interact with different circuits,
and work with several types of electronic components, for example, motors, LEDs,
switches, etc. GPIO pins can simply be used to turn devices on and off.
The image on the right provides an
understanding of the pinout labelling.
3V3 Power 1 2 5V Power
Raspberry Pi pins are labelled in two GPIO 2 (SDA) 3 4 5V Power
ways, i.e. the GPIO pinout labelling and GPIO 3 (SCL) 5 6 Ground
GPIO 4 (GPCLK0) 7 8 GPIO 14 (TXD)
Physical pin labelling. The physical pin Ground 9 10 GPIO 14 (RXD)
GPIO 17 11 12 GPIO 18 (PCM_CLK)
labelling is starting from 1 and ending GPIO 27 13 14 Ground
on 40 in the image. GPIO 22 15 16 GPIO 23
3V3 Power 17 18 GPIO 24
Ports: GPIO 10 (MOSI) 19 20 Ground
GPIO 9 (MISO) 21 22 GPIO 25
• Raspberry Pi is equipped with four GPIO 11 (SCLK) 23 24 GPIO 8 (CE0)
USB 2.0 ports and one LAN Port. Ground 25 26 GPIO 7 (CE1)
GPIO 0 (ID_SD) 27 28 GPIO 1 (ID_SC)
• USB ports allow USB devices to be GPIO 5 29 30 Ground
connected together and transfer GPIO 6 31 32 GPIO 12 (PWM0)
GPIO 13 (PWM1) 33 34 Ground
data over a USB Cable. GPIO 19 (PCM_FS) 35 36 GPIO 16
• The LAN port allows the raspberry GPIO 26 37 38 GPIO 20 (PCM_DIN)
Ground 39 40 GPIO 21 (PCM_DOUT)
pi to connect to a network using a
wired connection.
104
The City School 2021-2022
Raspbian OS
Raspbian is a Debian-based (32 bit) computer operating system for Raspberry
Pi. There are several versions of Raspbian including Raspbian Buster and
Raspbian Stretch. Since 2015 it has been officially provided by the Raspberry Pi
Foundation as the primary operating system for the family of Raspberry Pi
single-board computers. The operating system is still under active development.
Raspbian is highly optimized for the Raspberry Pi line’s low-performance ARM CPUs.
Raspbian uses PIXEL, Pi Improved X-Window Environment, Lightweight as its main
desktop environment as of the latest update. The Raspbian distribution comes with a
copy of the computer algebra program Mathematica and a version of Minecraft called Programming Robots & Single-Board Computers
Minecraft Pi as well as a lightweight version of Chromium as of the latest version.
Menu to access
tools, software
and preferences
Chromium Power & battery
web browser Wi-fi/Wireless CPU usage
File manager
Terminal Bluetooth
105
The City School 2021-2022
5.4. Python Basics
Python is a high-level programming language designed
to be easy to read and simple to implement. It is open-
source, which means it is free to use, even for commercial
applications. Python can run on Mac, Windows, and UNIX
systems. Running Python Using IDLE- The IDLE interpreter
is a sort of “sandbox” where you can work with Python
interactively without having to write whole scripts to
see what they do. The name IDLE stands for Integrated
Development Environment.
You can find IDLE in the taskbar under the label of programming. Follow the steps to
run your first program:
1. Click on the Raspberry Pi icon in the
taskbar and then go to programming and
hit Python 3 (IDLE).
2. Let’s start with the first program that
prints “Hello World” message on the
screen.
3. Write print (“hello world”) on IDLE
and hit enter.
Running Python as a Script on IDLE
A script or scripting language is a feature
of computer language with a series of Checkpoint
commands within a file that is capable of
being executed. Scripts are just the piece of The Raspberry Pi, which is a single
board computer (SBC), is a small credit
code, in which the code is written in the form card sized computing device that can
be used for a variety of purposes.
of scripts and get executed. Error checking is GPIO stands for General Purpose
done when the code is executed or run. Input/Ouput pins.
106
The City School 2021-2022
Follow the steps to run python as script on IDLE:
1. On Python IDLE click File>>New File.
2. In the resulting window type the following program and then save the file as
test1.py in the default location.
3. Then press F5 to execute the program.
4. The program output will be 15..
Sample code:
# This program adds two numbers
x = 10 Programming Robots & Single-Board Computers
y = 5
# Add two numbers and store result in z
z = x + y
# Display the sum
print(z)
5.5. Variables in Python
A variable is the storage placeholder for text and numbers. It must have a name
so that you can find it again. The variable is always assigned with an equality sign,
followed by the value of the variable. Variables can store data that can be used
elsewhere. They’re one of the most powerful tools programmers can use.
In python IDLE, enter the following statement: score=9 All this does is tell Python
that you want to use score as a new name for the value 9. After this point, whenever
Python sees score, it will insert the value 9. To demonstrate this, try entering the
following: print(score).
Remember that python executes instructions in order, and you must give score a
value before you use it or you will get an error.
Sample code:
# This defines a variable score and assigns a value to it
score = 9
# Display the value stored in the variable
print(score)
107
The City School 2021-2022
This illustrates another great aspect of python and that is dynamic typing. This
concept is defined with respect to the point at which the variable data types are
checked. In our code, the variable is score which holds the value 9 which is a number,
or we can label it as a data. A variable just stores the value, whereas the value could
be of different data types. The data type defines the type of data that is stored in the
variable.
Being said that, dynamic type languages are those in which the data type checking
is done at the run time. We don’t have to declare the data type in our code in python.
Python is smart enough to judge which data type is being held by the variable.
Data Types in Python
Values have types, every piece of data has to have a type associated with it so it
knows what it is dealing with. Python sets the variable type based on the value that is
assigned to it. Following are the data types which will be used throughout in coding:
Numbers: integers and float
String: any character or text
Boolean: true or false
5.6. LIST in Python
In Python, you can store your data into variables, but you can also put them in lists. A
list is just an ordered collection of items which can be of any data type. Creating a list
is as simple as putting different comma separated values between square brackets.
Each element of a list is assigned a value by using an index.
An example of list could be: newList=[10,20,30,”Samsung”]
To call or print a specific element of list, write the following code:
Sample code:
# This defines a list called newList
newList=[10,20,30,”Samsung”]
# Prints the third element in the list; starting from 0
print(newList[3])
108
The City School 2021-2022
Delete Elements in List
Del command is used to delete a list element as mentioned in the example below:
Sample code:
# This defines a list called newList
newList=[10,20,30,”Samsung”]
# Deletes the element at the index 1
del newList[1]
# Prints the list after deleting an item
print(newList)
Output: Programming Robots & Single-Board Computers
[10, 30, ‘Samsung’]
Add Elements in List
To add an item to the end of the list, use the append() method. The code below
demonstrates this:
Sample code:
# This defines a list called thisList
thisList=[”apple”,”banana”,”cherry”]
# adds a new element at the end of the list
thisList.append(“orange“)
# Prints the list after deleting an item
print(thisList)
Output:
[‘apple’,‘banana’,‘cherry’,‘orange’]
109
The City School 2021-2022
5.7. Conditional Statements in Python
Conditional statement is a set of rules performed if a certain condition is met.
IF Statement
if statement is a programming conditional statement that, if proved true, performs a
function or displays information. An if statement in python is written by using the if
keyword. The sample code below shows the if statement in python.
Sample code:
# This program compares two numbers using if
a = 33
b = 200
# if block
if b > a:
print(“b is greater than a”)
In this example, we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200
is greater than 33, and so we print to screen that “b is greater than a”. Indentation
is necessary; if we do not use the indentation as mentioned in example, python will give
an error.
Elif Statement
The elif keyword is Python’s way of saying “if the previous conditions were not true,
then try this condition”. The sample code below demonstrates Elif statement.
Sample code: Del command is used to delete a list
element whereas append() method is
# This program compares two numbers using elif used to add an item to the list
a = 33
b = 200 Checkpoint
# if block
if b > a: List is just an ordered collection of items
which can be of any data type.
print(“b is greater than a”) Del command is used to delete a list
element whereas append() method is
# elif block used to add an item to the list.
elif b == a:
print(“a and b are equal”)
110
The City School 2021-2022
In this example a is equal to b, so the first condition is not true, but the elif condition is
true, so we print to screen that “a and b are equal”.
Else Statement
The else keyword catches anything which isn’t caught by the preceding conditions. The
sampe code below shows else statement.
Sample code:
# This program compares two numbers using else statements
a = 33
b = 200 Programming Robots & Single-Board Computers
# if block
if b > a:
print(“b is greater than a”)
# elif block
elif b == a:
print(“a and b are equal”)
# else block
else:
print(“a is greater than b”)
In this example a is greater than b, so the first condition is not true, also the elif
condition is not true, so we go to the else condition and print to screen that “a is
greater than b”. We can also use the else without using elif.
5.8. Conditional and Logical Operators
Conditional operators refine the statement you’re testing for. For instance, you can
specify the statement whether it’s greater than, less than, and a whole lot more.
Operator Meaning
= Equal too
> Greater than
< Less than
>= More than or equal to
<= Less than or equal to
<> Not equal to
111
The City School 2021-2022
Logical operators are similar to Boolean expressions that return a boolean result.
These operators are called binary because they acquire two operands.
Operator Meaning
AND Both sides must be true
OR One one the two conditions must be true
XOR One side or other must be true but not both
NOT Negates truth
5.9. Looping Statement in Python
A For loop is used for repeating over a sequence (that is either a list or a string). This
is less like the FOR keyword in other programming languages and works more like an
iterator method as found in other object-orientated programming languages.
For example, we have a list of students and we want to display the student with the
highest marks without using the max() function:
Sample code:
# This defines a list of student marks
stdMarks = [70, 80, 92.5, 60.2]
# This variable keeps track of the max marks
maxMarks = 0
# for loop block
for i in range(0,4):
if stdMarks[i] > maxMarks:
maxMarks = stdMarks[i]
# Prints highest student marks
print(“Highest student marks are:”, maxMarks)
112
The City School 2021-2022
5.10. Python Functions
In Python, a function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable. Function names cannot
have spaces in between. Instead of spaces use _ underscore to connect the words.
In Python, a function is defined using the def keyword and for executing the function
we can use the function name along with parentheses ().
The sample code below demonstrates how functions are used in python: Programming Robots & Single-Board Computers
Sample code:
# This declares the function called my_function()
def my_function():
print(“Hello from a function”)
# Calling the function
my_function()
Output:
Hello from a function
5.11. Getting Started with Python and Raspberry Pi
One of the classic electronic analogy to “Hello World”
is to make an LED blink. It is one of the very basic
tutorials to begin with. To get started, you first of all
need to build the circuit on the breadboard; a board
for electronic prototyping.
Equipment needed
Following componentes are required for this project:
• 1 breadboard
• 1 LED
• 2 jumper wires
• 1 resistor: 220Ω/1KΩ
113
The City School 2021-2022
The circuitry of LED blink is pretty simple, you just have to connect the electronic
component with raspberry pi properly as shown in the picture above.
1. Connect resistor through jumper wire (represented in blackcolour) with PIN 6.
2. Connect the positive leg of the LED with PIN 12 (GPIO 18).
3. After completing the circuitry, it’s time to move on to Raspberry Pi.
4. Turn on the Raspberry Pi.
5. On the desktop, go the start menu and click on python IDLE and enter the following
code:
# calling header file for GPIO’s of PI.
import RPi.GPIO as IO
# calling for time library to use sleep command
for delays in program
import time
# programming the GPIO by BCM
IO.setmode (IO.BCM)
# initialize digital pin as an output.
IO.setup(18,IO.OUT)
# turn the LED on (making the voltage level HIGH)
IO.output(18,1)
# sleep for a second
time.sleep(1)
IO.output(18,0)
time.sleep(1)
IO.output(18,1)
time.sleep(1)
IO.output(18,0)
time.sleep(1)
IO.output(18,1)
time.sleep(1)
IO.output(18,0)
time.sleep(1)
114
The City School 2021-2022
BCM stands for Broadcom SOC channel. These pin numbers follow the lower-level
numbering system defined by the Raspberry Pi’s Broadcom System on Chip (SOC)
brain. The above program will turn the LED on and off thrice with a one second delay.
Resistor: The resistor is a passive device that controls or resists the flow of current to
your device, for example if we don’t use the resistor in the above experiment, the LED
may allow too much current to flow which can damage both the LED and the Pi.
Bread Board: Breadboards are one of the most 1 A B C D E Horizontal holes I J 1
F G H
2 are linked 2
fundamental pieces when learning how to build 3 together 3
4 4
circuits. A breadboard is a construction base for 5 5
6 But not across 6
prototyping of electronics for temporary testing. 7 8 the middle 7 8
divider
9 9
The following diagram shows how a breadboard is 10 10
11 11
connected. 12 12
13
13
Jumper Wire: A jump wire (also known as jumper 14 14
15
15
16 16
wire, or jumper) is an electrical wire, or group of them in a 17 17
18 18
cable, with a connector or pin at each end (or sometimes 19 19
20
20
without them – simply “tinned”), which is normally used to 21 21
22
22
23 23
connect the components of a breadboard or other prototype 24 24
25 25
26 26
or test circuit. Jumper wires typically have a solid core which 27 27
28 28
means they have 1 single strand of wire as opposed to the 29 29
30 30
usual multiple thin strands used in electrical circuits. This makes them easy to bend into
F G H
I
J
A B C D E
a particular shape.
Blinking LED Program
In this program, the same components will be used which we have used earlier, but this
program is a bit different than the previous one as we will use the while loop for
continuous repetition of the program.
Enter the following code in Python IDLE program using the raspberry Pi:
115
The City School 2021-2022
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
while True:
GPIO.output(18,True)
time.sleep(0.5)
GPIO.output(18,False)
time.sleep(0.5)
Button Controlled LED
In this program, the same components will be used which we have used earlier, except
the button. In this program, we will control the blinking or turning on and off the LED
using a button. Enter the following code in Python IDLE program using the raspberry Pi:
import RPi.GPIO as gpio
import time as t
gpio.setmode(gpio.BCM)
gpio.setwarnings(False)
gpio.setup(18, gpio.BCM)
gpio.setup(23, gpio.OUT)
while True:
if gpio.input(18):
gpio.output(23,True)
t.sleep(1)
else:
gpio.output(23,False)
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
Pi Shield on the top of the GPIO pins of Pi as a stack and connect 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.
116
The City School 2021-2022
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.
5.12. Interfacing with SONAR Sensor
Equipment needed
Following components are required for this project:
• Sonar Sensor
• Pi Shield
• Raspberry Pi
• Power Adapter / Battery
• Keyboard, Mouse & LCD
Hardware of this project is made simpler for your handling and does not require any
soldering or messy wiring. We will use the Pi Shield on the top of the GPIO pins of Pi as
a stack and connect 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.
Interfacing code:
import RPi.GPIO as gpio
import time as t
gpio.setmode(gpio.BCM)
gpio.setwarnings(false)
trigger=17 Python is one of the official
echo=27 programming languages at Google
gpio.setup(trigger, gpio.OUT) and YouTube is one of Google’s
gpio.setup(echo, gpio.IN) products that are powered by
Python.
def distance():
gpio.output(trigger,True)
117
The City School 2021-2022
t.sleep(0.0001)
gpio.output(trigger,False)
while gpio.input(Echo) == 0:
StartTime=t.time()
while gpio.input(Echo) == 0:
StopTime=t.time()
TimeElapsed=StopTime-StartTime
dis=(TimeElasped/2)*34300
return dis
while True:
D=distance()
D=int(D)
print(“Measured distance= ”, D, “cm”)
t.sleep(0.5)
In this program we are determining distance by using a Sonar Sensor. This explains the
application of sensors and they talk to the real world. We have created the function by
the name of Distance. This function will control voltages to trigger pin which will cause
Sonar Sensor to transmit the ultrasonic sound wave, which is inaudible to human ear,
for 0.0001 seconds. The transmitted wave will bounce back when it hits the object and
will be received by the echo pin. We have included two libraries in this code as well.
First is the RPi.GPIO and second is the time library. Distance is the product of Speed
into time.
5.13. Interfacing with 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
118
The City School 2021-2022
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.
Equipment needed
Following components are required for this project:
• Servo Motor Programming Robots & Single-Board Computers
• Pi Shield
• Raspberry Pi
• Power Adapter / Battery
• Keyboard, Mouse & LCD
Interfacing code:
import RPi.GPIO as GPIO
import time as t
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(13,GPIO.OUT)
p=GPIO.PWM(13,250)
p.start(24)
while True:
t.sleep(1)
p.ChangeDutyCycle(37)
t.sleep(1)
p.ChangeDutyCycle(75)
t.sleep(1)
p.ChangeDutyCycle(24)
119
The City School 2021-2022
Servo motors are controlled by PWM (Pulse Width Modulation). PWM 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.
5.14. Building Smart Robotic Car
Bumble Pi is an educational robot kit specially
designed for beginners to learn and get hands-
on experience with mechanics, electronics, and
Computer Science. Bumble Pi is easy to assemble.
Follow the step-wise instruction for making
Bumble Pi.
Equipment needed
• Raspberry Pi (with Raspbian OS)
• Pi Shield
• Screw Set
• Chassis (Upper and lower planks
and side planks)
• Battery with a zip tie
• DC Motors Chassis (upper and lower planks) DC Motors
• SONAR with Holder
• Servo Motor
• Wheels & Caster Wheel
• Android Mobile Device with
TechTree Bumble Pi Application
installed in it.
Wheels for DC Motor Caster wheel for the front
120
The City School 2021-2022
Pi Shield
Bumble Pi is an educational robot kit specially designed for beginners to learn
and get hands-on experience with mechanics, electronics, and Computer Science.
Bumble Pi is easy to assemble. Follow the step-wise instruction for making
Bumble Pi. Programming Robots & Single-Board Computers
121
The City School 2021-2022
Steps to Assemble
SONAR and
servo motor
screws
Pi-sheild screws
Chasis screws
122
The City School 2021-2022 Programming Robots & Single-Board Computers
123
The City School 2021-2022
124
The City School 2021-2022
Bumble-Pi Programming
Enter the following code in Python IDLE and save the file name as SRC
# importing the libraries
from Bluetooth import *
import RPi.GPIO as GPIO
# Addressing the GPIO Pins as per Pi Shield configuration
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(16,GPIO.OUT)
# Creating variables for motor functionality Programming Robots & Single-Board Computers
MotorL1 = 21
MotorL2 = 18
enA = 20
MotorR1 = 26
MotorR2 = 12
enB = 19
# initializing the output pins
GPIO.setup(MotorL1,GPIO.OUT)
GPIO.setup(MotorL2,GPIO.OUT)
GPIO.setup(enA,GPIO.OUT)
GPIO.setup(MotorR1,GPIO.OUT)
GPIO.setup(MotorR2,GPIO.OUT)
GPIO.setup(enB,GPIO.OUT)
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,False)
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,False)
#setting up the speed of motors
p=GPIO.PWM(enA,1000)
p.start(75)
q=GPIO.PWM(enB,1000)
q.start(75)
125
The City School 2021-2022
#activating the on-board bluetooth
server_sock=BluetoothSocket(RFCOMM)
port = 1
server_sock.bind(("",port))
server_sock.listen(1)
port=server_sock.getsockname()[1]
GPIO.output(16,True)
uuid ="94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service(server_sock,"SampleServe",service_id=uuid,
service_classes=[uuid,SERIAL_PORT_CLASS],
profiles=[SERIAL_PORT_PROFILE],)
client_sock,client_info=server_sock.accept()
print("Accept connection",client_info)
#setting conditions
while True:
data=client_sock.recv(1024)
print(“Receive[ %s]” % data)
if (data == ”quit”):
print(“quit”)
GPIO.cleanup()
break
#forward functionality
elif (data == ”F”):
GPIO.output(MotorL1,True)
GPIO.output(MotorL2,False)
GPIO.output(MotorR1,True)
GPIO.output(MotorR2,False)
#backward functionality
elif (data == ”D”):
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,True)
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,True)
126
The City School 2021-2022
#stop functionality
elif (data == ”S”):
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,False)
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,False)
GPIO.output(16,False)
#turn right functionality
elif (data == ”R”):
GPIO.output(MotorL1,True) Programming Robots & Single-Board Computers
GPIO.output(MotorL2,False)
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,False)
#turn left functionality
elif (data == ”L”):
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,False)
GPIO.output(MotorR1,True)
GPIO.output(MotorR2,False)
client_sock.close()
server_sock.close()
After successfully entering this code and saving your file with the name of SRC.py follow
these steps to connect your smart car using the android mobile device.
1. Connect and pair the Bluetooth of the mobile device
with raspberry pi.
2. Open terminal and type sudo python SRC.py & Checkpoint
3. You will notice the blue LED light will be on Pi Shield, In Python, a function is a group of
related statements that perform a
this means that bluetooth module is ready to specific task.
connect. SONAR is an acronym of Sound
Navigation & Ranging. It is used for
measuring distance.
4. Open the TechTree-Bumble pi application on the
A servo motor is an electrical device
mobile device which you have already paired with that can push or rotate an object with
great precision.
Bluetooth to this Raspberry Pi.
127
The City School 2021-2022
5. Click on the Bumble Pi icon on the right bottom corner.
6. For security purposes, your mobile device will ask for permission to give bluetooth
module access to this application. Select the Allow option to give permission.
7. After that, a list of Bluetooth devices will be available to connect, select the
raspberry pi option which will be listed with the physical (MAC) address of the
Bluetooth.
8. Car Controlling screen will appear and the Blue LED on your bumble pi shield will
turn off it means your Bluetooth connection is successful now you can control your
car from your smartphone.
9. If Blue LED doesn’t turn off it means you’re not connected with the Raspberry Pi so
reboot your Raspberry Pi by turning off its switch and then repeat from step 2.
Making a Bootloader
For mobility purposes, we can also make a bootloader which will automatically start
the command whenever the Raspbian OS will boot. By doing this we won’t be needing
the Keyboard, Mouse and LCD to be connected for configuring or executing the
command.
Note: This Step will not exclude the process of pairing the android device.
Follow these steps to make the bootloader:
1. Open terminal and type the command sudo nano /etc/rc.local
2. There will be a lot of text written in that file. Locate the comment stating # write a
path for the code to run here”. And enter this command sudo python /home/pi/
SRC.py & and press ctrl+x
3. The terminal window will ask to save the file, press Y for yes.
4. After that terminal will ask to save this file on the same location where we have to
press Enter key.
5. Unplug the cables and restart the Pi by typing the Reboot keyword within the
terminal window.
6. Wait for the Pi to boot completely and you will notice the blue light is lit and the Pi is
ready to connect with the paired mobile device using the Tech Tree Bumble Pi app.
128
The City School 2021-2022
Let’s Review
1. A single-board computer (SBC) is a complete computer built on a single circuit
board, with microprocessor(s), memory, input/output (I/O), and other features
required of a functional computer.
2. The Raspberry Pi, which is a single board computer (SBC), is a small credit card
sized computing device that can be used for a variety of purposes.
3. GPIO pins allow the Raspberry pi to be configured for different purposes; interact
with different circuits, and work with several types of electronic components.
4. A list is just an ordered collection of items which can be of any data type.
5. Del command is used to delete an item from list where as append() command is
used to add an item at end of the list.
6. In Python, a function is a group of related statements that perform a specific task.
7. SONAR is an acronym of Sound Navigation & Ranging. It is used for measuring
distance regardless of the shape colour and surface of the object.
8. A servo motor is an electrical device that can push or rotate an object with great
precision.
9. Bumble Pi is an educational robot kit specially designed for beginners to learn and
get hands-on experience with mechanics, electronics, and computer science.
My Notes!
129
The City School 2021-2022
Appendix
Developing Applications
Hello World
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnReaction.Click
lblReaction.Text = “Hello World”
End Sub
End Class
Declaring Private Variable
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim num1 As Integer
Dim num2 As Integer
num1 = TextBox1.Text
num2 = TextBox2.Text
Label1.Text = num1 + num2
End Sub
End Class
Declaring Public Variable
Public Class Form1
Public pub As Integer
Private Sub btnRst_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnRst.Click
pub = 0
Label1.Text = pub
130
The City School 2021-2022
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnAdd.Click
pub = pub + 1 Appendix
Label1.Text = pub
End Sub
Private Sub Label1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Label1.Click
End Sub
End Class
If...Then Statements
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim number As Integer
number = textBoxNumber.Text
If number >= 7 Then
lblResult.Text = “Congratulations! You win”
End If
End Sub
End Class
If...Then...Else Statements
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim number As Integer
number = textBoxNumber.Text
131
The City School 2021-2022
If number >= 7 Then
lblResult.Text = “Congratulations! You win”
Else
lblResult.Text = “No luck...Try Again”
End If
End Sub
End Class
If...Then...Elseif Statements
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim score As Integer
Dim grade As String
score = TextBox1.Text
If score >= 90 Then
grade = “A”
ElseIf score >= 80 Then
grade = “B”
ElseIf score >= 70 Then
grade = “C”
Else
grade = “Needs improvement”
End If
lblGrade.Text = grade
End Sub
End Class
132
The City School 2021-2022
For Loop
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles btnCalculate.Click Appendix
Dim i As Integer
Dim sum As Integer
sum = 0
For i = 1 To 50
sum = sum + i
Next
lblResult.Text = sum
End Sub
End Class
Do...Next Loop
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles btnCalculate.Click
Dim i As Integer
Dim sum As Integer
i = 0
sum = 0
Do While sum < 500
i = i + 1
sum = sum + i
lstResult.Items.Add(i & vbTab & sum)
Loop
End Sub
End Class
133
The City School 2021-2022
Event Handling
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
End Sub
Private Sub Form1_MouseHover(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.MouseHover
MsgBox(“This window pop-up window appears when mouse is hovered
over the button”)
End Sub
End Class
Functions and Subroutines
Public Class Form1
Private Function BMI(ByVal Height As Single, ByVal weight As Single)
As Double
BMI = weight / Height ^ 2
End Function
Private Sub btnBMI_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnBMI.Click
Dim h As Single
Dim w As Single
h = Val(TextBox1.Text)
w = Val(TextBox2.Text)
lblBMIResult.Text = BMI(h, w)
End Sub
End Class
134
The City School 2021-2022
Program Debugging and Error Handling
Public Class Form1
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles btnCalculate.Click Appendix
lbl_errorMsg.Visible = False
Dim firstNum, secondNum As Double
On Error GoTo error_handler
firstNum = firstNumber.Text
secondNum = secondNumber.Text
lblAnswer.Text = firstNum / secondNum
Exit Sub
‘to prevent error handling even when inputs are valid’
error_handler:
lblAnswer.Text = “Error”
lbl_errorMsg.Visible = True
lbl_errorMsg.Text = “One of the the entries is not a Number! Try
again”
End Sub
End Class
135
The City School 2021-2022
Glossary
Angular gradient: shades in a counter-clockwise sweep around the starting point.
Arguments: the argument is a parameter that can pass a value back to the function.
There is no limit to the number of arguments that can be added.
Bevel and emboss: add various combinations of highlights and shadows to a layer.
Bitmap: a rectangular grid of pixels, with each pixel’s colour being specified by a
number of bits.
Button: it is used as a standard Windows Button. In most cases, the Button Control is
used to generate a click event,
Checkbox: checkboxes are similar to radio buttons in the way that they are also used
in groups, however, a user can select more than one item in the group.
Clone stamp tool: the clone stamp tool paints one part of an image over another part
of the same image or over another part of any open document that has the same
colour mode.
Colour overlay: fills the layer’s content with color.
Colour palette: displays the current foreground and background colours and RGB
values for these colours.
ComboBox: it is similar to the list but it works as a dropdown for the user. A user can
click on the downwards aero on the right side and select any item.
Conditional operators: conditional operators refine the statement you’re testing for.
Cyber bullying: Bullying that occurs online, often through instant messaging, text
messages, emails, and social networks.
Database: a structured set of data held in a computer, especially one that is accessible
in various ways is called Database.
DateTime picker: this control allows the user pick the date and time via a Calendar
and a clock.
Decision making statements: allow to specify one or more conditions to be executed
if the condition is determined to be true.
Digital citizenship: digital citizenship means being part of the group of people that use
technology to communicate.
Diamond gradient: shades from the middle to the outer corners of a diamond pattern.
Digital resiience: the ability of young people to develop a critical mind-set when
136
The City School 2021-2022
accessing digital information to reduce their vulnerability to potentially harmful
information.
Drop shadow: Adds a shadow that falls behind the contents on the layer.
Error handling: An essential procedure in Visual Basic 2010 programming that helps Glossary
make a program error-free.
Event: user action like key press, clicks, mouse movements, etc., or some occurrence
like system generated notifications.
Fake news: deliberately made up stories or images to make people believe something
that isn’t true.
Field: a way of organizing information by type.
Filter gallery: a preview of many of the special effects & filters.
Foreign key: a column or group of columns in a relational database table that
provides a link between data in two tables.
Forms: display cases in stores that make it easier to view or get the items that you
want.
Free transform: lets you apply transformations (rotate, scale, skew, distort, and
perspective) in one continuous operation.
Function: a type of procedure that returns a value that is passed on to the main
procedure to finish execution. A function is similar to a subprocedure but there is one
major difference, a function returns a value whilst a subprocedure does not.
Gradient overlay: fills the layer’s content with gradient.
GPIO: general purpose input-output pins.
Healing brush: lets you correct imperfections, causing them to disappear into the
surrounding image.
Inner glow: add glows that emanate from the inside edges of the layer’s content.
Label: it is used to display some informative text on the GUI which is not changed
during runtime.
Layers: layers let you organize your work into distinct levels that can be edited and
viewed as individual units.
Layer blending mode: defines how the layer’s pixels blend with underlying pixels in the
image.
Layer mask: allows you to hide certain parts of the layer, which can then be revealed
by using the paintbrush and the white paint colour to expose portions of the layer.
137
The City School 2021-2022
Layer visibility: the eye shows that the selected layer is visible.
Linear gradient: shades from the starting point to the ending point in a straight line.
Live streaming: broadcasting of real-time, live, video to an audience over the internet.
Logical operators: similar to boolean expressions that return a boolean result.
Loop: a sequence of instructions that is repeated until a certain condition is reached.
Microsoft forms: allows Office 365 users to create custom surveys, quizzes, polls and
questionnaires in minutes.
Mirror gradient: mirrors the same linear gradient on either side of the starting point.
Not null: this constraint enforces that this field cannot be left unused.
Outer glow: add glows that emanate from the outside edges of the layer’s content.
Pattern overlay: fills the layer’s content with pattern.
Popups: adverts for products and services and other times they are phishing scams
asking you to enter personal details to claim an unbelievable prize.
Primary key: a key in a database that is unique for each record.
Private variables: variables that are accessible only to a certain part of the program
or code.
Properties: properties define the field’s characteristics and behaviour.
Public variables: are variables that are accessible to the whole program.
Query: a special “question” you apply to the database to find specific data and get the
information you want.
Radial gradient: shades from the starting point to the ending point in a circular
pattern.
Raspberry Pi: the Raspberry Pi, which is a single board computer (SBC), is a small
credit card sized computing device that can be used for a variety of purposes
Raspian-OS: raspbian is a Debian-based (32 bit) computer operating system for
RaspberryPi.
Raster graphics: a dot matrix data structure that represents a generally rectangular
grid of pixels (points of colour), viewable via a monitor, paper, or other display.
Record: a record is one unit of information. Every cell on a given row is part of that
row’s record.
Reports: offer a way to view, format, and summarize the information in your Microsoft
Access database.
Resolution: the number of pixels on a printed area of an image.
138
The City School 2021-2022
Responsive: responsive also means the interface provides some form of feedback.
Search engine: a search engine is designed to search for information on the World
Wide Web by using specified keywords.
Servo motor: an electrical device that can push or rotate an object with great
precision. Glossary
Single board computer: a single-board computer (SBC) is a complete computer built
on a single circuit board, with microprocessor(s), memory, input/output (I/O), and
other features required of a functional computer.
SONAR: SONAR is an acronym of Sound Navigation & Ranging. It is used for
measuring distance regardless of the shape colour and surface of the object.
Style palette: allows you to view, select, and apply pre-set layer styles.
Swatches palette: allows to choose a foreground or background colour and add a
customized colour to the library.
Table relationships: allows to join tables when you need to use them in a database
object.
Textbox: it is used to accept textual input from the user. The user can add strings,
numerical values and a combination of those.
Unique: this constraint enforces that the data entered in this field cannot be repeated
or all the values entered should be unique to each other.
User interface: the graphical layout of an application.
Variable: a name given to a storage area that our programs can manipulate.
139
The City School 2021-2022
140
The ICTECH curriculum engages students at technical and practical level,
equipping them with skills required in areas of research, publication
designing and prediction. The computing curriculum aims at teaching
principles of information and computation, how digital systems work and
how to put this knowledge to use through programming. ICTECH
activities incorportae a range of technology skills into student learning
such as word processing, programming, Animation, Programming,
Spreadsheets, Photoediting, Desktop Publishing, Digital Citizenship,
Databases, Operating system, Robotics, and Presentation Skills.
Microsoft
We are a Microsoft School
OSOF
OSOF
MICR
MICR
MICROSOFT T T
SCHOOLS
SCHOOLS
SCHOOLS
Microsoft