0% found this document useful (0 votes)
3 views164 pages

CodingandRobotics LearningCompanion

This document is about coding and robotics,it is uploaded from google classroom,useful to students

Uploaded by

kmabokela66
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views164 pages

CodingandRobotics LearningCompanion

This document is about coding and robotics,it is uploaded from google classroom,useful to students

Uploaded by

kmabokela66
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 1: Basic Concepts

Unit 1: Introduction to Computers:

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.

This Photo by Unknown Author is licensed under CC BY-NC

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.

System Software Application Software

System software is the essential


Application software refers to the
software that controls and manages
programs and tools designed for
the basic operations of a computer or
specific tasks or functions on a
electronic device.
Description

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.

Microsoft Windows Microsoft Office (MS Word, MS Excel,


Example

macOS MS Powerpoint)
iOS Games
Android Apps like Whatsapp and Facebook
Linux

Mental Note:

** Hardware and software work together to make a computer useful. Software


cannot work without hardware and hardware cannot work without software.
* * Computers are more than just laptops and desktops. They can also be
smartphones, ATMs, traffic lights etc.

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.

Below are a few visual examples of different Graphical User Interfaces

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.1 Describe the basic function of a computer.

1.2 How is hardware defined in the context of computers?

1.3 Explain what tangible components make up the hardware of a computer.

1.4 Which category does a keyboard belong to?

1.5 Categorise the keyboard as Input, Processing, Output, or Storage.

1.6 What is the role of the Central Processing Unit (CPU) in a computer?

1.7 Give an example of an output component.

1.8 Provide an example of a hardware component that is responsible for


presenting information to the user.
1.9 Name two types of software and explain how they are used.

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.

2.2 ATM Transaction:


Scenario:
A person inserts their debit card and enters a PIN, the ATM validates the PIN,
checks the account balance, and authorizes the withdrawal, the ATM
dispenses cash and prints a receipt. Transaction details are stored in the
bank's database.

2.3 Word Processing:


Scenario:
A student types an essay using a word processor, the software formats the
text, checks spelling, and counts words, and the student prints a hard copy.
The document is stored on the computer's hard drive.

2.4 Smart Thermostat:

Scenario:

A homeowner adjusts the temperature using a smart thermostat app, the


thermostat adjusts the heating/cooling system and the current temperature is
displayed on the app. Temperature preferences may be stored in the
thermostat's memory.

2.5 Fitness Tracker:


Scenario: A person wears a fitness tracker during a morning run, syncing the data
to their phone (Input). The tracker processes the data to calculate calories burned
and track activity (Processing), the user views daily activity summaries on the
tracker or app (Output). Daily activity logs are stored in the tracker's memory or
synced to a mobile app (Storage).

2.6 Library System:


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.

2.7 Email Communication:


Scenario:
A professional writes and sends an important email, the email software formats
the message and identifies the the recipient’s email adress, and the recipient
receives the email and can read/respond to it. Sent and received emails are
stored in the user's email account.

2.8 Gaming Console:


Scenario:
A gamer uses a console to play an immersive video game, the gaming console
processes the player's actions, renders graphics, and calculates scores, and the
game is displayed on the screen with audio feedback. Game progress and
settings are stored on the console's hard driv

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.

Skills upgrade: How to create a file


To create a file, you will need to use a file manager. A file manager is a software application
that allows you to manage files and folders. Most operating systems come with a built-in file
manager.

Let’s look at the steps to create a file on a Windows 10 operating system:


Step 1: Open the file manager:
Hint: A quick way to open the file manager is to press:

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:

Step 2: Click on the "New" button in the menu.


1. To open the menu, click on the right button on your mouse (henceforth referred to as
‘right click’). Then left click (left button on mouse) on the “new” option.

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.

Step 4: Name the file


You can name your file by typing it in the text field higlighted in blue.
After typing in the file name you can press the ‘enter’ button to save the new name.
In the example below the file is named: “[Link]”.
Notice that the file extention (.txt) is automatically added to the file’s name. This extention
indicates that the file is a text file.

3
Skills upgrade: How to move a file:

Hint: you can also use a shortcut to copy a file by pressing


ctrl + x

If you would like to move a file, then you can use the cut feature.

To cut a file you can follow the following steps:


Step 1: Open the file manager.
Step 2: Locate the file you want to move.
In this example we will use the text file created in the previous section.

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

Now your file should be displayed in the new loacation.

___________________________________________________________________

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.

To copy a file, follow these steps:


Step 1: Open the file manager.
Step 2: Locate the file you want to move.
In this example we will use the text file created in the previous section
Step 3: Right click on the file you want to move and click on the copy option on the
pop-up menu.

Hint: you can also use a shortcut to copy a file by pressing


ctrl + x

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

Now your file should be displayed in the new location.


___________________________________________________________________

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.

How to identify a file’s path


A file’s path can be identified by right-clicking on the file and then clicking on the properties
option on the pop-up menu.

Let’s see what the location is for ‘[Link]’ below:

The path reads as follow: C:\Users\relindeque\Music\New folder (2)

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).

Challenge: Creating and Organizing Files


Instructions:
1. Open the file manager.
2. Navigate to your personal folder.
3. Create a new folder named "MyFiles".
4. Inside "MyFiles", create a new text file named "[Link]".
5. Type a message in "[Link]".
6. Save your file and close it.

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:

1. Write your understanding of the concepts 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).

____________________________________
__________________________________

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.

Imagine following a recipe to bake cookies:


The recipe is the algorithm, and the steps you follow are the instructions.

Source: [Link] ([Link]

12
Algorithms have certain key characteristics which they have in common with
each other.

Let’s look at the characteristics of an algorithm:

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).

3. Input and Output:


• You start with something (input), follow the steps (algorithm/processing), and
end up with something new (output).
• . We can add ingredients together (input), and then process those ingredients
to end up with chocolate chip cookies (output).

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

Challenge: Create your own algorithm:

Create a step-by-step plan (algorithm) for a daily routine you follow.

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.

** We will explore variables, and functions later.

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
( }).

Challenge: Exploring the structure of basic C++ programs.


Your teacher will display different C++ programs and ask you to identify in
which distinct section each line of code is situated.

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:

Datatype Description Example


int (integer) Whole numbers -1,2,3,5,6,7,8,100,2001…

double/ float Decimal numbers 2.2, 50.2333, 44.21….

Collection of characters “John”, “We eat apples”,


string
Indicated by double quotes “P@$$word123”....

char Single characters.


‘A’, ‘c’, ‘2’,’#’, ‘@’....
(character) Indicated by single quotes

void Indicates no datatype N/A

17
Variables

What are 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

You can use the following syntax to declare a variable in C++:

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.

• Remember that all statements in C++ need to end with a semicolon ( ; )

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.

When a variable is initialised, it is given an initial value.


You can use the following syntax to declare a variable in C++:

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:

When the program is executed, it will output 5 to the console.


This is because the value of newNumber is assigned the value of number, which is set to 5
earlier in the code.

Syntax and Logic of Variable Assignment:


The syntax newNumber = number; is an example of a basic assignment statement.
The value on the right side (number) is assigned to the variable on the left side
(newNumber).
This process copies the value stored in number and assigns it to newNumber.

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.

Challenge: Fill in the missing data types.


Instruction: Complete the variable declarations below by assigning them the
correct data types.
1. ______ age = 25;
2. ______ temperature = 98.6;
3. ______ isStudent = true;
4 ______ count = 1000;
5. ______ cpiValue = 3.14;
6. ______ cityName = "New York";
7 ______ totalAmount = 150.75;
8. ______ hasPermission = false;
9. ______ population = 1000000;
10. ______ discountRate = 0.15;

Challenge: Exploring Variables in C++


Instructions:
1. Copy the Starter File:
• Navigate to the common drive and locate the file named
[Link].
(You will be provided with the complete path on the board.)
• Copy this file to your personal drive under the "C++" folder.

2. Open the Starter File:


• Open the copied [Link] file in the Code::Blocks IDE.

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.

Variable 1 → type: string; name: productDescription.

Variable 2 → type: double; name: price.

• Task 2: Initialize the declared variables with appropriate initial values.

productDescription → value: “Felicia Fudge”

price → value: 20.53


• Task 3: Change the values of the initialized variables.

Change the product description to: “Mageu by Moo Belle”.

Change the price to 55.67.

• Task 4: Access and output the values of the variables.

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.
• 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

Operators in programming are symbols or keywords that perform specific


operations on operands (variables, values, or expressions), allowing us to
manipulate data, perform calculations, compare values, and control program flow.

In this unit we will explore 4 categories of operators widely used in C++


programming.

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

Arithmetic operators are used to perform basic mathematical operations on values.


**Basic mathematical operations include addition, subtraction, multiplication, division,
and modulus operations.
Addition Operator ( + )
The addition operator, indicated by a plus symbol ( + ), are primarily used to add
values together.
Example:
Code:

25
Output:

• The output is 15, because:


5 + 10 = 15

Subtraction Operator ( - ):
The addition operator, indicated by a minus symbol ( - ), is used to subtract one
value from another.

Example:
Code:

Output:

• The output is 5, because:


20 – 15 = 5.

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:

• The output is 60, because:


10 x 6 = 60.

27
Division Operator ( / ):

The division operator, indicated by a forward slash ( / ) is used to divide values.

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:

• The output is 3, because


6 ÷ 2 = 3.

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:

The result is 2, because


(4 x 1) + 2 = 6
or
4 can go into 6 one time with a remainder of 2.

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.

Example using numbers:


Code:

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”.

Example using text:


Code:

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.

Example using integers:


Code:

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?

Note: 6 is not less


than 6, but 6 is in
fact equal to 6.

One can therefore


conclude that 2
questions are
asked:
Less than or 5 <= 6 //returns true
≤ <=
equal to 6 < = 6 //returns true
Is the number on
the left less than
the number on the
right, if not, then
is the number on
the left equal to
the number on the
right?

If both are false,


then the condition
will also be false.

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

Logical operators are used in programming to perform logical operations on boolean


values, where boolean values represent either true or false.
These operators allow developers to create more complex conditions by combining
or modifying boolean values. In simpler terms: Logical operators allow us to test a
combination of conditions.

AND operators ( && )


AND operators, indicated by two ampersands ( && ) test if all conditions in its scope
returns true.
Think about it in the following terms: You are sent to the shop, and you are instructed
to buy bread AND milk. If you only buy milk or if you only buy bread, did you follow
the instructions? The answer is no, you had to buy both bread AND milk. You would
therefore only have followed instructions if you bought both.
AND operators ask the following question: “Are all conditions related to the AND
operation true?”
Below is a table containing different combinations of Boolean values and their
outcomes related to an AND operation
AND (&&) operator (Are ALL conditions true?)
Combination Outcome
true && true true
true && false false
false && true false
false && false false

36
Let’s look at a practical example:
Code:

Output:

The output result is 0 or false.


Why?
The conditional statement in the program looks as follow:
price < 100.00 && product == “Cookies”
, which translates to the English question:
Is the value of ‘price’ less than 100 AND is the value of product equal to “Cookies”?

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

Let’s look at a practical example:


Code:

39
Output:

The output result is 1 or true.

Why?

The conditional statement in the program looks as follow:


price < 100.00 | | product == “Cookies”

, which translates to the English question:


Is the value of ‘price’ less than 100 OR is the value of product equal to “Cookies”?

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”.

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:

The output is 0 or false, how unexpected!


Let’s try and make some sense of this by analysing the code snippet.
The condition in the code asks: Is the value of ‘price’ smaller than 100.00?
The answer is ‘yes’ which should return the expected ‘true’ value.
However,…
If you look at the full condition, then you will see that there is an explanation mark
attached to it.
If we write down the condition again with the Boolean result within it scope it would
look like this:
!(true) or in English: “NOT true”
What is NOT true? The answer is false.
You can therefore see that a NOT operator will always return the OPPOSITE
Boolean value contained in its scope.

41
Assignment Operator(=)

The assignment operator, indicated by an equal sign ( = ), is used to assign values to


variables. We have already discussed this under variables.

Challenge: Determine the Boolean result of a conditional statement.


Instructions:
There is a list of conditional statements below. State whether each of the conditional
statements will return a true or false value.
1. 5 > 10

2. “John” == “john”

3. int x = 10;
int y = 50;
x <= y

4. char a = ‘@’
char b = ‘$’
char c = ‘%’

a == ‘@’ | | b == ‘@’ | | c == ‘@’

5. double j = 20.00;
double i = 32.00;
double k = 40.00;

j >= 10.66 && i == 32.00 && k < 50.25

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

What are 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:

• The condition is an expression that evaluates if a value will be true or false.


• If the condition is true, the code block within the first set of curly braces { } is
executed.
• If the 1st condition is false, the code block within the next set of curly braces is
evaluated and the process is repeated until either an condition is true.
• If ALL conditions are false, then the code between the curly braces after the else
keyword is executed.
• Only one code block will be executed.

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: _____________________________________________________

Challenge: Weather Checker


File:

Locate the file named [Link] on the common drive.

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:

1. Write your understanding of the concept you have learned in


this unit down below:

____________________________________
____________________________________
____________________________________

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

What are 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.

In simpler terms: Functions describe what programs do.

How do I define a function (create a blueprint)?

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.

• The return statement is used to return the calculated product as the


function's result.

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.

The returned value, will be 11 as 5 + 6 = 11

The result could be used as needed in further code statements or expressions.

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.

Function Definition - Implementation of the Ice Cream Machine:


The heart of our analogy lies in the function definition, where the ice cream-making process
unfolds:

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.

Function Calls - Placing an Order:


When we want to make a specific ice cream, we place an order (function call) and provide
the actual ingredients (arguments):

Here, 20 teaspoons of sugar, 5 liters of milk, and the "Raspberry" flavour are the
actual ingredients (arguments) we provide to the function.

Return Output - The Ice Cream Cup:


After placing the order, the ice cream machine (function) processes the ingredients and
produces the ice cream, returning a result or output.

Now let’s look at all the concepts mentioned above as one piece of code and
its output:

Code

54
Output:

Challenge: Test out the Ice Cream Machine Code.


File:

Locate the file named [Link] on the common drive.

• 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

What are 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!

Different types of loops:


In this unit we will cover two types of loops most commonly used in C++ as depicted
in the diagram below.

loops

for loop while loop

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.

In other words: the largest value which is smaller than 5 is 4, therefore


the loop will stop executing when the value of x is 4.

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:

Round of execution Value of x


1 0
2 1
3 2
4 3
5 4

Increments and decrements:


The values in a for loop can either increase or decrease with a certain after each round of
execution.

Let’s see how this can be expressed:

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

Using a for loop to iterate through an array:


For loops can be used to perform an action on every element on an array.
Let’s analyse and break down an example where this is done:
Code:

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:

Round index myArray[index] (value in array)


1 0 5
2 1 6
3 2 87
4 3 88
5 4 54
6 5 62
7 6 36
8 7 8
9 8 88
10 9 8563
11 10 484
12 11 12

While loops:

What are while loops?


• A while loop is used when the number of iterations is not known in advance, and the
loop continues to execute as long as a specified condition is true.

• 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.

In other words: the largest value which is smaller than 5 is 4, therefore


the loop will stop executing when the value of x is 4.

Let’s see how the value of x in the example will change after each round of
execution until the condition is met:

Round of execution Value of x


1 0
2 1
3 2
4 3
5 4

Challenge: Magic with Loops

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.

Task 1: Counting Forward with "for" Loop:


• Follow the comments in the file marked as // Task 1:.
• Use a "for" loop to print the numbers from 1 to 10.

Task 2: Even Numbers - "while" Loop:


• Follow the comments in the file marked as // Task 2:
• Use a "while" loop to print even numbers from 0 up to 20.

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.

Task 4: Reverse Counting - "for" Loop


• Follow the comments in the file marked as // Task 4:
• Use a "for" loop to print numbers from 10 to 1 in reverse order.

Task 5: Find Characters - “while” loop


• Follow the comments in the file marked as // Task 5:
• Use a while loop to print all the characters until it reaches a ‘$’ -character in the given
array.

Task 6: Filter Character’s – “for” loop


• Follow the comments in the file marked as // Task 6:
• Use a for loop along with an if statement to print out all the ‘@’ characters in the
given array.

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

What is an electrical circuit?

An electrical circuit is a closed loop or pathway through which an electric current can flow.

Different types of current:

There are two types of current: Alternating Current (AC)


and Direct Current (DC).

Alternating Current (AC)

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.

Direct Current (DC)?

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.

DC: Flows in one direction, like a steady river.

Sources of AC and DC:

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:

• Batteries: Batteries are like little powerhouses that


provide electrical current to things like your phone or
remote control.

• Solar Panels: Some devices, like solar-powered


calculators, use sunlight to make electricity directly.

• Adapters: Many devices, like laptops and game


consoles, use special adapters to change AC from
the wall into DC that they can use.

What do basic DC circuits look like?

• 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:

Component Picture Description Use

Materials with high electrical Transmit electrical signals


Conductors conductivity, allowing the flow and power between
of electric current. components.

Portable energy storage Power electronic devices


Batteries devices that convert chemical when no external power
energy into electrical energy. source is available.

Mechanical or electronic
Turn circuits on/off or
Switches devices that control the flow
change their configuration.
of electric current.

Passive electronic Control current flow,


Resistors components that limit the voltage levels, and protect
flow of electric current. components.

Challenge: Understanding Electrical Circuits


Underline the correct option for each Question:
1. What is an electrical circuit?
A. A path for water flow
B. A closed loop for electric current
C. A highway for cars
D. A playground for children

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.

3. Why is Alternating Current (AC) used to power homes and schools?


A. AC is more expensive.
B. AC can travel long distances without losing much power.
C. AC is safer.
D. AC is only used in batteries.

4. Which of the following is an example of a Direct Current (DC) source?


A. Power Grid
B. Solar Panels
C. Adapter
D. Power Plant

5. What do basic DC circuits look like?


A. A random assortment of components
B. A loop with a power source having a positive and negative pole
C. A straight line with multiple power sources
D. A circle with no power source

6. What is the direction of current in a DC circuit?


A. Changes direction many times
B. Flows back and forth
C. Always flows in the same direction
D. Follows a zigzag pattern

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.

Why do we simulate projects before 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.

4. Projects can be shared easily:


Most simulation software has a share function, which enable users to share virtual projects
over the internet. Imagine having to invite someone to your physical location just to hear
their opinions on your designs!

70
Challenge: Running your first Tinkercad simulation:
Setting up:
1. Go to [Link]

2. Click on “sign up”.

3. Click on “Students, join a Class”.

71
4. Type in the code which your teacher has shared with you, and click on “Go to my
class”

5. Click on “Join with Nickname”

72
6. Type in your FULL NAME, using only LOWERCASE characters. Then click on
“That’s me!”.

7. Click on the profile icon.

8. Click on “My classes”.

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.”

• Click on “ + create new design”

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:

According to convention, wires connected to a negative pole of a power source


must be black; and wires connected to a positive pole of a terminal must be
red.

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

What is Ohm’s Law?


Ohm's Law is a fundamental principle in electrical engineering and physics that relates the
current flowing through a conductor to the voltage across it and the resistance of the
conductor. It is named after the German physicist George Simon Ohm, who first formulated
the law in 1827.

Mathematically, Ohm's Law is expressed as:


V=IxR
where:

V → represents the voltage across


the conductor, measured in volts
(V).

I → represents the current flowing


through the conductor, measured
in amperes (A).

R → represents the resistance of


the conductor, measured in ohms
(Ω).
This Photo by Unknown Author is licensed under CC BY-SA

What will happen if I increase / decrease the resistance in a circuit according


to 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.

What will happen to an LEDs brightness if the current increases / decreases in


a circuit and why?

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.

Steps to calculate values using Ohm’s Law


Calculating the current (I)

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

STEP 1 Identify Values for V; I and R V = 10


I= ?
R = 50

STEP2 Write down the equation for Ohm’s Law V=IxR

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

STEP 5 Write down your answer I = 0.2A

STEP 6 DO NOT FORGET YOUR UNIT OF MEASUREMENT!!!

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

STEP 1 Identify Values for V; I and R V = 12


I= 2
R=?

STEP2 Write down the equation for Ohm’s Law V=IxR

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

STEP 5 Write down your answer R = 6Ω

STEP 6 DO NOT FORGET YOUR UNIT OF MEASUREMENT!!!

Calculating the Voltage (V)

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

STEP 1 Identify Values for V; I and R V=?


I= 3
R=8

STEP2 Write down the equation for Ohm’s Law V=IxR

STEP3 Substitute the values into the equation which you have V =(3)(8)
identified in step 1

STEP 5 Write down your answer V = 24V

STEP 6 DO NOT FORGET YOUR UNIT OF MEASUREMENT!!!

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?

2. A 5V battery is connected to a resistor with a current of 250 mA. What is the


resistance of the resistor?|

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?

6. A 12V battery is connected to a device with a resistance of 240 Ω. What is the


current flowing through the device?

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

What is the Arduino Uno board?

The Arduino board is like a tiny computer brain that can be programmed to control
other electronic components.

• The Arduino Uno can be connected to a computer


using a USB cable to write code to it, using the
Arduino software (IDE).

• Once the code is uploaded, the Arduino Uno can run


the program independently without needing a
computer.

• The code tells the microcontroller how to interact


with the electronic components connected to its
pins.

• We will discuss the Arduino IDE at a later stage in this module.

Pins and parts

• Digital I/O pins (14):

These pins can be used as inputs or outputs.

As inputs, they can read the state of a button or


sensor.

As outputs, they can control LEDs, motors, and other


actuators.

Six of these pins can be used for pulse-width


modulation (PWM), which allows you to control the
brightness of LEDs or the speed of motors.

86
• Analog input pins (6):

These pins can read analogue voltages, making them useful for connecting sensors like
temperature sensors or light sensors.

• Power supply (USB or external):


The Arduino Uno can be powered through the USB connection from your computer or with
an external power supply like a battery or AC adapter.

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:

Pin Voltage Current Use Cases


200 mA (max), 150 mA Main power for Arduino and
5V Regulated 5V
recommended most components
Low-power sensors,
3.3V Regulated 3.3V 50 mA
communication modules
Vin 7-12V external Variable, depends on High-power projects where an
(Voltage In) source source external source is needed.
Notes: USB power disables 5V pin.

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

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.

Here's a deeper dive into its key features:

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.

Let’s break down the basic features of the Arduino IDE:


1. setup() function:

• 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.)

4. Sketchbook File Manager

• The sketchbook file manager allows us to navigate to and open saved


sketchbooks (Arduino files) on the computer.

5. Upload buttons

• These buttons are used to upload files onto the Arduino.


• They are also used to debug the code (scan it for errors).

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);

value: The analog output level


ranging from 0 (always off) to
255 (always on).
pinMode() Configures the specified pin on pinMode(pin, mode);
the Arduino board as either an
INPUT or OUTPUT, defining its pin: The digital pin number on
behavior as either receiving or the Arduino board.
outputting signals. pinMode(5, OUTPUT);
mode: Either INPUT or
OUTPUT to configure the pin
as an input or output,
respectively.
delay() Pauses the execution of the delay(time);
program for the specified
number of milliseconds, allowing time: The number of delay(1000);
for timing and control of program milliseconds to pause the
flow. program execution.

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.

How does a breadboard work?

The rows of sockets are not just random holes; they're strategically grouped and connected
internally in specific ways.

Here's the breakdown:


Power Rails:
• The long vertical strips on the sides of the board
are called power rails (usually red for positive and
blue or black for negative).

• These rails run continuously along the entire length


of the board, providing a common power source for
your components.

Rows:
• The horizontal rows in the centre of the board are
where the real circuit construction happens.

• Each row is electrically connected internally in


groups of five sockets. This means that any
component inserted in the same row will share the
same electrical potential.

96
Columns:

• The vertical columns are not connected


internally.
• They allow you to isolate components from
each other, creating separate branches and
pathways within your circuit.

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)

What are 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.

How do LEDs work?

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

Standard LEDs have just two pins:

• 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.

Connecting the LED:


The other end of the resistor can finally be connected to the LED's cathode (-) pin.

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.

Challenge: Flashing an LED

Phase 1: Simulate in Tinkercad (with Arduino)

Step1: Log in to Tinkercad and create a new circuit.

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:

Step 8: Run the simulation to observe the LED flashing.

101
Phase 2: Arduino IDE setup

Step 1: Locate the "LED_Flash" sketch in the common drive.

Step 2: Copy it to your personal drive under the "Arduino" folder.

Step 3: Launch the Arduino IDE.

Step 4: Open the copied "LED_Flash" sketch.

Step 5: Copy the code you have written from the Tinkercad simulation and paste it in the
LED_Flash sketch.

Phase 3: Build the physical circuit

Step 1: Gather the materials below:

• Arduino Uno board


• USB cable
• Breadboard
• LED
• Resistor (220Ω)
• Male to male wires (The wires with 2 pointy sides).

Step 2: Follow the same wiring connections as in Tinkercad.

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.

Step 5: Observe the LED flashing on the breadboard.

Step 6: If it doesn't work, troubleshoot connections and code.

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

Visible light comprises of electromagnetic waves encompassing wavelengths ranging from


approximately 400 to 700 nanometres.

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.

• Combining primary colours creates new hues with increasing intensity.

• 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.

Anatomy of a Common Cathode RGB LED

• 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 RGB LED Pins can be broken down as follow:

• 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

The code to programming a RGB LED could look like this:

108
Let’s break each section of this code down to make it more understandable

void setColour(int r, int g, int b) function:


• This function takes three parameters (r, g, b), representing the intensity of the
red, green, and blue colours, respectively.

• The values passed to these parameters determine the colour that the RGB
LED will emit.

• The function uses analogWrite to set the intensity of each colour.

• The analogWrite function in Arduino allows you to output a variable voltage


level between 0 (fully off) and 255 (fully on) on a digital pin.

• 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.

• The values passed to analogWrite range from 0 to 255.

• 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.

void setup() function:


• In the setup function, pinMode is used to set pins 9, 10, and 11 as OUTPUT.

• 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.

• For example, setColour(255, 0, 0) sets the LED to red, setColour(0, 255, 0)


sets it to green, and so on.

• The delays (e.g., delay(1000)) control the duration each colour is displayed,
creating a cycling effect.

Color representation and values out of 255:


• The values passed to setColour are in the RGB colour model, where each
colour component (red, green, and blue) ranges from 0 to 255.

• 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.

Phase 2: Arduino IDE setup

Step 1: Locate the "RGB_LED" sketch in the common drive.


Step 2: Copy it to your personal drive under the "Arduino" folder.
Step 3: Launch the Arduino IDE.
Step 4: Open the copied "RGB_LED" sketch.
Step 5: Replace the existing code with the one from the Tinkercad simulation.

Phase 3: Build the physical circuit

Step 1: Gather the materials listed below:

• Arduino Uno board


• USB cable
• Breadboard
• RGB LED
• Resistor (calculated value)
• Male to male wires
Step 2: Follow the same wiring connections as in Tinkercad.
Step 3: Connect the Arduino to your computer using the USB cable.
Step 4: Copy the code on Tinkercad into the Arduino IDE screen.

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.

Where are variable resistors used?

• 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.

How do variable resistors work?

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 ___________.

3. The wiper in a variable resistor is connected to a _________ shaft.

4. If the wiper moves closer to _________, the resistance between two points in the

circuit will be low.

5. In a circuit diagram, if the wiper moves closer to _________, the resistance between

two points will be higher.

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.

Switches can have one of two states:


Open – When a switch is open, it means that the conductive material in the circuit are not
connected to each other at the point where the switch is in the circuit, resulting in no flow of
current.

This Photo by Unknown Author is licensed under CC BY-SA

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.

This Photo by Unknown Author is licensed under CC BY-SA

117
In this unit, we will discuss 3 types of switches:
Mechanical switches (push buttons) and relays (type of electrical switches).

Mechanical Switches

What are mechanical switches?


Mechanical switches are physical components which convert human force into a specific,
controlled action.
They operate through direct physical interaction, typically involving a lever, button, or knob,
and translate that movement into an output ranging from electrical control to mechanical
manipulation.

Examples of Mechanical Switches.

• Toggle switches: Simple on/off control for lights and appliances.

This Photo by Unknown


Author is licensed under

• Pushbuttons: Initiate immediate actions like doorbell rings or computer commands.


We will explore push buttons in more detail, later in this section.

118
• Rotary dials: Offer precise control over settings like volume or temperature.

This Photo by Unknown Author is licensed under


CC BY-SA

• Joystick Switches: Tilt in various directions to manuever cursors or control


machines

This Photo by Unknown Author is licensed


under CC BY-NC-ND

• Foot pedals: Activate functions with pressure from the foot, often used in sewing
machines or musical instruments.

This Photo by Unknown Author is licensed


under CC BY-SA-NC

119
Push Buttons

What are 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.

The parts and mechanics of pushbuttons:

• 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.

• When we connect for example, 1a to a power source, and the push


button is not being pressed, then it will conduct electricity to the 1b pin
only.

• When the pushbutton is being pressed then it will be able to conduct


electricity to all of the 4 pins on the pushbutton.

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

What are relays?


Relays are electromechanical devices used in various applications to control electrical
circuits.

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.

This Photo by Unknown Author is licensed under CC BY-SA-NC

123
Magnetic push and pull
• When we have two magnetic fields with the same polarity interacting, then
they will repel each other.

• Conversely, if we have two magnetic fields with the opposite polarity


interacting, then they will attract each other. Opposites attract!

This Photo by Unknown Author is licensed under CC BY-SA-


NC

How do relays work?

To understand how a relay works, you will first need to understand what goes on inside of a
relay.

Every relay has these parts:


1. Common Terminal (COM): This is like the main connection, linked to an external
power source like a battery or AC/DC adapter.
2. Normally Closed Terminal (NC): This refers to the terminal which is connected
to the common terminal in the relay’s normal state.
3. Normally Open Terminal (NO): This refers to the terminal which is
disconnected from the common terminal in the relay’s normal state.
4. Coil: An electromagnet that connects to a device, like an Arduino, to get electrical
signals that turn it on or off.

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.

• These magnetic waves pull the pin away from the


NC terminal towards the NO terminal, connecting
the COM terminal to the NO terminal.

Diagram showing how the magnetic


waves flow around an electromagnet.

State 2 of the relay

125
The Arduino-relay:

The Arduino relay has the following pins and terminals as seen in the picture
above:

• NO (normally open terminal)


• COM (common terminal)
• NC (normally closed terminal)

Additional pins on the Arduino pin:


• IN pin – This pin is usually connected to any of the PWM pins which sends an
electrical signal electrifying the coil in the relay and ultimately changing the state of
the relay. (Moving current away from the NC-terminal to the NO-terminal.)

• 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 Push Button to Relay:

• Connect one leg of the push button to the positive rail.


• Connect the other leg (diagonally opposite to the first pin) of the push button to
the IN pin of the relay.

Connect Relay to Arduino:

• Connect the VCC pin of the relay to the positive rail.


• Connect the GND pin of the relay to the ground rail.
• Connect the COM (common) terminal of the relay to the open positive rail on the
breadboard.

Connect LED to Relay:

• 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.

Testing the Circuit:

• Apply power to the Arduino.


• Press the push button and observe the LED's behaviour.
• Release the push button and note any changes.

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

What is Serial Communication?


Serial communication is a method of data transmission in which information is sent one bit at
a time over a single communication channel or wire.

Serial Communication between an Arduino and a Computer


Arduino boards often communicate with computers using serial communication. This method
facilitates the exchange of data between an Arduino microcontroller and a computer,
enabling tasks such as programming, debugging, and real-time data monitoring.

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.

The difference between Transmission and Receiving


Serial communication involves two fundamental processes: transmission and reception.

• Transmission is the sending of data.


• Reception is the receiving of data.
Understanding the distinction between these processes is crucial for effective
communication between devices.

Transmission and receiving pins.


TxD Pin:
The TxD (Transmit Data) pin is a specific pin in a device that is responsible for transmitting
data to another device in a serial communication setup. It plays a key role in the
unidirectional flow 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.

Printing to the Serial Monitor


• The Serial Monitor is a tool in the Arduino IDE that allows developers to observe and
debug the data being transmitted between the Arduino board and the computer.
• Printing to the Serial Monitor is a common practice for monitoring the output of
Arduino programs.

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).

Opening the Serial Monitor:


• To open the Serial Monitor in the Arduino IDE, click on the magnifying glass icon in
the top-right corner of the IDE.

• 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.

Let’s look at an example of a message which is printed to the serial


monitor.
Code:

Output on the serial monitor:

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 line introduces a delay of 1000 milliseconds (1 second) between consecutive


executions of the code within the loop function.

• 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

What are Sensors?


Sensors are devices designed to detect and measure changes in their environment,
converting physical stimuli into electrical signals or data.
Just like the five human senses, sensors allow electronic systems to perceive and respond
to their surroundings.

Similarities between Sensors and Human Senses.

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.

Soil Moisture Sensors

What they do:


• Soil moisture sensors measure
the water content in soil, aiding in
determining whether the soil is dry
or wet.

• They are instrumental in


applications such as irrigation
systems and agriculture.

137
How to Wire Them:
• Connect the VCC pin to a power source (e.g., 5V on Arduino).

• Connect the GND pin to the ground.

• Link the analog output pin to an analog input pin on the Arduino.

Creating a Threshold with the Serial Monitor:


To establish a wet or dry state using a soil moisture sensor, we will need to create a
threshold which indicates a point where the state changes from dry to wet.

We can do this by following the following steps:

Step 1: Obtain the analog value from the sensor.


We can do this by using the analogRead() function.
Breakdown of the analogRead() function:
Syntax: analogRead(sensorPin):

• 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

What do Infrared (IR) Sensors do?


Infrared (IR) sensors identify infrared radiation emitted or reflected by objects, commonly
used for proximity sensing and object detection.

How to Wire Infrared Sensors:

• Connect the VCC pin to a power source (e.g., 5V on Arduino).

• Connect the GND pin to the ground.

• Attach the signal pin to a digital input pin on the Arduino.

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).

Establishing the state of the IR sensor:


Step 1: Read the digital signal from the sensor using digitalRead().
Step 2: Use the Serial Monitor to monitor the sensor readings.
Step 3: Establish a threshold by defining conditions for "detection" and "no detection."
Step 4: Use an if-statement to determine which action should be followed with “detection”
vs “no detection”.

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.

Challenge: Soil Moisture Sensor Application


Materials Needed:
• Arduino board
• Soil moisture sensor
• Jumper wires
• Power source

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.

Challenge: Infrared (IR) Sensor for Object Detection


Materials Needed:
• Arduino board
• Infrared (IR) sensor
• Jumper wires
• Power source

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

Three Logical States in Digital Circuits:


Before we can discuss what pull down resistors are and why they are used, we must first
discuss digital logical states in circuits.

Digital logic circuits commonly exhibit three states:

• The 'on' state (true or positive or 1).

• The 'off' state (false or negative or 0 ).

• The Tri-State which introduces uncertainty in the absence of additional measures to


define input states clearly. This means that the logic circuit is in a state of both ‘on’ or
‘off’ (true or false, positive or negative, 1 or 0)

This tri-state can be observed when connecting a push button directly to a circuit and
then measuring its state on the serial monitor.

Example of the wiring used:

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.

Challenge: Toggle a LED using a pushbutton.


File Management:
• Locate the "LED_Toggle_Challenge" folder in the common drive.
• Copy the folder to your personal drive under the "Arduino" directory.

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

What are 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.

Breaking down the buck converter:

Parts of the buck converter:

3. Potentiometer: The potentiometer on the buck converter is used to increase or


decrease the amount of voltage being sent out of the buck converter by
turning the screw situated on it.

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.

7. The IN – terminal: The IN – terminal is usually connected to the negative pole of a


power source (like the negative pole of a battery or one of the GND pins of an
Arduino board) and allows an electrical current to flow from the buck converter to the
power source.

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:

A DC (direct current) motor operates based on the principles of electromagnetism


and the interaction between magnetic fields and electric current.

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

Magnetic Field Generation:

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

environments that are easy to use, efficient, and accessible to a wide


range of users.
A user-friendly design enhances the overall user experience by
considering the needs, preferences, and limitations of the users. Here
are some key factors that contribute to user-friendly design:
1. Functionality: A user-friendly product effectively performs its intended
function without unnecessary complexity.
2. Ease of Use: Users should be able to interact with the product without
confusion or frustration. Clear and intuitive interfaces contribute to ease
of use.
3. Accessibility: Design products that can be easily used by people with
varying abilities, including those with disabilities.
4. Consistency: Consistent design elements and interactions throughout
the product make it easier for users to navigate and understand.
5. Feedback: Providing feedback to users through visual cues, sounds, or
tactile sensations helps them understand the product's state and
actions.
6. Visual Appeal: A visually pleasing design can positively impact a user's
perception and make the product more inviting.
7. Clear Instructions: User-friendly products include clear and concise
instructions that guide users in using the product effectivel

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.

2. Preparation: Clean and prepare recycled materials before using them to


ensure they are in good condition.

3. Aesthetics: Incorporate recycled materials that add visual interest and


character to your design. Different textures and colors can make your
design stand out.

4. Combination: Experiment with combining different recycled materials to


create interesting contrasts and textures in your design.

5. Functionality: Ensure that the recycled materials you use contribute to


the functionality of your design. They should serve a purpose beyond
just aesthetics.

155

You might also like