Developing Applications – Visual Studio Class 8
If…Then…ElseIf Statement
If there are more than two choices to display, using the If...Then...Else statement is not enough. To
provide more choices, we can use the If...Then...ElseIf statement. In the following example, we have
created a program that translates a student’s score to the corresponding grade.
Follow the steps below to create the program using If…Then…Elself statement:
1. Create a new form with three labels, one text box and a button.
2. Edit the text for the first label to “Enter Your Score”.
3. Edit the button text to Show Grade.
4. Edit the text of the second label to “Your Grade:”
5. Place the third label adjacent to the second label and we will use
this label to generate the grade in it, edit the label text to “Grade
not generated yet” and also change the name of this label to “lblGrade” from the properties
panel.
6. Enter the code as shown in the example:
Declaration of Score Variable
Declaration of Grade Variable
Declaration of score value which would
be the TextBox1 which is user input
If…Then…Else Statement which
will take decision about the grade.
Data will be taken from the text
box and evaluated by the program
at every line and when the criteria This is the 3 label which will display the
rd
matches it will set the value of value of grade variable after taking
grade to the relevant string value
decision from if…then...else statement
• The first condition score >= 90 is evaluated and if it is true, then the variable grade takes the
value A.
• If a condition is found true, the following conditions are not evaluated and the instructions
under End If are executed.
• If a condition is evaluated as false, then the next condition is evaluated and so on, until a
condition is true.
• If none of the conditions are found to be true, then the code under Else is executed which
has a string value of “Need Improvement”.
Conditional and Logical Operators
Conditional and Logical operators can be used in making decision-based programs:
Conditional Operators Logical Operators
Operator Meaning Operator Meaning
= Equal to And Both sides must be true
> More than Or One side or other must be true
< Less Than XOr One side or other must be true but not both
>= More than or equal to Not Negates truth
<= Less than or equal to
<> Not Equal to
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 50 of 75
Developing Applications – Visual Studio Class 8
Repetition:
In computer programming, a loop is a sequence of instructions that is repeated until a certain
condition is reached. An operation is done, such as getting an item of data and changing it, and then
some condition is checked such as whether a counter has reached a prescribed number
In Visual Basic, we have two different structures that support repetitions, or loops as they are called
in programming languages.
For…Next loop
What if we want to add all the integers from 1 to 50? Of course, we are not going to start writing
1+2+3+…, we are going to program the computer to do the same thing using loops.
Follow the steps below to create a program using Loops.
• Create a new form with two labels and one button and edit their text preferably as shown in
the example.
• Double click on the button and type the code.
st
• In the 1 line declare the “i” variable as an integer.
nd
• In the 2 line declare the “sum” variable as an integer.
rd
• In the 3 line set the value of “sum” to 0.
th
• In the 4 line For loop is defined that i=1 to 50 means it will run
50 times and increment 1 in the value of sum.
th
• In the 5 line, while the loop runs every time it will add the value
of “i” in the sum variable.
Do…Next loop
In repetition do loop is used when we don’t know exactly how many
times this loop will run. Do loop will run until a condition is met or while a
condition is true.
Follow the steps to create a program to add all integers starting from 1
until the sum is 500 or greater.
• Create a new form with a button and a ListBox and name
it lstResults. ListBox is another type of control
element and can be added through toolbox it is used
to have a list of options for users to select but here
we have used only to display the output of the
Do loop program.
• The Do…Loop structure does not increment any
counter variable automatically, so we have included
the instruction i = i + 1 to increment it by one inside
the loop.
• With the instruction lstResults.Items.Add(i & vbTab & sum), we
add one line in each loop to the ListBox, containing the current
counter value and the current sum.
• The & operator is used to concatenate the different values into a
single line and the vbTab is a predefined constant of Visual Basic
representing a tab space.
• The loop here runs for as long as the value of the sum is smaller than 500.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 51 of 75
Developing Applications – Visual Studio Class 8
Mouse Events
Events are basically a user action like a key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events when they
occur. Mouse events occur with mouse movements in forms and controls. Following are the various
mouse events related to a Control class.
• MouseDown − it occurs when a mouse button is pressed
• MouseEnter − it occurs when the mouse pointer enters the control element
• MouseHover − it occurs when the mouse pointer hovers over the control element
• MouseLeave − it occurs when the mouse pointer leaves the control element
• MouseMove − it occurs when the mouse pointer moves over the control element
• MouseUp − it occurs when the mouse pointer is over the control element and the mouse
button is released
Follow the steps to create a program in which we will detect the Mouse Event in VS.
• The MouseHover event triggers when the mouse cursor hovers over a certain area.
• In the following example, we are going to display a pop-up window containing a message,
whenever the mouse hovers on the button inside our program’s form.
• Create a new form only with one button.
• Double click on the button to open the script
menu and then open the general tab on the
top of the current script window as shown in
the example.
• Select (Form1 Events).
• Then open the declaration window right next to it to select the MouseEvent by scrolling
down which is MouseHover in this case
• After selecting the MouseHover option from the declaration window, additional code will
automatically be added.
• In that part, we will add a predefined feature MsgBox().
• Next, we will declare a string value to display in parenthesis of this MsgBox(“this popup
window appears whenever the mouse hovers on this button”)
Add this
piece of
code
• Execute the program by debugging and also test it by Hovering the mouse on the button.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 52 of 75
Developing Applications – Visual Studio Class 8
Functions, Subroutines, and Modules:
A Visual Basic 2010 function is 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.
In Visual Basic 2010, there are two types of functions, the built-in functions and the functions
created by the programmers. Functions created by the programmer are also known as user-defined
functions. In this lesson,
Creating User-Defined Functions:
To create a user-defined function in Visual Basic 2010, you can use the following syntaxes:
Public Function functionName (Argument As dataType,……….) As dataType
OR
Private Function functionName (Argument As dataType,……….) As dataType
The keyword Public indicates that the function applies to the whole project and the keyword Private
indicates that the function only applies to a certain module or procedure. 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.
This BMI calculator is a Visual Basic 2010 program that can calculate the body mass index of a person
based on his or her body weight in kilograms and body height in meters. BMI can be calculated using
the formula weight/( height )2, where weight is measured in kg and height in meter. If the BMI is
more than 30, a person is considered obese. You can refer to the following range of BMI values for
your weight status.
Underweight =<18.5 | Normal weight =18.5-24.9 | Overweight =25-29.9 | Obesity =BMI of 30+
Follow these steps to create a program to calculate BMI:
• Create a new form with four labels, two text boxes, and a button.
• Change the text of all labels as shown in the example.
th
• Change the name of the 4 label(result) to “lblBMI”.
• Change the text of the button to “Calculate BMI”
• Double click on the button to open the script window.
• Enter the following code to create a function.
Private Function
Variable declaration.
Values from TextBoxes.
After calculation from
function, lblText will
have the value of BMI
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 53 of 75
Developing Applications – Visual Studio Class 8
Modules:
Visual Basic application source code is structured into module files with a .vb suffix. By default,
Visual Studio creates a separate module file for each form in an application containing the code to
construct the form. For example, the code to create a form called Form1 will be placed in a module
file named Form1.Designer.vb. Similarly, any code that has been defined by the developer to handle
events from controls in the form will be placed by Visual Studio into a module file called Form1.vb.
Using modules in VB are recommended while creating a complex application as they save space in
your code and also assist to reuse of code like functions.
To create a program using modules follow these steps:
• Create a form with one text box and a button and
change the text to “Code from Module”.
• Right-click on the project from the solution
explorer window and go to Add and then go to
Module and click
• In the next window Module will be automatically
selected give the name to Module or just click on
Add.
• After that, you will see the Module1.vb will start
appearing in the solution explorer window and
the script window of the module will also open.
• In between the Module and End Module lines, we will add our Subroutine.
VB
{ information
Public Subroutine message box
Pre Define
Code
• Using an element from another form in a module requires a declaration with the name of
the form. In this case Form1.TextBox1 is the name of the element from the other form and
its text will appear in the vbinformation box with the title defined as a string.
• Now go back to the form and double click on the button to open the script window.
• It is highly recommended to use the comments while using code from a module to
remember its functionality. Commenting is easy in VB using a ‘ single quote.
• To use the Subroutine/Function in this form we
will simply write its name in this case Pakistan().
• The green line above the sub with a single ‘ quote
is the comment.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 54 of 75
Developing Applications – Visual Studio Class 8
Creating a Good User Interface:
A good interface makes it easy for users to tell the computer what they want to do, for the computer
to request information from the users, and for the computer to present understandable information.
Clear communication between the user and the computer is the working premise of good UI design.
Good interfaces are:
Clear
A clear interface helps prevent user errors, makes important information obvious, and contributes to
ease of learning and use.
Consistent
A consistent interface allows users to apply previously learned knowledge to new tasks. Effective
applications are both consistent within themselves and consistent with one another.
Simple
The best interface designs are simple. Simple designs are
easy to learn and to use and give the interface a
consistent look. Good design requires a good balance
between maximizing functionality and maintaining
simplicity through progressive disclosure of information.
Direct
Users must see the visible cause-and-effect
relationship between the actions they take and
the objects on the screen. This allows users to feel
that they are in charge of the computer's
activities.
Provide Feedback
Keep the user informed and provide immediate
feedback. Also, ensure that feedback is appropriate
to the task.
Aesthetic
Every visual element that appears on the screen
potentially competes for the user's attention. Provide
an environment that is pleasant to work in and
contributes to the user's understanding of the
information presented.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 55 of 75
Developing Applications – Visual Studio Class 8
Bad User Interfaces:
A user interface that doesn’t follow the guidelines for good user experience can cause frustration or
even hours of missing productivity depending on the importance of the program’s job. Imagine a bad
user interface on a program controlling the positions of the aeroplanes in the sky for example. Take
a look at this real (and actually very useful) application that can make you crazy. It’s almost
impossible to use without training or carefully reading its user’s guide.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 56 of 75
Developing Applications – Visual Studio Class 8
Program Debugging and Error Handling:
Error handling is an essential procedure in Visual Basic 2010 programming that helps make a
program error-free. The user does not have to face all sorts of problems such as program crashes or
system hangs. Errors often occur due to incorrect input from the user. For example, the user might
make the mistake of attempting to enter text (string) to a box that is designed to handle only
numeric values such as the weight of a person, the computer will not be able to perform the
arithmetic calculation for text, therefore, will create an error. These errors are known as
synchronous errors.
In this example, we will deal with the error of entering non-numeric data into text boxes that are
supposed to hold numeric values. The program_label here is error_hanldler. When the user enters
non-numeric values into the textbox, the error message will display the text “One of the entries is
not a number! Try again!” If no error occurs, it will display the correct answer.
Follow the steps below to create a program which can handle user input errors:
• Create a new form with five labels, two text boxes, and a button.
st
• Change the text of the 1 label to First Number
nd
• Change the text of the 2 label to Second Number
rd
• Change the text of the 3 label to “Division of First
Number with Second Number” and also change its size
by Maximum Size properties under Layout heading
height=20 and width = 120
th
• Change the text of the 4 label to Result and change its
name to Lbl_Answer
th
• Clear the text of the 5 label to hide it while the program
is running and name it Lbl_ErrorMsg
• Change the text of the Button to Calculate and also
change its name to CmdCalculate
st
• Change the name of the 1 text box to FirstNumber
nd
• Change the name of the 2 text box to SecondNumber
• Double click on the button to open script window and
type this code
Hiding the Error
Message box
Declaration of error
Simple Program for handing that if error
division of two occurs go to error
numbers handler
Response of error
handler in case of error.
Result Label will
displays “Error” and
ErrorMsg box which
was hidden in the first
line of code will be
visible with the Error
Message in “ ”
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 57 of 75
Developing Applications – Visual Studio Class 8
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 58 of 75
Programming Robots and Single-Board Computers Class 8
Programming Robots and Single-Board Computers
What is a 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. 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.
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 experimentation, learning how to program,
building a media player or NAS drive, robotics and
home automation, and 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).
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.
Here’s a Glance of What Each
Component of a Raspberry Pi Does:
• GPIOs- Connect devices to
interact with the 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.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 59 of 75
Programming Robots and Single-Board Computers Class 8
Accessories Needed for the 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.
You need a microSD card to store your files and the Pi’s operating system. The Pi
doesn’t have a 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.
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 allow
the Raspberry pi to be configured
for different purposes, interact with
different circuits, and work with
several types of electronic
components, for example, sensors,
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. Raspberry Pi pins are
labelled in two ways, i.e. the GPIO
pinout labelling and Physical pin
labelling. The physical pin labelling is From this point onwards always refer to this configuration of GPIO
starting from 1 and ending on 40 in
the image.
Ports:
• Raspberry Pi is equipped with four USB 2.0 ports and one LAN Port.
• USB ports allow USB devices to be connected together and transfer data over a USB Cable.
• The LAN port allows the raspberry pi to connect to a network using a wired connection.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 60 of 75
Programming Robots and Single-Board Computers Class 8
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 Minecraft Pi as well as a lightweight
version of Chromium as of the latest version.
Chromium
Wi-Fi/Wireless CPU Usage
Web Browser File Manager
Terminal Bluetooth
Power & Battery
Menu to access
software, tools, and
setting preferences
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.
Click on the Raspberry Pi icon in the taskbar and then go to programming and hit
Python 3 (IDLE).
To follow the great programming tradition, let’s start with the first program
every programmer writes in any language, printing the words “Hello World”.
Write print (“hello world”) on IDLE and hit enter. You should immediately be greeted with hello
world.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 61 of 75
Programming Robots and Single-Board Computers Class 8
Running Python as a Script On IDLE- A script or scripting language is a feature of computer language
with a series of commands within a file that is capable of being executed. Scripts are just the piece of
code, in which the code is written in the form of scripts and get executed. Error checking is done
when the code is executed or run.
• On Python IDLE click File and then New File.
• In the resulting window type the following program and then save the file as “Test1.py” in
the default location.
Program Output
X=10
Y=5
Z= X+Y
print(Z)
• Then press F5 to execute the program.
• The program output will be 15.
Variables
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) or 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.
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.
Values:
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
LIST in Python:
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 62 of 75
Programming Robots and Single-Board Computers Class 8
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 a list could be:
To call a list element is as easy as calling a cell reference in excel:
With this code, python will output “Samsung” as the count in the list starts from 0.
Delete and Add List Elements:
Del command is used to delete a list element as mentioned in the example below:
Code Output
To add an item to the end of the list, use the append() method:
Code Output
Python Conditions and If Statements
These conditions can be used in several ways, most commonly in "if statements" and loops.
IF
An "if statement" is written by using the if keyword.
Code Output
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 for Multiple Conditions
The elif keyword is Python’s way of saying "if the previous conditions were not true, then try this
condition".
Code Output
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".
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 63 of 75
Programming Robots and Single-Board Computers Class 8
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Code Output
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.
Conditional Operators & Logical Operators:
Conditional Operators Logical Operators
Operator Meaning Operator Meaning
== Equal to and Both sides must be true
> More than or One Side or other must be true
< Less than not Negates truth
>= More than or equal to
<= Less than or equal to
!= Not Equal to
Python ‘For’ Loops
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. We will use the following code:
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 ().
Code Output
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 64 of 75
Programming Robots and Single-Board Computers Class 8
First Python Program with 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.
Things we need to complete this project are:
• 1 Breadboard
• 1 LED
• 2 Jumper Wires
• 1 Resistor: 220Ω/1KΩ.
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.
Connect resistor through jumper wire (represented in black
colour) with PIN 6.
Connect the positive leg of the LED with PIN 12 (GPIO 18).
After completing the circuitry, it’s time to move on to Raspberry Pi. Turn on the Raspberry Pi and
follow the steps below:
On the desktop, go the start menu and click on python IDLE and enter the following code:
Code: (only enter this) Function of the code (no need to enter this)
import RPi.GPIO as IO → # calling header file for GPIO’s of PI.
import time → # calling for time library to use sleep command for delays in program
IO.setmode (IO.BCM) → # programming the GPIO by BCM
IO.setup(18,IO.OUT) → # initialize digital pin as an output.
IO.output(18,1) → # turn the LED on (making the voltage level HIGH)
time.sleep(1) → # sleep for a second
IO.output(18,0) → # turn the LED off (making all the output pins LOW)
time.sleep(1) → # sleep for a second
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)
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.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 65 of 75
Programming Robots and Single-Board Computers Class 8
Bread Board: Breadboards are one of the most fundamental pieces when learning how to build
circuits. A breadboard is a construction base for prototyping of
electronics for temporary testing. The following diagram
shows how a breadboard is connected.
Jumper Wire: A jump wire (also known as jumper wire, or jumper) is
an electrical wire, or group of them in a cable, with a connector or
pin at each end (or sometimes without them – simply "tinned"),
which is normally used to connect the components of a breadboard or other
prototype or test circuit. Jumper wires typically have a solid core which means they
have 1 single strand of wire as opposed to the usual multiple thin strands used in electrical
circuits. This makes them easy to bend into a particular shape.
Practical Task: Perform the above-mentioned program using raspberry pi and necessary equipment
as mentioned above.
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:
import RPi.GPIO as GPIO
import time
Refer to the configuration
GPIO.setmode(GPIO.BCM)
of the GPIO diagram→
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)
Practical Task: Perform the above-mentioned program using raspberry pi and necessary equipment
as mentioned above.
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.IN)
gpio.setup(23,gpio.OUT)
while True:
if gpio.input(18):
gpio.output(23,True)
t.sleep(.1)
else:
gpio.output(23,False)
Refer to the configuration of GPIO diagram
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 66 of 75
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
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
Programming Robots and Single-Board Computers Class 8
Building a 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.
Things needed to assemble the Bumble Pi Car:
• Raspberry Pi (with Raspbian OS)
• Pi Shield
• Screw Set
• Chassis (Upper and lower planks and side planks)
• Battery with a zip tie
• DC Motors
• SONAR with Holder
• Servo Motor
• Wheels & Caster Wheel
• Android Mobile Device with TechTree Bumble Pi Application installed in it.
Chassis upper &
lower planks
and side planks Wheels for DC
DC Motors Motor
Caster Wheel for SONAR Holder
the front
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 69 of 75
Programming Robots and Single-Board Computers Class 8
Pi Shield:
Pi Shield is an additional part specially designed for the convenience of the students to avoid using
the hot soldering iron or a hot glue gun. Things will be easily managed by using the Pi Shield as it will
allow us to directly connect the parts of the smart car to raspberry pi without finding the GPIO pins.
Pi Shield will make assembling easier, convenient, and time-efficient.
Connectivity of components on Pi Shield:
LED indicators on Pi Shield:
• Green for Power
• Red for Low Battery.
• Yellow is for Processing.
• Blue is available for
Power Outlet for Bluetooth connectivity.
Right DC Motor battery/adapter
Connector
Power ON/OFF
Switch
Left DC Motor
Connector
Servo Motor SONAR Sensor
Servo Motor
Connector Connector
Connector
STEP 1
Mounting DC Motors on side planks STEP 2
Mounting wheels on DC Motors
After step 2
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 70 of 75
Programming Robots and Single-Board Computers Class 8
Step 3 Caster Wheel
Step 4 Mount Pi Shield to Raspberry Pi
Step 6 Completing the Chassis
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 71 of 75
Programming Robots and Single-Board Computers Class 8
Bumble Pi Programming:
Enter the following code in Python IDLE and save the file with the name of SRC:
from Bluetooth import *
Including the libraries!!
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False) Addressing the GPIO Pins as per
GPIO.setup(16,GPIO.OUT) Pi Shield configuration
MotorL1=21
MotorL2=18
enA=20 Creating variables for motor
functionality
MotorR1=26
MotorR2=12
enB=19
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) Initializing the output pins
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,False)
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,False)
p=GPIO.PWM(enA,1000)
p.start(75)
Setting Up the speed of the Motors
q=GPIO.PWM(enB,1000)
q.start(75)
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", Activating the on-board Bluetooth
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)
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 72 of 75
Programming Robots and Single-Board Computers Class 8
while True:
data=client_sock.recv(1024)
print("Receive[ %s]" % data)
Setting Conditions
if (data=="quit"):
print("quit")
GPIO.cleanup()
break
elif (data=="F"):
GPIO.output(MotorL1,True)
GPIO.output(MotorL2,False) Forward Functionality
GPIO.output(MotorR1,True)
GPIO.output(MotorR2,False)
elif (data=="D"):
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,True) Backward Functionality
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,True)
elif (data=="S"):
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,False) Stop Functionality
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,False)
GPIO.output(16,False)
elif (data=="R"):
GPIO.output(MotorL1,True)
GPIO.output(MotorL2,False) Turn Right Functionality
GPIO.output(MotorR1,False)
GPIO.output(MotorR2,False)
elif (data=="L"):
GPIO.output(MotorL1,False)
GPIO.output(MotorL2,False) Turn Left Functionality
GPIO.output(MotorR1,True)
GPIO.output(MotorR2,False)
client_sock.close()
server_sock.close()
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 73 of 75
Programming Robots and Single-Board Computers Class 8
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 &”
3. You will notice the blue LED light will be on Pi Shield, this means that Bluetooth Module is
ready to connect.
4. Open the TechTree-Bumble pi application on the mobile device which you have
already paired with Bluetooth to this Raspberry Pi.
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.
Note: if the android application screen locks itself or you switch to another application this
connection will be lost.
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”.
3. And enter this command “sudo python /home/pi/SRC.py &” and press ctrl+x
4. The terminal window will ask to save the file, press Y for yes.
5. After that terminal will ask to save this file on the same location where we have to press
Enter key.
6. Unplug the cables and restart the Pi by typing the Reboot keyword within the terminal
window.
7. 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.
The City School /Academics/Computing Curriculum/Class 8/2020-2021 Page 74 of 75
References
Some of the information contained in this document may have been retrieved or derived from the
following websites:
Microsoft Support https://support.microsoft.com/en-us/office
GCF Global https://www.gcflearnfree.org/
WonderShare Filmora https://filmora.wondershare.com/
Scratch MIT https://scratch.mit.edu/
Mobirise https://mobirise.com/help/
Edison https://meetedison.com/robot-programming-software/
WonderShare Edraw https://www.edrawsoft.com/guide/edrawmax/
WonderShare http://support.wondershare.com/
Code.org https://code.org/
Page 75 of 75
This page has been left blank intentionally