CodingandRobotics LearningCompanion
CodingandRobotics LearningCompanion
What is a computer?
A computer is an electronic device that can process and store data, perform
calculations, and execute instructions. It consists of two main parts: hardware and
software. Let's explore these components to understand how they work together.
Hardware
Hardware refers to the physical parts of a computer that you can touch, like the
keyboard, mouse, and screen. It can be further categorized into four main
components:
• Input: These devices allow users to provide information or commands to the
computer, such as keyboards, mice, cameras, and microphones.
• Processing: The central processing unit (CPU) is the brain of the computer. It
performs calculations, interprets instructions, and processes information
based on user input.
• Output: These devices display or present information to the user, such as
monitors, speakers, and printers.
1
Software
Software refers to the programs, instructions, and data that tell a computer what to
do.
It includes applications like word processors, games, and web browsers, as well as
the operating system that manages computer hardware and enables you to interact
with the machine. In simpler terms, software is the stuff that makes computers work
and lets you do different things on them.
Lets look at different types of software.
computer or device.
In simpler terms, system software and
In simpler terms, application software
firmware are like the computer's
is the stuff you directly interact with to
backbone, ensuring everything runs
get things done on your computer or
smoothly and allowing you to use
device.
various programs and features on your
device.
macOS MS Powerpoint)
iOS Games
Android Apps like Whatsapp and Facebook
Linux
Mental Note:
2
Let’s visualise what we just learned in a diagram:
Input
Hardware Output
Processing
Computer
System Software
Software
Application Software
3
Graphical User interface (GUI):
A Graphical User Interface (GUI) acts as a visual aid when we use computers. It
uses pictures and buttons, making it easier for users to interact by clicking, dragging,
and dropping items instead of typing text commands.
Windows GUI
macOs GUI
Xbox Gui
Android GUI
4
Interactive Developing Environments (IDEs)
What is an IDE?
An Integrated Development Environment (IDE) is a software application that
provides easy to use tools and features to help software developers in writing,
editing, and managing source code.
We will explore different IDEs up until the end of Grade 9.
Features of an IDE:
Feature Description
Allows programmers to write, edit,
Code Editing and
manage source code efficiently.
Translates the written code into
Copiling / Interpreting machine-readable language or
executes it directly.
Helps identify and fix errors (bugs) in
the code by allowing step-by-step
Debugging
execution and inspection of
variables.
Colors different parts of the code to
Syntax Highlighting enhance readability and identify
syntax errors
Predicts and completes code as you
Auto-Completion type, reducing errors and improving
coding speed.
Enables tracking changes,
collaboration, and managing
Version Control Integration
different versions of the code using
systems like Git.
Provides tools for organizing and
Project Management: managing project files, resources,
and dependencies.
Allows direct interaction with the
Built-in Terminal system or execution of command-
line operations.
Facilitates easy movement between
Code Navigation code sections, functions, or files for
efficient development.
Displays documentation for libraries
or functions, aiding developers in
Integrated Documentation
understanding and using code
libraries.
Assists in designing graphical user
GUI Builder (if applicable) interfaces for applications without
manual coding.
5
Allows integration of additional tools
Plug-in Support or extensions to customize the IDE
according to the developer's needs.
Offers pre-defined code snippets for
Code Templates common tasks, improving coding
speed and consistency.
Supports the creation and execution
Unit Testing Integration of unit tests to ensure the reliability
of the code.
Activity 1:
Answer the questions below.
1.6 What is the role of the Central Processing Unit (CPU) in a computer?
Activity 2:
Identify possible input, output, processing, and storage process and if
possible identify components used to perform those actions for each of the
scenarios below.
6
2.1 Online Shopping:
Scenario:
A customer selects products on an e-commerce website, the website
processes the order, verifies payment, and updates inventory, and the
customer receives an order confirmation email. Order details are stored in the
website's database.
Scenario:
7
A librarian scans the barcode of returned books, the library system updates the
book's status, checks for late returns, and adjusts inventory, and the system
prints a receipt. Information about checked-in books is stored in the library
database.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
8
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
9
Unit 2: File Management
What is a file?
A file is a unit of data that is stored on a computer.
Files can contain text, images, videos, music, or other types of data.
Files are named and grouped into folders.
What is a folder?
A folder is a collection of files and other folders.
Folders are used to organize files and make them easier to find.
Folders can be nested within other folders to create a hierarchical file system.
windows button + E
or
Click on te yellow icon at the bottom of your screen.
1
Your file manager should look similar to the picture below:
2
Step 3: Choose the file type you want to create:
If we, for example, want to create a text file, then we will click on text file in the pop-
up menu.
3
Skills upgrade: How to move a file:
If you would like to move a file, then you can use the cut feature.
Step 3: Right click on the file you want to move and click on the cut option on the
pop-up menu.
4
Step 4: Paste the file in a new location.
1. Navigate to the location where you wish to move the file to.
2. Click on an open space in the location (usually a folder)
3. Right click and then left click on the paste option on the pop up menu
___________________________________________________________________
5
Skills upgrade: How to copy a file:
If you would like to move a file but keep a copy of the file in its original location, then you can
use the ‘copy’ feature.
6
Step 4: Paste the file in a new location.
1. Navigate to the location where you wish to move the file to.
2. Click on an open space in the location (usually a folder)
3. Right click and then left click on the paste option on the pop up menu
7
File location
When you store a file on your computer, it is saved to a specific location on your hard drive.
The location of a file is called its path.
The path is made up of the folder hierarchy and the name of the file.
For example, the following path identifies the file "[Link]" in the folder
"Documents":
Documents\[Link]
Notice that a backward slash ( \ ) indicates that everything after the backward
slash is contained in a folder indicated before the forward slash.
8
Let’s break down the path mentioned above using a diagram.
Notice the hierarchy of folders and files:
C: (C- drive)
Users
relindeque
Music
New folder(2)
[Link]
If you look at the diagram above you will see that:
• The file ,‘[Link]’, is located in the folder, ‘New folder(2),
• The folder, ‘New folder(2), ' is located in the folder, ‘Music’.
• The folder, ‘Music’, is located in the folder, ‘relindeque’.
• The folder, ‘relindeque’ is located in the folder, ‘Users’.
• And the folder, ‘Users’ is located in the C-drive (a specific hard drive).
•
9
Challenge: File operations.
Instructions:
1. Create a new folder named ‘copied files’ in the folder named ‘MyFiles’.
2. Copy "[Link]" to the ‘copied files’ folder.
3. Navigate to the ‘images’ folder located in the common drive.
4. Move the image file named ‘crocodile rock’ to the ‘copied files’ folder which you have
created.
5. Rename the image file called ‘crocodile rock’ to ‘I love crocodiles’.
6. Delete the file named ‘[Link]’ still located in the ‘MyFiles’ folder.
7. Right-click on a file and explore its path, and write down its path in our workbook.
Self-reflection:
____________________________________
____________________________________
____________________________________
________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
__________________________________
10
Module 2: Introduction to C++
Skills Upgrade: Code::Blocks IDE
Before we start coding, you will first need to familiarise yourself with the Code::Blocks IDE.
Scan the QR code below to watch a video on the basics of VS code.
11
Unit 1: Algorithms
What is an Algorithm?
An algorithm is a set of instructions, almost like a recipe, that tells you exactly what steps to
take to solve a problem or do a specific task.
12
Algorithms have certain key characteristics which they have in common with
each other.
1. Step-by-Step Instructions:
• Algorithms are like a to-do list that tells you what to do one step at a time.
Each step is simple and clear.
2. Repeatability:
• If you follow the same steps with the same ingredients (input), you'll get the
same cookies (output).
• Algorithms work the same way – they're reliable and give consistent results.
• We could use the cookie recipe over and over again, and still be able to eat
the same delicious cookies (if you follow the instructions).
4. Problem-Solving:
• Algorithms are problem-solvers. They help you figure out how to do things,
whether it's finding the quickest way to get to a friend's house or organizing a
list of names.
• Someone had to create that first chocolate chip cookie recipe. Do you think
that they got it right the first time?
5. Efficiency:
• Think of an algorithm like finding the fastest route on a map. It's about doing
things in a smart and quick way, not a slow and messy way. (would you mix
the cookie dough in a bathtub and then bake them outside using only direct
sunlight?)
13
Abstraction:
• Abstraction means focusing on the important parts and ignoring the less
important details.
• You wouldn’t write down how to wash the utensils or in which bowl to put the
cookies in, in the recipe.
• Algorithms are specific but they are also short and sweet
Be imaginative in your approach, using both pictures and descriptions to clarify the plan.
Make sure each step is clearly explained, and feel free to add your personal touch to the
process.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
________________________________
14
Unit 2 Understanding the Environment of C++
Programs
The environment in which a C++ program operates plays a crucial role in the execution and
behaviour of the code.
In this section, we will explore the fundamental aspects of the environment surrounding
every C++ program.
A C++ program is structured into distinct sections, each playing a crucial role in its execution.
Let's explore these sections by examining a basic example:
Header Files:
• Definition:
Header files, like #include <iostream>, are added at the start of the program to give
vital details about external features.
• Purpose:
Including header files allows you to reuse code and forms the compiler about the
elements used in your program.
15
Definitions and Declarations:
• Definition:
This section is a placeholder for additional declarations or definitions specific to your
program.
• Purpose:
It is here that you can declare variables, functions, or classes that will be utilised in
the rest of your code.
Main Function:
• Definition:
The int main() function is the entry point of every C++ program. Execution begins
here, and the program terminates when main returns.
• Structure:
The main function contains a code block within curly braces ( { } ) where the
program's main logic is written. We also refer to the area between the curly braces as
a scope.
• Code Execution:
Code within the main function is executed sequentially, line by line, starting from the
opening curly brace ( { ) and continuing until the closing curly brace
( }).
16
Unit 3: Data Types and Variables in C++
Data Types
Data types play an important role in specifying the nature of values we use in computer
programs.
By categorising data into distinct types, programmers can ensure precision and efficiency in
handling various kinds of information.
Let’s familiarise ourselves with the different data types wich will be used going
forward:
17
Variables
Variables in C++ are named storage locations that hold values of various types, such as
integers, floating-point numbers, characters, or user-defined types. Think of them as jars or
containers which can temporarily store data.
Declaring a variable
variable
data type ;
name
• The data type tells us what kind of values the variable can store. It is
important to remember that only values of the data type which is declared will
be able to be stored in the variable it is assigned to.
• The variable name usually describes the data we wish to store in it. This
could be any word. We could for example call it ‘age’, if we want to store a
user’s age in it, or ‘name’, if we want to store a user’s name in it.
Hint:
When declaring more than one variable
of the same data type, then you could
use the following syntax:
data type var name 1, var name 2, … ;
Example:
Int age, year, amount ;
18
Initialising a Variable.
variable
data type = value ;
name
• The equal sign ( = ) indicates that a value to the right of it will be assigned to
the variable to the left of it .
NB!!: Remember that the data type you use, and the variable’s value need to
correspond, otherwise you will get an error.
19
Changing a Variable’s Value
In C++, you can assign values to a variable after declaring it by using the assignment
operator (=) followed by the desired value.
You can use the following syntax to assign a new value to a variable:
variable
= value ;
name
20
Accessing a Value Stored in a Variable
To access values stored in variables and use them, you can directly reference the variable
name (call its name) within your code, allowing you to retrieve and use the stored value in
calculations, conditions, or other operations.
Example:
Code:
Output Result:
Code Breakdown:
1. Header Section:
• The #include <iostream> statement includes the input/output stream library,
allowing the use of functions like cout for output.
21
2. Using Namespace:
• The using namespace std; statement allows you to use elements from the
std namespace without having to prefix them with std::. This is commonly
used in C++ programs for simplicity.
3. Variable Declaration:
• Two variables, number and newNumber, are declared of type int (integer).
4. Main Function:
• The main function is the entry point of the program.
5. Variable Assignment:
• number = 5;:
Assigns the value 5 to the variable number.
• newNumber = number;:
Assigns the value of number to the variable newNumber. This is a simple
assignment operation, where the right-hand side (number) is assigned to the
left-hand side (newNumber).
6. Output Statement:
• cout << newNumber;:
Outputs the value of newNumber to the console using the cout (console
output) stream. In this case, it will output 5 to the console.
Output:
22
It's important to note that after this assignment, newNumber holds its own copy of the
value, and changes to one variable don't affect the other.
23
3. Follow the Instructions in the Comments:
• The file contains comments with instructions. Read each comment
carefully and follow the provided instructions to complete the tasks.
• Look for sections marked as // Task X: where X is a number. Complete
the tasks as described in those comments.
4. Task Overview:
• Task 1: Declare two variables of different data types.
Important Notes:
• Ensure that you are working on your personal drive under the "C++" folder.
• Follow the instructions in the comments precisely.
• Save your work regularly to avoid losing progress.
• The goal is to gain hands-on experience with variable concepts in C++. The
amount you master will directly depend on how much you practise, who
knows, maybe you become the next Elon Musk
24
Unit 4: C++ Operators
Note that each operator has its own unique use. Understanding the various
uses of an operator, will enable you to know where and how to use them.
Arithmetic Operators
25
Output:
Subtraction Operator ( - ):
The addition operator, indicated by a minus symbol ( - ), is used to subtract one
value from another.
Example:
Code:
Output:
26
Multiplication Operator ( * ):
The multiplication operator, indicated by an asterisk ( * ) is used to multiply values.
Note that we do not use the mathematical symbol ( x ) for multiplying values. The
compiler will recognize this as the letter ‘x’ and will ultimately return an error
message.
Example:
Code:
Output:
27
Division Operator ( / ):
Note that we do not use the mathematical symbol ( ÷ ) for dividing values. The
compiler will not recognise this symbol and will ultimately return an error message.
Example
Code:
Output:
Hint:
It is good practise to store a result from a division operation in a double or
floating-point variable, as the results of division operations often are decimal
numbers.
Example:
5 ÷ 2 = 2.5
28
Modulus Operator ( % )
In the process of dividing numbers, we often encounter situations where the result is
not a whole number, and there is a remainder.
Typically, the result of division includes a decimal portion. However, for a more
detailed understanding of what remains after division, we use a mathematical
operation known as the "modulus" or "remainder" operation.
Let’s compare division operations with modulus operations to see the
difference:
Division:
Consider the division of 11 by 5:
11 ÷ 5 = 2.22
The result of this division is 2.22.
Here we get a decimal result without any remainder.
Modulus:
The modulus operation, denoted by the percentage symbol ( % ), calculates the
remainder when one number is divided by another.
Using the same numbers:
11 % 5 = 1
In this case, the modulus operation gives us the remainder, which is 1.
The remainder signifies the numbers left after the division process.
When we say 11 % 5 = 1, it means that when 11 is divided by 5, there is a remainder
of 1.
This leftover part represents the "extra" or the "remainder" that doesn't fit into the
whole portions during division.
In other words, when we divide 11 by five the closest whole number result is 2,
because 10 ÷ 5 = 2, but 5 x 2 is not equal to 11. To get to 11 we need to add 1. This
number we need to add to get to 11 is referred to as the remainder.
29
Example:
Code:
Output:
30
Comparison Operators
Comparison Operators are used to compare two values with each other. This is done
by asking a question which will return a ‘yes’ or ‘no’ answer.
If the answer is ‘yes’, then the condition will return a true or a 1 value.
Conversely, if the answer is ‘no’, then the condition will return a false or a 0
value.
Notice that the values returned are Boolean data types and you would need to
use Boolean variables to store the result of a conditional operation.
Equal to – operator ( = = ):
The equal to – operator, indicated by two equal signs ( == ), determines if two
values are equal to each other.
It asks the question: “Is the value on to the left of the operator the same as the
value to the right of the operator?”
Note that equal to – operations are not just applied to numbers, such as
integers, doubles, and floating points, but also to other data types.
31
Output:
The result is 0, or false, because if we ask the question: “Is 6 equal to 4 ?”, the
answer will be: “No, 6 is not equal to 4”.
Output:
The result is 0, or false, because if we ask the question: ‘Is “basic bee” equal
to “Basic bee”?’, the answer will be: ‘No, “basic bee” is not equal to “Basic
bee’.
Note that C++ programs are case sensitive, meaning that it takes all
punctuation, upper or lower case, and spaces into consideration. Therefore, if
the two strings being compared are not EXCACTLY the same, then it will return
a false value.
32
Not equal to – operator ( != )
The not equal to – operator, indicated by an exclamation mark and an equal sign
( != ), determines if two values are not equal to each other.
It asks the question: “Is the value on to the left of the operator the different from
the value to the right of the operator?”
Note that the not equal to – operations are not just applied to numbers, such
as integers, doubles, and floating points, but also to other data types.
Output:
The result is 1, or true, because if we ask the question: ‘Is 6 not equal to 4 ?’,
the answer will be: ‘Yes, 6 is not equal to 4.’
33
Example using text (strings):
Code:
Output:
The result is 1, or true, because if we ask the question: ‘Is “basic bee” not
equal to “Basic bee”?’, the answer will be: ‘Yes, “basic bee” is not equal to
“Basic bee’.
34
Other Comparison operators ( <, > , < = , > = )
Below is a table explaining the remainder of the comparison operators.
You might have familiarised yourself with them in mathematics.
Therefore, the equivalent mathematical operators have also been added to the table.
Note that if you should use these equivalent mathematical operators in a C++
program, that it would return an error.
It is additionally good to remember that in C++ the question reads from left to right
whereas in mathematics it depends on which number is larger or smaller.
Math C++
Name Code Example Question asked
Symbol Symbol
< < Less than 5 < 6 // returns true Is 5 less than 6?
> > Larger than 5 > 6 // returns false Is 5 larger than 6?
Is 5 less than OR
equal to 6?
Is 6 less than OR
equal to 6?
Is 5 larger than
OR equal to 6?
Larger than 5 >= 6 // returns false
≥ >=
or equal to 6 >= 6 // returns true Is 6 larger than
OR equal to 6?
35
Logical Operators
36
Let’s look at a practical example:
Code:
Output:
Before we answer that, let’s break this statement into smaller parts:
Condition one: price < 100 or “Is the value of price (50.30) less than 100.00?”
The answer is yes, so condition one is true.
Condition two:
product == “Cookies” or “Is the value of product (“Chocolate”) equal to “Cookies”?”
The answer is no, the value of product is equal to “Chocolate”, not
“Cookies”.
37
When looking at the breakdown above it is safe to say that the conditional
statement can be simplified as follow:
true && false,
You can see that if we asked if ALL conditions are true in this AND operation, that our
answer will be ‘no’.
The AND operation will therefore return a false value.
38
OR operators ( | | )
OR operators, indicated by two vertical bars ( | | ) test if AT LEAST ONE of the
conditions in their scope is true.
Now I want you to imagine a scenario where you have been sent to the shop once
again. This time money is a bit scarce, and you have been instructed to buy either
milk OR bread. Should there be a Black Friday special running and you get both milk
and bread, then great, what a score! If you buy only milk OR only bread, then have
you still followed instructions? The answer is yes, you only had to get one of the
items. What if you don’t buy any of the items? Have you followed the instructions
given to you? No, you haven’t!
OR operators ask the following question: “Is AT LEAST ONE of the conditions
true?”
Below is a table containing different combinations of Boolean values and their
outcomes related to an OR operation.
OR ( | | ) operator (Is ATLEAST ONE condition true?)
Combination Outcome
true | | true true
true | | false true
false | | true true
false | | false false
39
Output:
Why?
Before we answer that, let’s break this statement into smaller parts:
Condition one: price < 100 or “Is the value of price (50.30) less than 100.00?”
The answer is yes, so condition one is true.
When looking at the breakdown above it is safe to say that the conditional
statement can be simplified as follow:
true | | false,
You can see that if we asked if ATLEAST ONE of the conditions are true in this OR
operation, that our answer will be ‘yes’.
The OR operation will therefore return a true value.
40
NOT operators ( ! )
NOT operators, indicated by a single exclamation mark ( ! ), return the opposite
Boolean value of which is indicated in its scope.
If a value in their scope is false, then they will return true. Conversely if a value in
their scope is true, then they will return false! These operators are cheeky little
devils!
Let’s see this cheekiness in action in a practical example:
Code:
Output:
41
Assignment Operator(=)
2. “John” == “john”
3. int x = 10;
int y = 50;
x <= y
4. char a = ‘@’
char b = ‘$’
char c = ‘%’
5. double j = 20.00;
double i = 32.00;
double k = 40.00;
42
Challenge: Exploring Arithmetic operations
1. Download Starter File:
• Locate the file named [Link] on the common drive.
• Copy this file to your personal drive under the "C++" folder.
2. Open the Starter File:
• Open the copied [Link] file in Code::Blocks.
3. Follow the Instructions in Comments:
• The file contains comments with instructions. Read each comment
carefully and follow the provided instructions to complete the tasks.
• Look for sections marked as // Task X: where X is a number. Complete
the tasks as described in those comments.
4. Task Overview:
• Task 1: Perform basic arithmetic operations (addition, subtraction,
multiplication, division) on given variables.
• Task 2: Explore the use of the modulus operator to find remainders.
5. Save Your Work:
• Save your changes frequently using the "Save" option in Code::Blocks.
• Save your final work before closing the file.
Important Notes:
• Ensure that you are working on your personal drive under the "C++" folder.
• Follow the instructions in the comments precisely.
• Save your work regularly to avoid losing progress.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
43
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
________________________________
44
Unit 5: Control Structures: If – else statements
The if- statement is a way of making decisions in programming by testing a condition and
executing specific code based on whether the condition is true or false, allowing us to control
the flow of our program and handle different scenarios.
Notes:
45
Let’s have a look at a practical example:
In the example below, we will determine if someone is old enough to watch a movie,
using an if else statement.
Code:
Output:
46
Explanation:
In the provided code, there is an if statement that evaluates a condition based on the values
of the variables age (10) and ageRestriction (16).
The condition being checked is age <= ageRestriction or “Is the value of age less than or
equal to 16?”
If this condition is true, the code inside the if block will be executed.
In this specific example, since age is 10 and ageRestriction is 16, the condition:
age <= ageRestriction is true.
Therefore, the code within the if block will be executed, and the cout statement inside the if
block will print the message: “You are not old enough to watch this movie!” to the
console.
**If the condition were false, meaning that the value of age was greater than
ageRestriction, the code inside the else block would be executed, and the message
“You are old enough to watch this movie” would be printed to the console.
Challenge: Predict the Output
Given the following code blocks, analyse and determine the output that will be
printed to the console.
Code:
Output: _____________________________________________________
47
Code:
Output: _____________________________________________________
Code:
Output: _____________________________________________________
Copy this file to your personal drive under the "C++" folder.
Open the copied [Link] file in Code::Blocks.
The file contains comments with instructions. Read each comment carefully and
follow the provided instructions to complete the tasks.
48
Look for sections marked as // Task X: where X is a number. Complete the tasks as
described in those comments.
Task Overview:
Task 1: Declare a variable to store the temperature. Prompt the user to enter the
temperature. Use an if-else statement to determine and print whether the weather is
"cold" or "hot" based on the temperature.
Task 2: Modify the temperature values in the condition to fit your local climate or
preferences. Test the program with different temperature values to observe how it
responds based on the if-else condition.
Save your changes frequently using the "Save" option in Code::Blocks.
Save your final work before closing the file.
Important Notes:
Ensure that you are working on your personal drive under the "C++" folder.
Follow the instructions in the comments precisely.
Save your work regularly to avoid losing progress.
Self-reflection:
____________________________________
____________________________________
____________________________________
49
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
__________________________________
50
Unit 6: C++ Functions
Functions are reusable blocks of code that perform specific tasks and are used to
break programs down into smaller manageable pieces , improve code organisation,
and enhance code reusability and readability.
To create a function in C++ with a return value, you need to provide the function
definition along with the return type, function name, and any necessary
parameters.
• In this example, the function adds numOne and numTwo and stores the
result in the result variable.
51
How do I call a function?
To call (or invoke) a function in C++, you use its name followed by parentheses,
passing any required arguments inside the parentheses.
In this example, the add function which was declared in the previous exampled
is called with arguments 5 and 6.
The function will execute, performing the addition operation, and then return the
result.
52
We can compare this abstract concept to the process of making ice
cream to make it more understandable:
Like an ice cream machine, a C++ function executes a set of instructions to do a specific task.
These instructions are contained within the function, allowing us to use them whenever
necessary. The function we'll examine is makeIceCream, responsible for crafting a personalized
ice cream treat.
53
Parameters - Ingredients for the Ice Cream:
Parameters serve as containers for the values passed to the function. In our scenario, sugar,
milk, and flavour represent parameters storing the ingredients for our ice cream.
Here, 20 teaspoons of sugar, 5 liters of milk, and the "Raspberry" flavour are the
actual ingredients (arguments) we provide to the function.
Now let’s look at all the concepts mentioned above as one piece of code and
its output:
Code
54
Output:
• Copy this file to your personal drive under the "C++" folder.
• Open the copied [Link] file in Code::Blocks.
Task Overview:
• Call the makeIceCream function with different arguments to see how the
output changes.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
55
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
56
Unit 7: Control Structures – Loops
Loops are blocks of code which allow us to repeatedly execute a block of code until
a certain condition is met. This way we wouldn’t have to repeat the code manually by
copying and pasting!
loops
57
For loops
When do we use for loops?
For loops are used if you know in advance how many times the loop will need to run.
In other words the loop will have a known start and end point.
Syntax breakdown:
for → This keyword indicates that a for loop is being used.
Initialiser → The initialiser indicates the point at which the loop will start iterating
from. In the example above the loop will start at the value 0.
Condition → The condition indicates a condition that has to be met (return true) for
the loop to stop executing. In the example above the loop will iterate until
x’s value is not smaller than 5 anymore.
Increment → The increment indicates how much the value of the initial value will
increase or decrease after each round of execution. In this example the
value of x will increase with a value of 1 after each round of execution.
58
Let’s see how the value of x in the example will change after each round of
execution until the condition is met:
Expression Meaning
x++ increase x with 1
x += 2 increase x with 2
x += 5 increase x with 5
x -- or x -=1 decrease x with 1
x -= 6 decrease x with 1
59
Output:
• In the example, an integer array named myArray is declared and initialized with
twelve elements.
These elements are: 5, 6, 87, 88, 54, 62, 36, 8, 88, 9563, 484, and 12.
• Within the main function, a for loop is used to iterate over the elements of myArray.
• The loop initialises an integer variable, index, to 0 and continues as long as index is
less than 12 (the length of the array).
• During each iteration, the value at the current index of myArray is printed to the
console using cout.
• This ensures that each element of the array is displayed on a new line. The program
concludes with the end of the for loop and the closing brace for the main function.
60
Let’s see how each value in the array corresponds with the index and round of
execution:
While loops:
• It checks the condition before executing the code inside the loop. This means if the
condition returns false before the first iteration, then the loop will not run at all.
61
Syntax breakdown:
while → This keyword indicates that a while loop is being used.
Condition → The condition indicates a condition that has to be met (return true) for
the loop to stop executing. In the example above the loop will iterate until
x’s value is not smaller than 5 anymore.
Let’s see how the value of x in the example will change after each round of
execution until the condition is met:
File Setup:
• Locate the [Link] file on the common drive.
• Copy the file to your personal drive under the "C++" folder.
• Open the copied [Link] file in Code::Blocks.
62
Task 3: Multiples of 3 with "for" Loop:
• Follow the comments in the file marked as // Task 3:.
• Use a "for" loop to print multiples of 3 up to 30.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
_________________________________
63
Module 3: Electronics Theory
Unit 1: Introduction to Electrical Circuits
An electrical circuit is a closed loop or pathway through which an electric current can flow.
AC electricity is like a swing that keeps moving back and forth. It changes direction
many times per second, going first in one way and then in the opposite direction. It's
like a little dance that the electricity does!
AC is used to power our homes, schools, and pretty much everything that needs a
lot of electricity. It can travel over long distances without losing too much power,
which is why we use it to bring electricity from power plants to our houses.
DC electricity is like a one-way street. It always flows in the same direction, like a
river that only goes downstream. It's steady and doesn't change its path.
DC is used in batteries, like the ones in your phone or remote control. It's also what
powers small electronic gadgets you use every day.
64
The Difference between AC and DC:
Direction of current:
AC: Swings back and forth, changing its direction many times.
AC Sources:
• Power Grid: AC comes from big power plants that create it and send it
through wires to our homes and schools.
65
DC Sources:
• Every circuit has a power source. All DC circuits has a power source with a
permanent positive (+) and negative ( - ) pole.
• The current in DC circuits will always move from the positive pole to the negative
pole of the power source as depicted in the diagram above.
• This type of current is commonly also referred to as conventional current.
66
Basic electronic components
There are a number of electronic components that you will see in almost every circuit
going forward. These components are absolutely crucial for any circuit to work
properly.
Below is a table shortly describing these components and what their functions
are. Some of these will be discussed in more detail later in this module:
Mechanical or electronic
Turn circuits on/off or
Switches devices that control the flow
change their configuration.
of electric current.
67
2. How does Alternating Current (AC) differ from Direct Current (DC)?
A. AC flows in one direction, while DC swings back and forth.
B. AC changes direction, while DC flows steadily in one direction.
C. AC and DC are the same.
D. AC and DC always flow in the opposite direction.
68
7. Which component limits the flow of electric current in a circuit?
A. Conductors
B. Batteries
C. Switches
D. Resistors
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
_______________________________
69
Unit 2: Tinkercad®
What is Tinkercad ® ?
Tinkercad is an online platform developed by Autodesk. It serves as a practical resource for
individuals who want to create and simulate 3D designs, electronic circuits, and code.
Tinkercad is primarily used to visualise and test designs virtually before physically building
them.
1. Cost Efficiency:
Simulation minimizes costs related to physical prototyping, enabling users to rebuild and
improve designs without material expenses.
2. Time Optimisation:
Testing and retesting projects virtually saves time, compared to traditional physical
construction.
3. Risk Mitigation:
Early identification of design issues in the simulation phase reduces risks associated with
physical prototypes.
70
Challenge: Running your first Tinkercad simulation:
Setting up:
1. Go to [Link]
71
4. Type in the code which your teacher has shared with you, and click on “Go to my
class”
72
6. Type in your FULL NAME, using only LOWERCASE characters. Then click on
“That’s me!”.
73
9. Click on your class, where all the Tinkercad® challenges will appear.
Note: To get back to the challenges screen after signing up, you will click on:
Login → Students with Class Code, after which you will follow the steps above from
step 6.
Task:
• Click on the block which says: “Challenge: Run your first Simulation.”
74
• Click on “circuit”.
• Your screen should look like the picture below. Now you are ready to start
building your simulation!
• Add the 9V battery by clicking on its picture in the right pane and dragging it
onto the platform where you are going to build your circuit design.
(Your teacher will show you how to do this).
• Add a light bulb to the platform, by searching for it in the search bar and
dragging it onto the platform once its picture appears.
75
• Your screen should now look like this:
• Now attach wires from both the negative pole and positive poles of the battery
to the two terminals underneath the light bulb. You can do this by clicking on
the pole and then dragging the mouse to where you want the wire to bend or
where you want to attach the other end of the wire. (Your teacher will guide you
with this.)
When you are done, your screen should display the following:
76
• It is important to always use the correct colour conventions for your wires to
avoid confusion. You can achieve this by first clicking on the wire of which you
want to change the colour of and then clicking on the colour dropdown in the
top tab. Once you have done that, you can click on the colour you want to
change the wire to.
Remember:
Once you have completed this step, your screen should display the following:
77
• Now it is time to test if your circuit works! To do this you can run the
simulation by clicking on the “Start Simulation” button.
If you build the circuit correctly, the light bulb will turn on.
Note: If you want to stop the simulation, you can just click on the same button,
which now reads “Stop Simulation”.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
___________________________________
78
Unit 3: Ohm’s Law
• According to Ohm's Law (V = I x R), if you increase the resistance in a circuit while
keeping the voltage constant, the current flowing through the circuit will decrease.
• Conversely, if you decrease the resistance in a circuit while keeping the voltage
constant, the current flowing through the circuit will increase.
79
What will happen if I increase / decrease the current in a circuit according to
Ohm’s Law?
• If you increase the current while keeping the voltage constant, the resistance in the
circuit must decrease.
• Conversely, if you decrease the current while keeping the voltage constant, the
resistance in the circuit must increase.
The brightness of an LED (Light-Emitting Diode) is directly related to the current flowing
through it. Therefore, if the current increases in an LED circuit, the brightness of the LED will
also increase, and if the current decreases, the brightness will decrease.
Imagine you have a circuit consisting of a resistor and a power supply. The resistor has a
resistance value of 50 ohms. The power supply provides a voltage of 10 volts You want to
determine the current flowing through the circuit (I).
EXAMPLE
STEP3 Substitute the values into the equation which you have (10) = I(50)
identified in step 1
STEP 4 Get “I” alone by dividing with the number it’s multiplied 1050 =
with. I(50)50
80
Calculating the resistance (R)
Suppose you have a circuit powered by a battery with a voltage of 12 volts. The circuit is
connected to a light bulb, and the current flowing through the bulb is 2 amperes. You want
to determine the resistance in the circuit .
EXAMPLE
STEP3 Substitute the values into the equation which you have (12) = (2)R
identified in step 1
STEP 4 Get “R” alone by dividing with the number it’s multiplied with. 122=
(2)R2
Suppose you have a circuit with a current of 3 amperes flowing through a resistor with a
resistance of 8 ohms . You want to determine the voltage .
EXAMPLE
STEP3 Substitute the values into the equation which you have V =(3)(8)
identified in step 1
81
Different Units of Measurement
Because values often span over large ranges it can become quite difficult to keep track of
numbers.
Imagine that we said that the distance from Johannesburg to Cape Town is One million three
hundred ninety-eight thousand meters (1 398 000m), instead of just saying One thousand
three hundred and ninety-eight kilometres (1389km)?
Different units help us to simplifying values by using a scale. The units of measurement used
in Ohm’s law is no different.
When using Ohm’s law, it is very important to only use basic units of measurements to get
an accurate answer. This means that any larger or smaller units must first be converted to
basic units of measurement.
The table below explains how to convert various units of measurements for voltage,
current, and resistance to their basic units of measurement:
Resistance (Ω)
Measurement Unit Symbol Conversion formula to Ohms
Ohms Ω -
Micro-ohms µΩ 1 Ω = 1 µΩ / 1,000,000
Milli-ohms (mΩ) mΩ 1 Ω = 1 mΩ / 1,000
Kilo-ohms (kΩ) kΩ 1 kΩ = 1 Ω × 1,000
Mega-ohms (MΩ) MΩ 1 MΩ = 1 Ω × 1,000,000
Voltage (V)
Measurement Unit Symbol Conversion formula to Volts
Volts (V) V -
Microvolts (µV) µV 1 V = 1 µV / 1,000,000
Millivolts (mV) mV 1 V = 1 mV / 1,000
Kilovolts (kV) kV 1 kV = 1 V × 1,000
Megavolts (MV) MV 1 MV = 1 V × 1,000,000
Current (A)
Measurement Unit Symbol Conversion formula to Amperes
Amperes (A) A -
Micro-amperes (µA) µA 1 A = 1 µA / 1,000,000
Milli-amperes (mA) mA 1 A = 1 mA / 1,000
Kilo-amperes (kA) kA 1 kA = 1 A × 1,000
Mega-amperes (MA) MA 1 MA = 1 A × 1,000,000
*Remember to replace the value 1 with the actual value presented in practice.
82
Challenge: Ohm’s Law in Practice
The circuit depicted above has an LED connected to a 9V battery. The current flowing
through the LED is 915mA, which is too much, considering that the LED can accommodate
an absolute maximum current of 20mA. To fix this problem, we will have to add a resistor to
lower the amount of current to suitable levels.
Use Ohm’s law to calculate the amount of resistance the resistor will need to have.
83
Challenge: Calculate the Missing Value
1. A circuit has a voltage of 12V and a resistance of 300 Ω. What is the current flowing
through the circuit?
3. A light bulb with a resistance of 100 Ω is drawing a current of 0.5 A. What is the
voltage across the light bulb?
4. A resistor with a voltage drop of 9V has a current of 150 mA flowing through it. What
is the resistance of the resistor?
5. A circuit has a current of 0.2 A and a resistance of 500 Ω. What voltage is needed to
power the circuit?
7. A resistor with a current of 400 mA has a voltage drop of 6V. What is the resistance
of the resistor?
8. A circuit has a total resistance of 800 Ω and a current of 125 mA. What is the voltage
across the circuit?
9. A 9V battery is connected to a 220 Ω resistor. What is the current flowing through the
resistor?
10. A circuit has a voltage of 15V and a current of 0.35 A. What is the total resistance of
the circuit?
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
84
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
85
Unit 4: Micro-controllers – Arduino Uno
The Arduino board is like a tiny computer brain that can be programmed to control
other electronic components.
86
• Analog input pins (6):
These pins can read analogue voltages, making them useful for connecting sensors like
temperature sensors or light sensors.
87
• Ground pin:
This pin provides a reference voltage for the analogue inputs and is also used for grounding
circuits. It acts as the negative pole on the Arduino.
• Reset button:
This button restarts the program running on the Arduino Uno.
88
• Power Pins:
There are three power pins which allow us to provide a constant amount of current to
components.
They consist of the:
1. 3.3V,
2. 5V,
3. and Vin (Voltage In) pins.
These pins act like the positive poles of a battery and cannot be programmed like
the Digital I/O pins.
Let us analyse and compare these three pins in the table below:
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
________________________________
89
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
90
Unit 5: Programming with Arduino
The Arduino IDE, is the official software used to write code, upload that code to your Arduino
board, and communicate with it. It's essentially your creative hub for bringing your Arduino
projects to life.
1. Text Editor:
The heart of the IDE is a code editor where you write your Arduino programs, known as
"sketches." It supports syntax highlighting and auto-completion for C/C++ code, which is the
base language used on Arduino. This makes writing and editing code easier and less error-
prone.
2. Compiler:
Once you've written your sketch, the IDE compiles it into machine code that your Arduino
board can understand. This includes checking for syntax errors and ensuring your code
follows proper Arduino programming rules.
3. Uploader:
After compilation, the IDE allows you to upload your sketch directly to your Arduino board via
USB connection. This sends the compiled code to the board's microcontroller, where it can
then be executed and bring your project to life.
4. Serial Monitor:
The IDE also includes a serial monitor that allows you to see data sent from your Arduino
board through the serial port. This is incredibly valuable for debugging your code, monitoring
sensor readings, and interacting with your project in real-time.
91
Arduino IDE interface breakdown
Below is an screenshot of what the interface of the Arduino IDE looks like.
• It's a special function that runs once at the beginning of your Arduino sketch, when
the board is powered on or reset.
• It's used to initialise variables, configure hardware settings, and establish any initial
conditions required for your project.
It cannot be called directly like other functions.
• It must be present in every Arduino sketch, even if it's empty.
92
2. loop() function
• It's the heart of your Arduino sketch, where you place the main code that you want to
run repeatedly.
• It executes continuously after the setup() function has finished.
3. Console
• This is where all errors and other messages from your Arduino will display. Output
results from the code are not displayed output results are not displayed here.
(See serial communication.)
5. Upload buttons
6. Board selector
• The board selector drop down allows us to indicate which Arduino board is being
used.
• It also allows us to select the port (See serial communication).
93
Basic Arduino Functions:
• The Arduino IDE has various built in libraries and functions which are used to
program the Arduino.
• Like with any other function call, these functions will have descriptions and
space for arguments which will do different things.
• Note: Custom functions can still be defined as we have done in previous
modules.
The table below briefly discusses some of the built in Arduino functions.
These functions will be discussed and practiced as you familiarize yourself
with additional components.
Function Description Arguments Example Usage
digitalWrite Sets the specified digital pin on pinMode(pin, value);
the Arduino board to either HIGH
(5V) or LOW (0V), turning the pin: The digital pin number on
output on or off, respectively. the Arduino board.
digitalWrite(13, HIGH);
value: Either HIGH or LOW to
set the pin output to 5V or 0V,
respectively.
analogWrite Writes a PWM (Pulse Width analogWrite(pin, value);
Modulation) signal to the
specified analog (PWM-enabled) pin: The PWM-enabled analog
pin on the Arduino, allowing for pin number on the Arduino
analog output levels. board. analogWrite(9, 127);
94
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
95
Unit 5: Electronic components – Breadboard
What is a breadboard?
A breadboard is a perforated plastic board filled with rows of connected sockets that you can
use to plug in wires, components, and integrated circuits (ICs). This makes it easy to
experiment, test, and modify your circuits without the permanent commitment of soldering.
The rows of sockets are not just random holes; they're strategically grouped and connected
internally in specific ways.
Rows:
• The horizontal rows in the centre of the board are
where the real circuit construction happens.
96
Columns:
These concepts make more sense if you look at the conductive plating built in the
breadboard:
• Notice how the conductive metal is laid out and how it will affect the flow of
current.
• This must be kept in mind when wiring projects going forward to avoid
disconnections or short circuits!!!
97
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
_______________________________
98
Unit 6: Electronic components – Light
Emitting Diodes (LEDs)
LED stands for Light-Emitting Diode. They're miniature semiconductors that convert
electrical energy into light when current passes through them.
Unlike traditional incandescent bulbs that get hot and waste energy, LEDs are highly efficient
and emit cool light, making them an environmentally friendly choice.
Inside an LED, there are two layers of semiconductor material with different electrical
properties.
When voltage is applied, electrons flow from the negative (n-type) layer to the positive (p-
type) layer, and their energy releases as light photons. The colour of the light depends on
the materials used in the semiconductor layers.
99
How to wire a standard LED
• Anode (+):
This is the positive lane, the entrance for
electricity coming into the LED. Think of it as
the "go" light for electrons. It's often the
longer leg of the LED or marked with a plus
sign (+).
• Cathode (-):
This is the negative lane, the exit for
electricity flowing out of the LED. Picture it as the "stop" light for electrons. It's
usually the shorter leg of the LED or marked with a minus sign (-).
Wiring it Up:
The key to making your LED shine is connecting these pins to the right spots.
Power Supply:
You need a source of electricity, like a battery or a power supply that provides the correct
voltage for your LED (most common are 3V or 5V).
The positive pole of the power supply must be connected to the LED's anode (+) pin.
Current Limiting:
A resistor is crucial to limit the current flowing through the LED and prevent it from burning
out.
Choose a resistor value according to your LED's voltage and desired brightness. One end of
the resistor can be connected to the power supply's negative pole.
100
Applications of LEDs:
LEDs have countless applications, from everyday uses like phone flashlights and indicator
lights to more advanced uses like high-definition displays, architectural lighting, and even
medical devices. Their versatility, efficiency, and long lifespan make them the lighting
technology of the future.
Step2: Add an Arduino Uno, an LED, and a resistor and a breadboard to your workspace.
Step 3: Connect the LED's anode to pin 9 of the Arduino. (Remember how the breadboard’s
rails and rows work. You can use any of them as long as there is a flow of current.)
Step 4: Connect the LED's cathode to one end of the resistor. (The resistor can be placed
strategically on the breadboard).
Step 5: Connect the other end of the resistor to a ground pin (GND) on the Arduino.
Step 6: Calculate resistor value using Ohm’s Law. You can use 5V as the voltage and
200mA as the current.
Step 7: Add the code below to your Tinkercad simulation. To access the code, you can click
on code → blocks → select “text” → continue, to get to the code box.
Code:
101
Phase 2: Arduino IDE setup
Step 5: Copy the code you have written from the Tinkercad simulation and paste it in the
LED_Flash sketch.
Step 3: Connect the Arduino to your computer using the USB cable.
Step 4: Click the "Upload" button in the Arduino IDE to transfer the code to the board.
102
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
103
Unit 6: Electronic components – Red, Green,
and Blue Light Emitting Diodes (RGB LEDs)
The Electromagnetic Spectrum – Visible Light
Each wavelength corresponds to a specific colour; red occupies the longer end (700 nm), while
violet resides at the shorter end (400 nm).
Understanding this relationship between wavelength and colour forms the foundation for
manipulating light with RGB LEDs.
Below is a chart which shows the different wavelengths and their corresponding colours
on the visible light spectrum:
104
Additive Colour Mixing
• Unlike subtractive mixing with pigments, where colours blend to create darker
shades, light combines additively.
• For example, red and green combine to form yellow, green and blue create cyan, and
red and blue blend into magenta.
• By precisely controlling the intensity of each individual LED (red, green, and blue),
we can generate a vast spectrum of colours.
105
You can look at the RGB colour wheel below to see how different wavelengths
of light can be added to make different colours:
Note: Capital letters refer to red, green and blue at full intensity, while smaller case
letters refer to red, green and blue at half-intensity.
• A common cathode RGB LED houses three individual LEDs within a single package,
each emitting a primary colour.
• All three LEDs share a common cathode pin, while each colour LED has its
dedicated anode pin for independent brightness control.
• Common Cathode: The single cathode pin connects to the negative side of the
power source, providing a common return path for all internal LEDs. The common
cathode pin is usually the longest out of the
four pins.
• Red, Green, Blue (Individual Anode
Pins): These control pins connect to
respective PWM - pins, that regulate the
brightness of each individual LED.
• The brightness can be controlled through code
on the Arduino as we will explore later.
106
Wiring a Common Cathode RGB LED
• The common cathode is connected to a resistor, which is in turn connected to the
negative side of the power source. This establishes the circuit path and limits the
current flowing through the LED, preventing damage.
• Each Red, Green, and Blue anode pin is connected to its respective PWM-pin.
• The control signals through the PWM pins will independently adjust the voltage or
current to control the brightness of each LED. This will enable us to create different
hues of colour.
A wired RGB LED will look similar to this. Note that any PWM pin could be used:
107
Programming a RGB LED
108
Let’s break each section of this code down to make it more understandable
• The values passed to these parameters determine the colour that the RGB
LED will emit.
• In this context, it controls the brightness of each colour in the RGB LED.
analogWrite usage:
• Inside the setColour function, the analogWrite(9, g) line sets the intensity of
the green colour, analogWrite(10, b) sets the intensity of the blue colour, and
analogWrite(11, r) sets the intensity of the red colour.
• A higher value means a brighter colour, and 0 means the colour is turned off.
• This is how the function controls the individual intensities of each colour in the
RGB LED.
• This step is essential, as it initialises these pins for output, indicating that they
will be used to send signals to the RGB LED.
109
void loop() function:
• The loop function contains a sequence of calls to the setColour function with
different color values and delays between each call.
• The delays (e.g., delay(1000)) control the duration each colour is displayed,
creating a cycling effect.
• A value of 255 means the colour is at its maximum intensity, while 0 means
the colour is turned off.
• Combining different intensities of red, green, and blue allows you to create a
wide spectrum of colours.
• For instance, (255, 0, 0) results in pure red, (0, 255, 0) in pure green, and (0,
0, 255) in pure blue.
• Mixing these colours in different proportions gives you a variety of hues. The
setColour function streamlines this process, making it easy to experiment with
and control the colours emitted by the RGB LED.
110
Challenge: Create your own RGB LED colour cycle.
Phase 1: Simulate in Tinkercad (with Arduino)
Step 1: Log in to Tinkercad and create a new circuit.
Step 2: Add an Arduino Uno, an RGB LED, a resistor, and a breadboard to your
workspace.
Step 3: Connect the RGB LED's anode to pin 9 of the Arduino. Utilize the breadboard’s
rails and rows for proper current flow.
Step 4: Connect the RGB LED's cathode to one end of the resistor, strategically placing
the resistor on the breadboard.
Step 5: Connect the other end of the resistor to a ground pin (GND) on the Arduino.
Step 6: Calculate the resistor value using Ohm’s Law. Assume 5V as the voltage and
200mA as the current.
Step 7: Use the following code for the Tinkercad simulation:
111
Step 8: Run the simulation to observe the RGB LED changing colour.
Step 5: Click the "Upload" button in the Arduino IDE to transfer the code to the
board.
Step 6: Observe the RGB LED cycling through colours on the breadboard.
Step 7: If issues arise, troubleshoot connections and code. Experiment with the code
to create different colour patterns.
112
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
113
Unit 6: Electronic components –
Potentiometers
What are potentiometers?
A potentiometer is a resistor that can adjust the resistance in a circuit to adjust the flow of
current (or amount of electricity) in a circuit.
• Variable resistors are used in many different types of devices and electronics, such
as:
• Radios: to control the volume
• Lights: to control the brightness
• Musical instruments: to control the tone or volume of the sounds, amongst other
things.
A variable resistor works by changing the resistance. As shown in the picture below, a
conductive pad (wiper) is connected to a rotary shaft and connected to a component being
controlled, such as a musical instrument. The wiper moves between two points, 1 and 3, on
the resistive element. The closer the wiper is to a specific node, the lower the resistance will
be.
For example, when measuring the resistance between node 2 and 3 on the variable resistor,
turning the rotary shaft clockwise will cause the wiper (connected to the knob) to decrease
the resistance.
114
Challenge: Fun with Variable Resistors
Fill in the blanks to complete the sentences:
1. A variable resistor is a type of resistor that can ____________the resistance in a
circuit.
2. Variable resistors are used in many different types of devices such as __________
and ___________.
4. If the wiper moves closer to _________, the resistance between two points in the
5. In a circuit diagram, if the wiper moves closer to _________, the resistance between
6. The knob that you turn to adjust the resistance in a variable resistor is connected to
the _________.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
115
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
_______________________________
116
Unit 7: Electronic components – Switches
What are switches?
Switches are mechanical or electronic devices that control the flow of electric current.
Switches are used to run circuits on or off by connecting or disconnecting the conductors in
the circuit.
Closed – When a switch is closed, it means that the conductive material in the circuit are
connected to eachother at the point where the switch is in the circuit, resulting in a flow of
current.
117
In this unit, we will discuss 3 types of switches:
Mechanical switches (push buttons) and relays (type of electrical switches).
Mechanical Switches
118
• Rotary dials: Offer precise control over settings like volume or temperature.
• Foot pedals: Activate functions with pressure from the foot, often used in sewing
machines or musical instruments.
119
Push Buttons
Push buttons are simple physical switches that control electrical circuits. They translate
physical pressure into electrical changes, allowing you to trigger actions with a simple press.
They come in various shapes and sizes, from tiny momentary buttons on keyboards to large
emergency stop buttons on machines.
• Housing: The exterior structure, typically made of plastic or metal, enclosing the
internal mechanisms.
• Actuator: The part you press, like a button cap, lever, or touch-sensitive surface. It
transmits pressure to the internal mechanism.
• Contact mechanism: This heart of the button houses metal contacts separated by a
gap. When pressed, the actuator bridges the gap, completing the circuit.
• Spring: Provides a restoring force, pushing the actuator back to its original position
after pressure is released, opening the circuit.
• Terminals: Electrical connectors soldered to the contact mechanism, allowing the
button to connect to wires and the circuit.
120
How the pins on a pushbutton work
The pushbuttons we are going to discuss will all have 4 pins:
1a, 1b, 2a, and 2b.
121
How to wire a pushbutton to a LED:
You can follow the following steps to wire a pushbutton to a LED:
Step 1: Connect one of the terminals on your pushbutton to the positive pole of a power
source
Step 2: Connect the diagonally opposite terminal to the terminal you connected in step 1 to
the Anode of the LED.
Step 3: Connect the cathode of the led to the negative pole of your power source.
Hint: Always make sure that there isn’t too much current flowing through your
components, by adding a resistor if necessary.
Below are diagrams depicting the process explained in the steps above. Notice
how the flow of current changes if the pushbutton is pressed:
122
Electrical Switch – Relay
They serve several important purposes, and the reasons for using relays include:
• Electrical Isolation: Relays provide electrical isolation between the control circuit
and the load circuit. This isolation is essential in situations where you want to protect
sensitive control components from the high voltages and currents of the load
circuit.
• Voltage and Current Compatibility: Relays allow you to control high-voltage or
high-current circuits with low-voltage and low-current control signals. This is
particularly useful in applications where the control signal is insufficient to directly
control the load.
• Switching: Relays serve as electrically operated switches that can open or close
a circuit. This is particularly useful in applications where you need to control the
on/off state of a load, such as turning lights on and off, opening or closing valves, or
activating/deactivating motors.
Electromagnetism
To understand how relays work, we first need to discuss the concept of
electromagnetism.
The flow of charge, called current, generates a surrounding magnetic field. The direction of
this field can be determined using the right-hand rule.
The right-hand rule involves gripping a wire with your right hand. You thumb will point the
direction of current flow, and your curled fingers will point the direction of the magnetic field
lines circling the conductor.
123
Magnetic push and pull
• When we have two magnetic fields with the same polarity interacting, then
they will repel each other.
To understand how a relay works, you will first need to understand what goes on inside of a
relay.
124
Relays have two states:
State 1:
• When there's no electrical signal or a LOW signal sent to the coil (controlled by the
Arduino code), the coil stays off. That means no electricity flows, and the
electromagnet doesn't create any magnetic waves.
• With the electromagnet off, the NC terminal stays connected to the COM terminal,
allowing electricity to go through the NC terminal ONLY.
State 1 of a relay
State 2:
• When a HIGH electrical signal goes to the coil, it
turns on. The coil gets power and starts
producing magnetic waves, affecting the relay's
pins.
125
The Arduino-relay:
The Arduino relay has the following pins and terminals as seen in the picture
above:
• VCC pin – This pin acts like the positive pin of the relay, powering the red and green
LEDs on the terminal. The VCC pin is usually connected to either the 5V (5 Volt) or
the 3.3V (3.3 Volt) pins on the Arduino board.
• GND (Ground) pin – This pin acts like negative pin of the relay and is usually
connected to any of the GND (ground) pins on the Arduino board.
126
The Tinkercad relay
The Tinkercad relay works exactly like the Arduino relay. It looks slightly different
though, and it doesn’t have VCC or GND pins.
127
Challenge: Switching a LED on and of with a relay and a pushbutton
Materials Needed:
• Arduino board
• Breadboard
• Jumper wires
• Push button switch
• Relay module
• LED
• Resistor (check LED specifications for the appropriate value)
• Power source (battery or USB cable for Arduino)
Instructions:
Connect Power Source:
Step 1: Connect the 5V pin of the Arduino to the positive rail of the breadboard.
Step 2: Connect the GND (ground) pin of the Arduino to the ground rail of the
breadboard.
• Connect a resistor from the NO (normally open) terminal of the relay to the anode
(+) of the LED.
• Connect the cathode (-) of the LED to the remaining open ground rail on the
breadboard.
128
Complete the Circuit:
• Connect the negative rail you have connected to the LED of the breadboard to
the GND (ground) pin of the Arduino.
• Connect the positive rail which you have connected to the relay to the 3.3V pin on
the Arduino.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
129
Unit 7: Serial Communication
Digital Signals
In serial communication, data is transmitted using digital signals, which consist of
binary code represented by 0s and 1s. These digital signals ensure reliable and
accurate transmission of information.
RxD Pin:
The RxD (Receive Data) pin is designated for receiving data from another device in a serial
communication system. This pin is crucial for the device to interpret and process the
incoming data correctly.
Both the Arduino and the USB port in a laptop or desktop computer have TxD and RxD pins.
130
Serial Library in Arduino
Arduino provides a Serial library that simplifies serial communication programming. This
library includes functions and methods that enable easy configuration and management of
serial communication on Arduino boards.
[Link]() Function
• The [Link]() function is used in Arduino programming to initialize serial
communication.
• It sets the baud rate, which is crucial for establishing a consistent communication
speed between devices.
Baud Rate:
• The baud rate refers to the speed at which data is transmitted in a serial
communication system.
• A common baud rate is 9600, representing 9600 bits per second.
131
The Serial Monitor
The Serial Monitor in the Arduino Integrated Development Environment (IDE) is a tool that
allows you to communicate with your Arduino board or compatible microcontroller. It's
commonly used for debugging and testing purposes, as well as for monitoring the output of
your Arduino programs.
Serial Communication:
• The Serial Monitor enables serial communication between your computer and the
Arduino board through the USB port.
• It allows you to send data from your computer to the Arduino (output) and receive
data from the Arduino to your computer (input).
• Make sure your Arduino board is connected to your computer before opening the
Serial Monitor.
132
Receiving Data from Arduino:
• The Serial Monitor displays the data received from the Arduino in the output area.
• This is helpful for monitoring sensor readings, or any output generated by your
Arduino program.
133
Explanation:
[Link](9600);:
• This line initialises the serial communication with a baud rate of 9600.
• The begin function is used to set up the serial communication, and 9600 is the baud
rate at which data will be transmitted.
[Link]("This is the message I am printing out");:
• This line prints the specified message ("This is the message I am printing out") to the
serial monitor.
• The println function appends a newline character after the message, so each
message will appear on a new line in the serial monitor.
delay(1000);:
• This delay slows down the loop, making the message appear in the serial monitor
once every second.
• Without this delay, the message would be printed continuously and rapidly, making it
difficult to read in the serial monitor.
Challenge: Counting to 20
Materials Needed
• Arduino board
• USB cable for Arduino
• Computer
File Management:
Step 1: Locate the "Counting_to_20" sketch in the common drive.
Step 2: Copy the sketch to your personal drive under the "Arduino" folder.
134
Instructions:
Step 1: Connect your Arduino board to your computer using the USB cable.
Step 2: Open the Arduino IDE and Upload the Following Code
Step 3: Open the Serial Monitor: Click on the magnifying glass icon in the top-right corner of
the Arduino IDE to open the Serial Monitor.
Step 5: Observe the Output: You should see numbers 1 to 20 printed on separate lines in
the Serial Monitor.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
135
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
136
Unit 8: Sensors
Detection of Changes: Sensors, like human senses, excel at detecting changes in their
environments.
Signal Conversion: Both sensors and human senses convert stimuli into signals – electrical
for sensors and neural for human senses.
Specialisation: Sensors, similar to human senses, often specialise in specific types of
stimuli, optimising their efficiency.
In this unit, we will explore two sensors: Soil moisture sensors, and infrared (IR) sensors.
137
How to Wire Them:
• Connect the VCC pin to a power source (e.g., 5V on Arduino).
• Link the analog output pin to an analog input pin on the Arduino.
• This function reads the analog value from the sensor connected to the specified
analog pin (A0 - A5).
• The returned value ranges from 0 to 1023, representing the voltage level on the pin.
138
Step 2: Map the analog value to a moisture range.
This can be done by storing the value measured with analogRead() in a variable and
sending it to the serial monitor, and then writing down the value displayed when the soil
moisture sensor is in wet soil and when it is in dry soil.
Step 3: Establish a threshold and use an if – statement to have the Arduino perform different
actions for each state. For example the Arduino can switch on a pump when the soil is dry,
and then switch of a pump when the soil reaches a wet state.
Let’s look at a practical example where the Arduino will print out different messages
when the soil is wet versus when its dry:
Code Explanation:
• The code above reads the measurements of the sensor connected at analog pin A0.
• Then using 2 if statements, it checks if the soil moisture is above 70 (wet) or below
30 (dry).
• If the moisture levels are above 70, it will print: “Soil is wet. Avoid overwatering.” to
the serial monitor.
• If the moisture levels are below 30, it will print: “Soil is dry. Water needed.” to the
serial monitor.
139
Infrared Sensors
140
Creating a Threshold with the Serial Monitor:
• The digitalRead() function in Arduino is used to check the state of a digital input pin.
• It takes one parameter, which is the pin number you want to read.
• The function returns either HIGH (if the voltage is close to the system's supply
voltage, typically 5V) or LOW (if the voltage is close to ground, usually 0V).
Let’s look at a practical example where the Arduino will print out different messages
when there is an object detected in front of the IR sensor vs when nothing is detected
in front of the IR sensor :
Code to print different states to the serial monitor.
Output
When object is in front of sensor When object is not in front of sensor
0 1
(FALSE) (TRUE)
In the example above a reading is taken from the sensor connected to pin 9, using
digitalRead().
The reading will be 0 (FALSE) if the sensor is triggered and 1 (TRUE) if it is not triggered.
141
Code to perform different actions based on the sensor reading.
• The code above takes the reading from the sensor using digitalRead() and will
print out different messages if there is an object in front of the IR sensor vs
when there are no objects in front of the IR sensor.
File Management:
• Locate the "Soil_Moisture_Sensor_Application" folder in the common drive.
• Copy the folder to your personal drive under the "Arduino" directory.
142
Instructions:
1. Connect the VCC pin of the soil moisture sensor to the 5V output on the Arduino.
2. Connect the GND pin of the sensor to the ground (GND) on the Arduino.
3. Link the analog output pin of the sensor to an analog input pin on the Arduino (e.g.,
A0).
4. Write code to read the analog value from the sensor using analogRead(sensorPin)
and print it to the Serial Monitor.
5. Use the Serial Monitor to determine the analog values when the soil is wet and when
it's dry.
6. Establish a threshold (e.g., above 70 for wet, below 30 for dry) and use an if-
statement to print different messages to the Serial Monitor based on soil moisture
levels.
File Management:
1. Locate the "IR_Sensor_Object_Detection" folder in the common drive.
2. Copy the folder to your personal drive under the "Arduino" directory.
Procedure:
1. Connect the VCC pin of the IR sensor to the 5V output on the Arduino.
2. Connect the GND pin of the sensor to the ground (GND) on the Arduino.
3. Attach the signal pin of the sensor to a digital input pin on the Arduino (e.g., pin 9).
4. Write code to read the digital signal from the sensor using digitalRead(sensorPin)
and print the result to the Serial Monitor.
5. Use the Serial Monitor to monitor the sensor readings and determine the state when
an object is detected (e.g., LOW) and when nothing is detected (e.g., HIGH).
6. Establish a threshold by defining conditions for "detection" and "no detection" (e.g., if
the reading is LOW, an object is detected; if HIGH, no object is detected).
143
7. Use an if-statement to perform different actions based on the sensor reading, such
as printing messages to the Serial Monitor.
8. Test the system by placing objects in front of the sensor and observing the
corresponding messages in the Serial Monitor.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
144
Unit 9: Understanding Pull-Down Resistors and Serial
Communication in Arduino
This tri-state can be observed when connecting a push button directly to a circuit and
then measuring its state on the serial monitor.
145
Example of the code used to measure the circuit state:
The output will fluctuate between 1 and 0 randomly when the button is pushed.
This would make it difficult to determine if the button is in a high or low state, and as result
have different blocks of code run for when the button is pressed vs when it is not pressed.
To fix this problem, we can add a pull-down resistor. Or in simpler terms, add a 10kΩ
resistor between the negative pole and where the signal wire is connected to the
button as seen in the picture below:
146
When the resistor is connected to the GND pin, it locks the circuit reading
state to 0. Only now when the button is pressed will the reading be 1.
Wiring:
• Connect one leg of the push button to digital pin 9 on the Arduino.
• Connect the other leg of the push button to the 5V pin on the Arduino.
• Connect a 10kΩ resistor from the same leg of the push button (where it
connects to digital pin 9) to the GND pin on the Arduino.
• Connect the anode of the LED to digital pin 10 on the Arduino.
• Connect the cathode of the LED to the ground pin (GND) on the Arduino.
Coding:
• Open the Arduino IDE on your computer.
• Add the following code as seen in the image below:
147
• Upload the modified sketch to the Arduino board.
• Observe what happens to the LED when the pushbutton is pressed, vs when
it is not pressed.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
148
Unit 10: Buck converters
• Buck converters, also known as step-down converters, are a type of DC-DC (Direct
Current to Direct Current) power converter used to efficiently reduce the voltage
of a direct current (DC) power source.
• They are widely used in electronics, power supplies, and various applications to
provide a stable and lower output voltage than the input voltage.
Increasing the amount of voltage will increase the amount of electrical power the
device connected to the buck converter receives.
Conversely, decreasing the amount of voltage will also decrease the amount of
electrical energy the device connected to the buck converter receives.
149
4. IN + terminal: The IN + terminal is usually connected to the positive pole of a
power source (like the positive pole of a battery or the VIn pin of an Arduino board)
and allows an electrical current to flow from the power source to the buck converter.
5. The OUT + terminal: The OUT + terminal is usually connected to the positive
terminal or pin of a device and allows the new current with an increased or
decreased voltage to flow from the buck converter to the device being controlled.
6. The OUT - terminal: The OUT - terminal is usually connected to the negative
terminal or pin of a device and allows an electrical current to flow back to the buck
converter.
Note that the buck converter has a clear positive and negative side.
• The positive side containing the IN + terminal, potentiometer, and OUT +
terminal facilitates a current moving from the positive pole of a power source
to a device being controlled.
• While the negative side containing the OUT – terminal, and IN – terminal
facilitates a current moving back from the device being controlled to the power
source.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
150
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
151
Unit 11: DC Motors:
Basic Components:
• Stator: The stationary part of the motor that generates a magnetic
field.
• Rotor: The rotating part of the motor that carries
current and experiences a force in the magnetic field
Rotor Current:
• The rotor, typically made of a coil of wire, is placed
within the stator's magnetic field.
• When a DC voltage is applied to the rotor, a current
flow through the coil and a magnetic field is produced
around each wire
152
Interaction of Magnetic Fields:
• The magnetic field produced by the stator interacts with the magnetic
field generated by the current flowing through the rotor. These two
magnetic fields push each other away, resulting in the motor rotating.
Self-reflection:
1. Write your understanding of the concept you have learned in this unit
down below:
____________________________________
____________________________________
____________________________________
____________________________________
2. What did you struggle to understand in this unit (It is always good
practice to ask your teacher these questions when you see them
again).
____________________________________
____________________________________
____________________________________
____________________________________
____________________________________
153
Module 4: Design
Unit 1: Understanding User-Friendly Design
User-Friendly Design:
● User-friendly design refers to creating products, systems, or
154
Unit:2 Creative Use of Recycled Materials:
Using recycled materials creatively is a sustainable approach to design.
By repurposing materials that would otherwise be discarded, you can
create innovative and unique designs while reducing waste.
Here are some tips for using recycled materials creatively and
effectively:
1. Material Selection: Choose recycled materials that are safe, durable,
and suitable for the purpose of your design.
155