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: SBCs are also increasingly used for a wide range of industrial applications in areas that include robotics and the Internet of things (IoT). • 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. 101 The City School 2023-2024Programming Robots & Single-Board Computers
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 2023-2024
Programming Robots & Single-Board Computers 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. 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. You need a microSD card to store your files and the Pi’s operating system. 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. SD 8 Gb 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 2023-2024
5.3. Raspberry Pi Architecture General purpose input-output (GPIO) 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. 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. 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 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 starting from 1 and ending on 40 in the image. 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20 21 22 23 24 26 27 29 30 31 32 33 34 35 36 37 38 39 40 28 25 10 3V3 Power 3V3 Power GPIO 2 (SDA) GPIO 3 (SCL) GPIO 4 (GPCLK0) GPIO 10 (MOSI) GPIO 9 (MISO) GPIO 11 (SCLK) Ground GPIO 0 (ID_SD) GPIO 5 Ground GPIO 17 GPIO 27 GPIO 22 5V Power 5V Power Ground GPIO 14 (TXD) GPIO 14 (RXD) GPIO 18 (PCM_CLK) Ground Ground GPIO 25 GPIO 8 (CE0) GPIO 7 (CE1) GPIO 1 (ID_SC) Ground GPIO 12 (PWM0) Ground GPIO 16 GPIO 20 (PCM_DIN) GPIO 21 (PCM_DOUT) GPIO 23 GPIO 24 GPIO 13 (PWM1) GPIO 19 (PCM_FS) GPIO 6 GPIO 26 Ground 104 The City School 2023-2024
Programming Robots & Single-Board Computers Raspbian OS Chromium web browser Menu to access tools, software and preferences File manager Terminal Bluetooth Wi-fi/Wireless CPU usage Power & battery 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. 105 The City School 2023-2024
5.4. Python Basics Python is a high-level programming language designed to be easy to read and simple to implement. It is opensource, 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 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. Checkpoint 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. GPIO stands for General Purpose Input/Ouput pins. 106 The City School 2023-2024
Programming Robots & Single-Board Computers # This program adds two numbers x = 10 y = 5 # Add two numbers and store result in z z = x + y # Display the sum print(z) # This defines a variable score and assigns a value to it score = 9 # Display the value stored in the variable print(score) 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: Sample code: 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. 107 The City School 2023-2024
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 5.6. LIST 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 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: # This defines a list called newList newList=[10,20,30,”Samsung”] # Prints the third element in the list; starting from 0 print(newList[3]) Sample code: 108 The City School 2023-2024
Programming Robots & Single-Board Computers Delete Elements in List Add Elements in List Del command is used to delete a list element as mentioned in the example below: # 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) Sample code: Sample code: Output: Output: [10, 30, ‘Samsung’] [‘apple’,‘banana’,‘cherry’,‘orange’] To add an item to the end of the list, use the append() method. The code below demonstrates this: # 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) 109 The City School 2023-2024
5.7. Conditional Statements in Python 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. 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. Conditional statement is a set of rules performed if a certain condition is met. 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. Sample code: Sample code: IF Statement Elif Statement # This program compares two numbers using if a = 33 b = 200 # if block if b > a: print(“b is greater than a”) # This program compares two numbers using elif a = 33 b = 200 # if block if b > a: print(“b is greater than a”) # elif block elif b == a: print(“a and b are equal”) Checkpoint List is just an ordered collection of items which can be of any data type. Del command is used to delete a list element whereas append() method is used to add an item to the list. Del command is used to delete a list element whereas append() method is used to add an item to the list 110 The City School 2023-2024
Programming Robots & Single-Board Computers 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. 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 . Sample code: # This program compares two numbers using else statements a = 33 b = 200 # 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” ) 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 2023-2024
Logical operators are similar to Boolean expressions that return a boolean result. These operators are called binary because they acquire two operands. 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: 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 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 2023-2024
Programming Robots & Single-Board Computers 5.10. Python Functions 5.11. Getting Started with Python and Raspberry Pi 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: Sample code: Output: Hello from a function # This declares the function called my_function() def my_function(): print(“Hello from a function” ) # Calling the function my_function() 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. Following componentes are required for this project: • 1 breadboard • 1 LED • 2 jumper wires • 1 resistor: 220Ω/1KΩ Equipment needed 113 The City School 2023-2024
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 2023-2024
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 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. A 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 B C D E A B C D E F G H I J F G H I J Horizontal holes are linked together But not across the middle divider 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 2023-2024Programming Robots & Single-Board Computers
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) 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. Button Controlled LED 116 The City School 2023-2024
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 Following components are required for this project: • Sonar Sensor • Pi Shield • Raspberry Pi • Power Adapter / Battery • Keyboard, Mouse & LCD Equipment needed 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 echo=27 gpio.setup(trigger, gpio.OUT) gpio.setup(echo, gpio.IN) def distance(): gpio.output(trigger,True) Python is one of the official programming languages at Google and YouTube is one of Google’s products that are powered by Python. 117 The City School 2023-2024Programming Robots & Single-Board Computers
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 2023-2024
Programming Robots & Single-Board Computers 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 • 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 2023-2024
Servo motors are controlled by PWM (Pulse Width Modulation). PWM works like Ontime 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. Bumble Pi is an educational robot kit specially designed for beginners to learn and get handson experience with mechanics, electronics, and Computer Science. Bumble Pi is easy to assemble. Follow the step-wise instruction for making Bumble Pi. • 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. 5.14. Building Smart Robotic Car Equipment needed Chassis (upper and lower planks) Wheels for DC Motor Caster wheel for the front DC Motors 120 The City School 2023-2024
Programming Robots & Single-Board Computers 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. Pi Shield 121 The City School 2023-2024
Steps to Assemble Chasis screws Pi-sheild screws SONAR and servo motor screws 122 The City School 2023-2024
Programming Robots & Single-Board Computers 123 The City School 2023-2024
124 The City School 2023-2024
Programming Robots & Single-Board Computers 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 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 2023-2024
#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 2023-2024
Programming Robots & Single-Board Computers #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) 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 & 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. Checkpoint In Python, a function is a group of related statements that perform a specific task. SONAR is an acronym of Sound Navigation & Ranging. It is used for measuring distance. A servo motor is an electrical device that can push or rotate an object with great precision. 127 The City School 2023-2024
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. 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 128 The City School 2023-2024
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. Let’s Review My Notes! 129 The City School 2023-2024
Appendix Hello World Declaring Private Variable Declaring Public Variable 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 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 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 Developing Applications 130 The City School 2023-2024
Appendix End Sub Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click pub = pub + 1 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 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 If number >= 7 Then lblResult.Text = “Congratulations! You win” End If End Sub End Class 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 2023-2024
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 2023-2024
Appendix For 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 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 2023-2024
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 2023-2024
Appendix 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 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 2023-2024
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 Glossary 136 The City School 2023-2024
Glossary 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 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 2023-2024
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 2023-2024
Glossary 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. 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 2023-2024
140 The City School 2021-2022
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 MICROSOFT SCHOOLS We are a Microsoft School Microsoft