0% found this document useful (0 votes)
1K views79 pages

Coding and Robotics Study Guide - Grade 8 and 9

This document provides an introduction to coding and robotics using Arduino. It includes a table of contents and overview sections on Arduino, C++, the Arduino IDE, the Arduino Uno board, programming LEDs, variables, data types, analog and digital I/O, control structures, functions, and sensors. The guide aims to summarize important concepts for grades 8-9 coding and robotics curriculum and includes icons for steps, important information, and activities.
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)
1K views79 pages

Coding and Robotics Study Guide - Grade 8 and 9

This document provides an introduction to coding and robotics using Arduino. It includes a table of contents and overview sections on Arduino, C++, the Arduino IDE, the Arduino Uno board, programming LEDs, variables, data types, analog and digital I/O, control structures, functions, and sensors. The guide aims to summarize important concepts for grades 8-9 coding and robotics curriculum and includes icons for steps, important information, and activities.
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
You are on page 1/ 79

CODING AND ROBOTICS

Study Guide
Elsabe Matthee
Grade 8 and 9
Table of Contents
About the guide .......................................................................................................... 2
Icons used in this guide .......................................................................................... 2
Introduction ................................................................................................................ 3
What is Arduino? .................................................................................................... 3
What is C++? .......................................................................................................... 3
Arduino IDE ................................................................................................................ 4
What is the Arduino IDE? ....................................................................................... 4
Writing sketches ..................................................................................................... 2
The Arduino Uno board .............................................................................................. 3
The microcontroller ................................................................................................. 3
USB Port................................................................................................................. 4
Power Jack ............................................................................................................. 5
Reset button ........................................................................................................... 5
Power Pins ............................................................................................................. 6
Status LED lights .................................................................................................... 7
Digital and Analog................................................................................................... 7
Digital pins .............................................................................................................. 9
Pulse Width Modulation (PWM) ............................................................................ 10
Analog pins ........................................................................................................... 11
Using the Arduino IDE .............................................................................................. 12
Creating a new project .......................................................................................... 12
Uploading ............................................................................................................. 12
The 5 stages of development ................................................................................... 14
An Arduino program ................................................................................................. 15
Sketch Structure ................................................................................................... 15
Activity 1 ............................................................................................................ 16
The serial monitor ................................................................................................. 16
Activity 2 ............................................................................................................ 19
Comments ................................................................................................................ 20
Why we need comments ...................................................................................... 20
Single line comments............................................................................................ 20
Multi-line comments .............................................................................................. 21

1
Activity 3 ............................................................................................................ 21
Activity 4 ............................................................................................................ 21
Digital I/O Functions ................................................................................................. 22
pinMode() ............................................................................................................. 22
digitalWrite() ......................................................................................................... 22
digitalRead() ......................................................................................................... 23
Time Functions ......................................................................................................... 24
delay()................................................................................................................... 24
delayMicroseconds()............................................................................................. 24
Programming LEDs .................................................................................................. 25
Arduino’s built-in LED ........................................................................................... 25
Activity 5 ............................................................................................................ 26
External LEDs ....................................................................................................... 27
Activity 6 ............................................................................................................ 29
Activity 7 ............................................................................................................ 30
Variables .................................................................................................................. 31
Data types ................................................................................................................ 33
int .......................................................................................................................... 33
Floating-point ........................................................................................................ 33
Activity 8 ............................................................................................................ 34
Analog I/O Functions ................................................................................................ 35
analogRead() ........................................................................................................ 35
analogWrite() ........................................................................................................ 35
Control Structures .................................................................................................... 37
if statement ........................................................................................................... 37
else ....................................................................................................................... 38
Activity 9 ............................................................................................................ 40
Comparison operators .............................................................................................. 41
Activity 10 .......................................................................................................... 42
Boolean operators .................................................................................................... 43
Creating your own functions ..................................................................................... 45
Activity 11 .......................................................................................................... 47
Using sensors .......................................................................................................... 49

2
Infrared Sensor (IR) .............................................................................................. 49
Ultrasonic sensor .................................................................................................. 57
Index ........................................................................................................................ 63
Examples in this guide ............................................................................................. 64
Table of figures ........................................................................................................ 65
References ............................................................................................................... 66

3
About the guide
This guide was written for Robotics in Curro Nelspruit. The aim of this guide is to give
you a summary of the most important aspects of the Arduino board and Arduino
programming as covered in the Curro Curriculum and Assessment Policy Statement
for grades 7 – 9 for Coding and Robotics.

Icons used in this guide

This icon indicates steps that you should follow and practice.

This icon indicates important information that you should study and
memorise.

This icon indicates an activity.

2 Study guide for Arduino


Introduction
What is Arduino?
Arduino is a free and open-source electronics platform with simple hardware and
software. Arduino boards can read inputs such as a light on a sensor, a finger on a
button, or a Twitter message and convert them into outputs such as activating a motor,
turning on an LED, or publishing something online. You can instruct your board by
sending a set of instructions to the board's microcontroller. You use the Arduino
programming language (based on Wiring) and the Arduino Software (IDE) (based on
Processing) to accomplish this. i

What is C++?
C++ is a programming language developed in 1979 by Bjarne Stroustrup and his team
at Bell Laboratories. Forty years later, it is one of the most widely used programming
languages in the world; C++ applications can be found everywhere, from the bottom
of the oceans to the surface of Mars. ii

C++ runs line by line, top to bottom.

i (Arduino, 2022)
ii (Codecademy, 2022)

Introduction 3
Arduino IDE
What is the Arduino IDE?
The Arduino Integrated Development Environment (IDE), also known as the Arduino
Software (IDE), has a code editor, a message area, a text console, a toolbar with
buttons for common functions, and a series of menus. It connects with and uploads
programs to the Arduino hardware. iii The next page shows a diagram of v1.8.19
installed from the Windows Store. For a full list of details on the menu items, visit this
page. To see how to install the IDE, click here. You can also use Arduino’s Web Editor.

iii (Arduino, 2022)

4 Study guide for Arduino


File name IDE Version
Menu bar

Toolbar
buttons

Text editor

Uploading
status

Message
area

Configured
board and
serial port

FIGURE 1 – ARDUINO IDE

2 Study guide for Arduino


FIGURE 2 – THE TOOLBAR

A – Verify: Checks your code for errors before compiling it.


B – Upload: Compiles your code and uploads it to the configured board.
C – New: Creates a new sketch.
D – Open: Presents a menu of all the sketches in your sketchbook.
E – Save: Saves your sketch.
F – Serial Monitor: Opens the serial monitor.

Writing sketches

Programs written using Arduino Software (IDE) are called


sketches. These sketches are written in the text editor and are saved on
your computer.

2 Study guide for Arduino


The Arduino Uno board

FIGURE 3 – ARDUINO UNO BOARD

We need to understand the different parts of the Arduino Uno board so that we can
create amazing projects.

The microcontroller

FIGURE 4 – ARDUINO UNO MICROCONTROLLER

Your code is stored and executed in the microcontroller.

The Arduino Uno board 3


USB Port

FIGURE 5 – ARDUINO UNO USB PORT

We connect the board to our computer by plugging a USB cable into this port.
This allows you to power your board from your computer and upload your sketch to
your board. The code (sketch) will then be stored in the internal memory of the
microcontroller.
When we want to read data from a sensor in the serial monitor or use the serial monitor
to help us debug our program, we also need to connect the computer to this port using
a USB cable.

FIGURE 6 – USB TYPE-B CABLE USED FOR


ARDUINO UNO

4 Study guide for Arduino


Power Jack

FIGURE 7 – ARDUINO UNO POWER JACK

Arduino boards can be powered directly using a 9V power supply. We can also
connect a barrel jack to a battery clip to power the board.

FIGURE 8 – CONNECTING A BARREL JACK TO THE POWER JACK OF THE ARDUINO UNOiv

Reset button

FIGURE 9 – RESET BUTTON ON THE ARDUINO UNO

The board has a reset button that can be used to restart your program from the
beginning. Each time the button is pressed, the Arduino restarts your code from the
first instruction.

iv (Robottronic, 2022)

The Arduino Uno board 5


Power Pins

FIGURE 10 – POWER PINS ON THE ARDUINO UNO

The power pins provide stable supply voltages to your board. Most components that
are used with the Arduino work with 5V or 3.3V. We can use these pins to power the
components.

GND – There are several GND pins on the Arduino, any of which can be used
to ground your circuit.

Vin − This pin also can be used to power the Arduino board from an external
power source, like batteries.
We use DuPont jumper wires to connect batteries or components to these pins.

FIGURE 11 – DUPONT JUMPER WIRESv

v (Alibaba.com, 2022)

6 Study guide for Arduino


Status LED lights
3

2
1

FIGURE 12 – LED LIGHTS ON THE ARDUINO UNO

There are 4 status LEDs on the Arduino board that give us specific information:
1. Power LED indicator
This LED should light up when you plug your Arduino into a power source to indicate
that your board is powered up correctly. If this light does not turn on, then there is
something wrong with the connection, the power supply, or the board.
2. TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX (receive). They appear
in two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate
the pins responsible for serial communication. Second, the TX and RX LED.

The TX LED flashes with different speed while sending the serial data.
RX flashes during the receiving process.
3. On-board Surface Mount LED
This is a built-in or on-board surface mount LED that is connected to digital pin 13.
This LED can be controlled from your sketches.

Digital and Analog


The Arduino board has digital and analog pins that we use to send and receive signals
to and from other devices. To understand the difference between the type of
information digital and analog pins can send or receive, consider the following
analogies:

The Arduino Uno board 7


Notice that the analog sensor would be able to tell you how many apples there are on
the table, but that the digital sensor can only tell you that there IS an apple on the table
or that there is NOT an apple on the table.
Similarly for output devices, a motor driving the wheel of a robot car will either turn at
maximum speed OR not turn at all if it is plugged into a digital pin.
If the motor were connected to an analog pin, you could set the speed of the motor to
any value between the minimum and maximum rotation speeds of the motor.vi
Digital signals only have two states: HIGH and LOW. When set to HIGH, the output
voltage of the pin is 5V. When set to LOW, the voltage is 0V.
Analog signals are variable, meaning that they have multiple states. Analog input
signals can represent such items as temperature. Analog output signals are also
variable and can be used for such things as opening a valve to a desired position.
A digital signal is something like telling if a door is open or not. An analog signal is
something like telling how much the door is open (or closed).

vi (Prinsloo, 2021)

8 Study guide for Arduino


Digital pins

FIGURE 13 – DIGITAL PINS ON THE ARDUINO UNO

The board has 14 digital pins that can be configured as digital input or digital
output. This means that the pins can be used to read or write digital values. Digital
signals can assume only two values: 0 that correspond to 0V and 1 that correspond to
5V. To switch a component, like an LED light off, we will set it to 0V and to switch in
on, we set it to 5V.
Remember! Pins 0 and 1 are used for communication with the computer. Connecting
anything to these pins can interfere with that communication. It also causes failed
uploads to the board. Therefore, we connect components to pins 2 – 13.

The Arduino Uno board 9


Pulse Width Modulation (PWM)
Digital pins that are labelled with the tilde symbol (~) can also be used to generate a
special kind of digital control known as PWM (Pulse Width Modulation).

FIGURE 14 – THE DUTY CYCLES OF PWM

In the image above you will see that PWM also uses 0V and 5V but because the signal
can fluctuate between the two states, you can control the voltage between 0V and 5V.
It imitates an analog signal.
An example of using PWM:

225 191 172 64 0

FIGURE 15 – CONTROLLING LED LIGHTS WITH PWM

10 Study guide for Arduino


Analog pins

FIGURE 16 – ANALOG PINS ON THE ARDUINO UNO

There are 6 analog input pins, A0 to A5. These pins can read the signal
generated from analog sensors like a light sensor and convert this physical value into
a number that can be used by the microprocessor.
The board can accept analog signals that can assume any value in the range 0V to
5V and convert it into a number in the range 0 to 1023.

The Arduino Uno board 11


Using the Arduino IDE
Creating a new project
Once the software starts, you can create a new project:

FIGURE 17 – CREATING A NEW PROJECT

Uploading
Selecting your Arduino board:
To avoid any error while uploading your program to the board, you must select the
correct Arduino board name, which matches with the board connected to your
computer.

Go to Tools → Board and then select your board.

FIGURE 18 – SELECTING THE CORRECT BOARD IN THE IDE

12 Study guide for Arduino


Selecting your serial port:
To be able to upload your sketch to the Arduino board, you must first select the correct
serial port.

Go to Tools → Serial Port and then select your serial port.


This is likely to be COM3 or higher (COM1 and COM2 are usually reserved for
hardware serial ports). To find out, you can disconnect your Arduino board and re-
open the menu; the entry that disappears should be of the Arduino board. Reconnect
the board and then select that serial port.

FIGURE 19 – SELECTING THE SERIAL PORT

Uploading the program to your board:

Click the Upload button in Toolbar.


Wait a few seconds. You will see the RX and TX LEDs on the board flashing. If the
upload is successful, the message "Done uploading" will appear in the status bar.

Using the Arduino IDE 13


The 5 stages of development

Code Save

Verify &
Execute
compile

Upload

FIGURE 20 – 5 STAGES OF DEVELOPMENT IN ARDUINO PROGRAMMING

As we have seen, Arduino uses C++, which is a compiled language. That means that
to get a C++ program to run, you must first translate it from a human-readable form to
something a machine can “understand.” This is called machine code. That translation
is done by a program called a compiler.
When you program in Arduino, you mainly go through 5 phases during development:
1. Code – writing the program.
2. Save – saving the program.
3. Verify and Compile — checking for any programming errors and then
translating the program for the machine to understand. During this phase you
will also debug the errors if needed. Debugging means that you must go
through your code to correct any errors.
4. Upload – uploading your code to the Arduino board.
5. Execute – as soon as it is uploaded the program will start running.
And repeat.

14 Study guide for Arduino


An Arduino program
Sketch Structure
The Arduino program has a very specific structure. The structure consists of two main
functions:

• Setup() function
• Loop() function

Beginning of a function
loop function

What the program does


End of a function

FIGURE 21 – STRUCTURE OF AN ARDUINO PROGRAM

void setup()

The setup function is run when a sketch starts.

It can be used to set variables, pin modes, and begin using libraries, among other
things. The setup function will only run once, after the Arduino board is powered on or
reset.
void loop()

The loop function will be run repeatedly, line by line, from top to bottom.
After the creation of the setup function, that creates and sets the initial values, the loop
function does exactly what its name implies: it loops consecutively, allowing your
program to change and respond. It can be used to actively control the Arduino board.

An Arduino program 15
Void: The void keyword is used before a function. It stipulates that a method
should not have a return value. It means that it will run the code you give it, without
giving you any information back.

Note: The setup and loop functions must be in the Arduino code. If not, an error is
generated.

FIGURE 22 – EXAMPLE OF AN ERROR CODE WHEN THE SETUP FUNCTION IS OMITTED

Activity 1

Let’s explore!

1. Open die Arduino IDE or go to the web editor.


2. Click on the different buttons to familiarise yourself with the program.

The serial monitor


We use serial communication to communicate between the Arduino board and a
computer or other devices.
The serial monitor is used for two purposes:

1. Arduino → Computer: data from the Arduino board is displayed on the


computer screen. This is usually used for debugging or when you read data
from a sensor.
2. Computer → Arduino: sends the program to the Arduino board.

The Arduino Uno uses serial pins 0 (RX) and 1 (TX). Pins 0 and 1 are used
for communication with the computer. Connecting anything to these pins can interfere
with that communication. It also causes failed uploads to the board.

16 Study guide for Arduino


You can use the Arduino environment’s built-in serial monitor to communicate with
an Arduino board.

Click the serial monitor button in the toolbar. Make sure to select the same
baud rate in the serial monitor that you put into the code.

Baud rate refers to how fast data is transferred between your computer and
the Arduino board. It is measured in bits per second. We use 9600.
Serial.begin()
We use the Serial.begin function inside the curly brackets of the void setup function.

void setup() {
Serial.begin(9600);
}
EXAMPLE 1 – SERIAL.BEGIN()

• Serial.begin sets the baud rate for communication between the Arduino board
and the computer.
• () Every function has round brackets that hold parameters. Some functions,
like void setup does not have anything inside the brackets.

Parameters are used in functions that give information to the function.

• 9600 is the baud rate we use for communication.


• ; is a punctuation that tells the computer that you are at the end of a statement.
It is like a period in a sentence.vii
Serial.print()
We use the Serial.print function inside the curly braces of the void loop function.

void loop() {
Serial.print(“Let’s learn to code!”);
}
EXAMPLE 2 – SERIAL.PRINT()

vii (codecademy, 2022)

An Arduino program 17
• Serial.print prints your text and numbers to the serial monitor. This command
can take many forms. Look at the following examplesviii:

→ Serial.print(78) gives "78"


→ Serial.print(1.23456) gives "1.23"
→ Serial.print('N') gives "N"
→ Serial.print("Hello world.") gives "Hello world."

• () Every function has round brackets that hold parameters.


• “Let’s learn to code!” is what will be printed to the serial monitor. You need
double quotes around text.
• ; is a punctuation that tells the computer that you are at the end of a statement.
It is like a period in a sentence.ix

Serial.print will not create a new line after the output. Look at the following
example:

void loop() {
Serial.print(“Let’s learn to code”);
Serial.print(“in the Arduino IDE.”);
}
EXAMPLE 3 – SERIAL.PRINT()

This will print like this:

Let’s learn to codein the Arduino IDE.

Notice that it printed all the text in the same line without a space between the words
code and in. That is because we did not add a space after the word code or before the
word in. To create a new line after your text, rather use the Serial.println function.
Serial.println()
We use the Serial.println function inside the curly braces of the void loop function.

• The ln in the function is short for line. println is pronounced print line.

void loop() {
Serial.println(“Hello”);
Serial.println(“Goodbye”);
}
EXAMPLE 4 – SERIAL.PRINTLN()

viii (Arduino, 2022)


ix (codecademy, 2022)

18 Study guide for Arduino


This code will print like this:

Hello
Goodbye

Activity 2

Use what you’ve learned so far to print something to the serial monitor.

1. Create a new Sketch and save it as “Hello World”.


Initialize the serial monitor and then print “Hello World” to the serial monitor. On
a new line, print your name and surname.
2. Instead of displaying those two lines in the output, edit the code so that we print
the following pattern to the serial monitor:

Print it exactly how it is in the image.

An Arduino program 19
Comments
Sometimes you need to work together on a project, or you return to a project at a later
stage only to find that your own code has become difficult to understand! For these
reasons, it’s often useful to leave notes in our code for ourselves or other developers.

Why we need comments


When we make notes in our code, the compiler will ignore them. Comments exist just
for human readers. Comments can explain what the code is doing, leave instructions
for developers using the code, or add any other useful annotations. x
There are two types of comments:

Single line comments


A single line comment is used when we only need a comment on one line. We start
the comment with two forward slashes:
// This is a single line comment
Example:

void loop() {
//This will print “Hello” to the serial monitor .
Serial.println(“Hello”);
}
EXAMPLE 5 – SINGLE LINE COMMENT

You can add single line comments above or next to a line of code that you want to
annotate.

void loop() {
Serial.println(“Hello”); //This will print “Hello” to the serial
monitor.
}
EXAMPLE 6 – SINGLE LINE COMMENT

x (codecademy, 2022)

20 Study guide for Arduino


Multi-line comments
A multi-line comment will comment out (create a comment on) multiple lines. We use
/* to start the comment and */ to end the comment.
/* This is a
multiline comment. */

void loop() {
/*This is all commented.
Serial.println(“Hello”);
None of this code will run!*/
}
EXAMPLE 7 – MULTI-LINE COMMENT

Activity 3

1. Print a secret name for yourself to the serial monitor.


2. On the next line, print your goals for robotics to the serial monitor.
3. In the code, next to your secret name, add a comment with your real name and
surname.
4. In the code, underneath your goals, add a multi-line comment to say how you
plan to reach your goal.
Your output in the serial monitor should look like this:

Red Lion
I want to better my mark by 10% this term.

Notice that your comments do not print!

Activity 4

1. Start a new sketch.


2. In the void setup section, start the serial monitor and print the following in the
setup section: “This is setup code”.
3. In the void loop section, print “This is loop code”.
4. Open the serial monitor and run your code. Write down what you notice.

Comments 21
Digital I/O Functions
The Arduino programming language can be divided in three main parts: functions,
values (variables and constants), and structure. We have already looked at sketch
structure earlier in the guide.
Functions are used to control the Arduino board and to perform computations.xi
The following functions are used with the digital input/output pins.

pinMode()
With the pinMode() function, we configure a specific pin to behave as either as in input
or an output pinxii.
pinMode () has two parameters: pinMode(pin, mode)
pin: The pin number on the Arduino board that we are setting the mode of.
mode: INPUT or OUTPUT.
Example:

void setup() {
pinMode(13, OUTPUT); //Sets digital pin 13 as output.
}
EXAMPLE 8 – PINMODE ()

Notice that INPUT and OUTPUT must be capitalised!

digitalWrite()
This function writes a HIGH or LOW value to a digital pinxiii.
If the pin has been configured as an OUTPUT with pinMode(), its voltage will be set to
the corresponding value: 5V (or 3.3V) for HIGH, 0V (ground) for LOW.
digitalWrite() has two parameters: digitalWrite(pin, value)
pin: The pin number on the Arduino board that we are setting the value of.
value: HIGH or LOW.

xi (Arduino, 2022)
xii (Arduino, 2019)
xiii (Arduino, 2019)

22 Study guide for Arduino


Example:

void setup() {
pinMode(13, OUTPUT); //Sets digital pin 13 as output.
}

void loop() {
digitalWrite(13, HIGH); //Sets digital pin 13 on.
delay(1000); //Waits for a second.
digitalWrite(13, LOW); //Sets digital pin 13 off.
delay(1000); //Waits for a second.
}
EXAMPLE 9 – DIGITALWRITE()

Notice that HIGH and LOW must be capitalised!

digitalRead()
This function reads the value from a specified digital pin, either HIGH or LOWxiv.
digitalRead() has one parameter: digitalRead(pin)
pin: The Arduino pin number that you want to read.
The function returns a value to your board. It returns either HIGH or LOW.
Example:

void setup() {
pinMode(7, INPUT); //Sets digital pin 7 as input.
}

void loop() {
digitalRead(7); //Reads the input from pin 7.
}
EXAMPLE 10 – DIGITALREAD()

To use the data (HIGH or LOW) that we read from a pin, we will use variables; this will
be explained later.

xiv (Arduino, 2019)

Digital I/O Functions 23


Time Functions
delay()
The delay() function pauses the program for the amount of time (in milliseconds)
specified by the parameter.
1 000 milliseconds = 1 second.
delay() has one parameter: delay(ms)
ms: The number of milliseconds to pause.
Example:

void setup() {
pinMode(13, OUTPUT); //Sets digital pin 13 as output.
}

void loop() {
digitalWrite(13, HIGH); //Sets digital pin 13 on.
delay(2000); //Waits for 2 seconds.
digitalWrite(13, LOW); //Sets digital pin 13 off.
delay(1000); //Waits for 1 second.
}
EXAMPLE 11 – DELAY()

delayMicroseconds()
This function pauses the program for the amount of time (in microseconds) specified
by the parameter.
1 000 microseconds = 1 millisecond
delayMicroseconds() has one parameter: delayMicroseconds(us)
us: The number of microseconds to pause.
Example:

void setup() {
pinMode(13, OUTPUT); //Sets digital pin 13 as output.
}
void loop() {
digitalWrite(13, HIGH); //Sets digital pin 13 on.
delayMicroseconds(50); //Waits for 50 microseconds.
digitalWrite(13, LOW); //Sets digital pin 13 off.
delayMicroseconds(50); //Waits for 50 microseconds.
}
EXAMPLE 12 – DELAYMICROSECONDS()

24 Study guide for Arduino


Programming LEDs
Arduino’s built-in LED
The Arduino Uno board has a built-in LED that is connected to pin 13. We can control
this LED with our sketches. It is very helpful to test a program using this LED.
In a sketch, the built-in LED is referred to as LED_BUILTIN.
Example:

1 void setup() {
2 pinMode (LED_BUILTIN, OUTPUT); //Sets digital pin 13 as output.
3 }
4
5 void loop() {
6 digitalWrite(LED_BUILTIN, HIGH); //Sets digital pin 13 on.
7 delay(1000); //Waits one second.
8 digitalWrite(LED_BUILTIN, LOW); //Sets digital pin 13 off.
9 delay(1000); //Waits one second.
10 }
EXAMPLE 13 – LED_BUILTIN

The above example is a very popular LED-Blink example that is included in the IDE’s
build-in examples and used widely on the Internet.
There are a few important things we can learn from the example above:
1. On the Arduino IDE, you can choose to display line numbers. This makes it
easier to refer to specific sections of your code.

Go to File and then select Preferences. On the Settings tab, tick the
Display line numbers box.

Programming LEDs 25
2. When we code, we indent our code. Look at lines 2 and 6 – 9. This makes the
code more readable and easier to understand.

While typing, you can press the <Tab> key on your keyboard to
create an indent. <Backspace> or <Delete> can be used to remove an indent.
An easier way to ensure that your code is indented correctly, is to use Arduino’s
Auto format tool. Go to Tools and then select Auto Format. You can also use
the shortcut keys <Ctrl>+<T>.
3. Every function has round brackets () that hold parameters. Some functions,
like void setup does not have anything inside the brackets. pinMode and
digitalWrite has parameters.
4. We always end each instruction with a semicolon (;).

Activity 5

1. Open the Arduino IDE. Go to File and choose Examples. In the Basics section
you will find the Blink code that is shown above. Open the Blink sketch and
upload the sketch onto your Arduino board.
2. Write down your observations. What do you see on your Arduino board?

26 Study guide for Arduino


External LEDs
We can control external LEDs or any other powered components in a similar way.
A light-emitting diode is a device that allows current to flow in only one direction.
LEDs have polarity, which means that they will only light up if you orient the legs
properly.xv

FIGURE 23 – POLARITY OF AN LED

The leads are identified by:

• the difference in length; the longer one is the anode and the shorter one is the
cathode.
• either a notch or a flat spot on the case. The lead closest to the flat area is the
cathode pin.

Anode Cathode

FIGURE 24 – HOW TO IDENTIFY THE LEADS OF AN LED

In any practical application, an LED requires the use of a resistor.

xv (Khalil, 2021)

Programming LEDs 27
FIGURE 25 – RESISTORSxvi

The resistor is there to ensure that the maximum current rating of the LED will not be
exceeded. This means that it lowers the current in the circuit to protect the LED,
otherwise the unrestricted current will quickly burn out the LED. The resistor can have
any value between 100 and 10K Ohms. Lower resistor values allow more current to
flow, making the LED brighter. Higher resistor values restrict current flow, making the
LED dimmer.xvii

xvi (Indiamart, 2022)


xvii (Campbell, 2015)

28 Study guide for Arduino


Activity 6

Components Needed:

1 x Arduino Uno 1 x 220Ω Resistor


1 x USB cable 1 x Breadboard
1 x 5mm LED 2 x jumper wires

1. Build the following circuit:

2. Connect the LED to pin 13 and use the same code we used above to program
the LED to flash on and off.
3. Change the pin: connect the LED to pin 2. Change your code as follows:
a. Change your pin number to 2.
b. Change both delay times to 0.5 seconds.
4. Write down your observations.

Programming LEDs 29
Activity 7

Components Needed:

1 x Arduino Uno 2 x 220Ω Resistor


1 x USB cable 1 x Breadboard
2 x 5mm LED 5 x jumper wires

1. Build the following circuit:

2. Program the LEDs to flash alongside for 300 milliseconds. The LEDs should
both be blinking. But they should not be blinking in sync, they should alternate.
3. Now change the sequence by adding a synchronous blink after the alternating
blinks. You should be able to see:
• The red LED staying on for 300 milliseconds, then
• the red LED should go off at the same time as the blue LED comes on and,
• stays on for 300 milliseconds, then
• the blue LED should go off.
• Both LEDs must be off for 300 milliseconds, then
• they should both flash together for 300 milliseconds, then
• both LEDs should be off for 300 milliseconds.

30 Study guide for Arduino


Variables
A variable is a place to store a piece of data, or we can say that it is a placeholder for
a value. It has a name, a value, and a type. xviii Variable values can be constant (they
do not change) or variable (values that change during the program).xix

data type int LED = 8 value

name

Example of variable with a constant value:

int LED = 8; //Creates a variable integer called


‘LED’ with a value of 8.

void setup() {
pinMode(LED, OUTPUT); //Sets digital pin 8 as an output pin.
}

void loop() {
digitalWrite(LED, HIGH); //Sets digital pin 8 on.
delay(500); //Waits for half a second.
digitalWrite(LED, LOW); //Sets digital pin 8 off.
delay(500); //Waits for half a second.
}
EXAMPLE 14 – CONSTANT VARIABLE

In this example, we connect an LED to a digital pin 8 on our Arduino board. Pin 8 will
be used for the LED throughout the program and will not change; therefore, it is a
constant variable.

xviii (Arduino, 2022)


xix (TechTarget, 2021)

Variables 31
Example of a variable with a variable value:

int design = 14; //Creates a variable integer called ‘design’


with a value of 14.
int codingC = 11; //Creates a variable integer called ‘codingC’
with a value of 11.
int codingP = 15; //Creates a variable integer called ‘codingP’
with a value of 15.
int web = 9; //Creates a variable integer called ‘web’ with
a value of 9.
int total = 0; //Creates a variable integer called ‘total’
with a value of 0.

void setup() {
Serial.begin(9600);
}

void loop() {
Serial.print(“Total learners in the coding programs: ”);
Serial.println(coding + codingP);
Serial.print(“Total learners in the design programs: ”);
Serial.println(design + web);
Serial.print(Total learners in the club: ”);
Serial.println(design + codingC + codingP + web);
}
EXAMPLE 15 – VARIABLE WITH A VARIABLE VALUE

The result of the example above will be:

32 Study guide for Arduino


Data types
int
Integers are your primary datatype for number storage. It does not acknowledge
fractional numbers. We can use the int datatype in variables.xx
Example:

int LED = 8; //Creates a variable integer called ‘LED’ with a


value of 8.
EXAMPLE 16 – INT

Floating-point
Floating-point data types are used for fractional numbers. There are two types of
floating-point data types:

float
This data type has a decimal point that typically allows up to seven points after a
decimal.
Example:

float percentage = 80.5; //Creates a variable float called


‘percentage’ with a value of 80.5.
EXAMPLE 17 – FLOAT

double
Double typically allows up to 15 points after a decimal.xxi But, on the Uno board, double
is the same as float, without making the number more precise.

double percentage = 80.5; //Creates a variable double called


‘percentage’ with a value of 80.5.
EXAMPLE 18 – DOUBLE

bool
A bool holds one of two values, true or false.xxii We can use the bool datatype in
variables.
Example:

bool sensor = false; //Creates a variable Boolean called ‘sensor’


with a ‘false’ value.
EXAMPLE 19 – BOOL

xx (Arduino, 2022)
xxi (Indeed Editorial Team, 2021)
xxii (Arduino, 2022)

Data types 33
long
Long variables are used for number storage, both positive and negative, that may
have many place values.
Example:

long rTime = 0; //Creates a variable long called ‘time’ with a


value of 0.

void setup() {
Serial.begin(9600);
}

void loop() {
Serial.print("Time: ");
rTime = millis(); //Prints time since program started.
Serial.println(time);
delay(1000); //Wait a second so as not to send
massive amounts of data.
}
EXAMPLE 20 – LONG

Activity 8

Practice writing your own variables and explain what they can be used for. Use any
appropriate pins or values.
Example:

int button = 3; //creates a variable integer for a button that is


connected to pin 3.

1. Create and explain two variables with the integer type.


2. Create and explain two variables with the bool type.
3. Create and explain two variables with the float type.

34 Study guide for Arduino


Analog I/O Functions
analogRead()
analogRead reads the value from a specified analog pin. On the Uno board we use
pins A0 – A5xxiii.
analogRead() has one parameter: analogRead(pin)
pin: The name of the analog input pin to read from (A0 – A5).
The analogRead function returns a value. It turns the voltage value into integer
values:

Minimum: 0 → 0V

Maximum: 1024 → 5V

Example:

int value = 0; //Variable to store the value read.



void loop() {
value = analogRead(A1); //Reads the input pin and stores the
value in the value variable.
}
EXAMPLE 21 – ANALOGREAD()

analogWrite()
analogRead writes and analog value to a pin. On the Uno board we use the PWM
(pulse width modulation) pins. We can use this to set the brightness of a light or the
speed of a motor.xxiv

The PWM pins on the Uno board are 3, 5, 6, 9, 10, 11.

The analogWrite function has nothing to do with the analog pins or the analogRead
function!
analogWrite() has two parameters: analogWrite(pin, value)
pin: The pin to write to.
Value: a value between 0 (always off) and 255 (always on).

xxiii (Arduino, 2019)


xxiv (Arduino, 2019)

Analog I/O Functions 35


Note: You can only use the int data type with this function.

Minimum: 0 → 0V → LOW

Maximum: 255 → 5V → HIGH

Example:

int LED = 3; //Variable to store the pin value of the LED.



void loop() {
analogWrite(LED,127); //Writes a value to the pin to set
the LED to 50% brightness.
}
EXAMPLE 22 – ANALOGWRITE

36 Study guide for Arduino


Control Structures
In C++ coding, there are control structures that we use to control the behaviour of
our program. Control structures are commands that allows a program to “make
decisions” based on certain conditionsxxv.

if statement
The if statement checks for a condition and performs the statement or set of
statements that follows, if the condition is ‘true’.xxvi
We write an if statement as follows:

if (condition) {
statement(s)
}
EXAMPLE 23 – IF STATEMENT

Example:

if (x = 10) { //Checks if x is equal to 10.


digitalWrite(12, HIGH); //If ‘true’, set digital pin 12 on.
}
EXAMPLE 24 – IF STATEMENT

xxv (Yse, 2020)


xxvi (Arduino, 2022)

Control Structures 37
Logical flow of an if statement
To better understand how if statements work, look at this chart that shows the logical
flow of an if statement:

START

Declare variables:
sensor, senval,
LED

true
is senval Turn LED
Read
<= 5? on
sensor

false

STOP

else
If you need to test for more than one thing, you can use else. If you use an else clause,
it will be executed if the condition in the if-statement is false.
Each test will continue to the next one until a test is true. When a true test is found,
the code inside the if-statement’s braces is run and the program then skips to the line
following the entire if/else section.
If all the tests are false, the last else block is executed, if there is one. You can use an
unlimited amount of else if branches.xxvii
We write an else clause as follows:

if (condition 1) {
//Do thing A.
}
else if (condition 2) {
//Do thing B.
}
else {
//Do thing C.
}
EXAMPLE 25 – IF…ELSE

xxvii (Arduino, 2019)

38 Study guide for Arduino


Example:

if (temperature >= 40) {


Serial.println(“Danger! High fever!”);
}
else if (temperature >= 37) {
Serial.println(“Caution! Temperature is high.”);
}
else {
Serial.println(“Temperature is normal.”);
}
EXAMPLE 26 – IF…ELSE

Logical flow of an if else statement


To better understand how if else statements work, look at this chart that shows the
logical flow of an if else statement:

START

Declare variables:
sensor, senval, high,
caution, normal

true Display
is temp
Read message:
>= 40?
sensor high

false if else

Display
is temp true
message:
>= 37? caution

false else

Display
message: STOP
normal

Control Structures 39
Activity 9

Write your own example using an else clause. Only write the if-statement with the else
clause as in the example above.

40 Study guide for Arduino


Comparison operators
Comparison operators are used to compare values. We use the following comparison
operators with the if statement:

Operator Example Explanation


== x == y x is equal to y
!= x != y x is not equal to y
< x<y x is less than y
> x>y x is greater than y
<= x <= y x is less than or equal to y
>= x >= y x is greater than or equal to y

Be careful! Don’t use the single equal sign (e.g., if (x = 10). The single equal
sign is used to set a value, i.e., it gives x the value 10. Instead use the double equal
sign (e.g., if (x == 10) ), which will test whether x is equal to 10 or not.xxviii

xxviii (Arduino, 2022)

Comparison operators 41
Activity 10

Program a doorbell:
Components Needed:
1 x Arduino Uno 1 x 220Ω Resistor
1 x USB cable 1 x Breadboard
1 x buzzer 7 x jumper wires
1 x push button

1. Build the following circuit:

2. Use an if statement to program the buzzer to sound when the push button is
pressed.

42 Study guide for Arduino


Boolean operators
Logical AND (&&)
The logical AND operator is used to include two conditions in an if-statement. xxix

//If BOTH the switches read HIGH:


if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) {
digitalWrite(8, HIGH);
}
EXAMPLE 27 – AND (&&)

Logical OR (||)
The logical OR results in a TRUE if either of the two operands is true. xxx

//If EITHER x or y is greater than zero:


if (x > 0 || y > 0) {
//Statement(s)
}
EXAMPLE 28 – OR (||)

Logical NOT (!)


The logical NOT results in a TRUE if the operand is FALSE and vice versa. xxxi

//If x is not true:


if ( !x ) {
//Statement(s)
}
EXAMPLE 29 – NOT (!)

xxix (Arduino, 2019)


xxx (Arduino, 2019)
xxxi (Arduino, 2019)

Boolean operators 43
Keywords or operators – which is the best?
C++ defines certain keywords to act as aliases for several operators:

Keyword Operator

and &&

and_eq &=

not !

not_eq !=

or ||

or_eq |=

These keywords can be used the same way as the punctuation symbols they replace.
This means that the expressions (a > 0 and not flag) and (a > 0 && !flag) have identical
meanings. xxxii Remember that the keywords should not be capitalized!
Example:

//If EITHER x or y is greater than zero:


if (x > 0 or y > 0) {
//Statement(s)
}
EXAMPLE 30 – KEYWORD USE FOR LOGICAL OPERATORS

xxxii (Wikipedia, 2022)

44 Study guide for Arduino


Creating your own functions
Whenever we want to perform the same action multiple times in a program, we create
a function. A function is code that allows you to divide specific code in sections, and
each section performs a particular task.xxxiii
We already know of two functions: setup() and loop().
A function has the following partsxxxiv:

void flash () { parentheses


return type
opening curly
function name brace – the body of the
digitalWrite(LED, HIGH); function will go between
delay(500); the braces
closing curly digitalWrite(LED, LOW);
brace
}
Statement(s) that specify what
the function must do.

FIGURE 26 – THE PARTS OF A FUNCTION

Return type: A function must have a return type. The example function does not
return anything, so the return type is void.
Function name: we must give our function a name that describes what the function
does.
Parentheses: The function name ends with parentheses. In this example, we do not
use any parameters, so the parentheses are empty.
Statement(s): The function body is made up of statements placed between braces {}.
The statements contain the code that will perform the specific task that the function is
created for.

Your function needs to be added (declared) outside any other function, (i.e.,
not inside the braces of the loop() or setup() functions). Your function can go either
above or below the loop() function.

xxxiii (JavaTPoint, 2022)


xxxiv (Starting Electronics, 2015)

Creating your own functions 45


Example:
Components Used:
1 x Arduino Uno 2 x 220Ω Resistors
1 x USB cable 1 x Breadboard
1 x 5mm LED 7 x jumper wires
1 x push button

int btn = 5;
int LED = 4;
int btnval = 0;
void setup() {
pinMode(btn, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
LEDoff(); //Calling (running) the LEDoff function.
btnval = digitalRead(btn); //Reading pin 5.
if (btnval == 1) { //If the button is pressed, call
the flash() function*.
flash();
}
}
void LEDoff() { //Declaring (creating) a function
called LEDoff.
digitalWrite(LED, LOW);
delay(10);
}

46 Study guide for Arduino


void flash() { //Declaring a function called
flash.
digitalWrite(LED, HIGH);
delay(500);
digitalWrite(LED, LOW);
delay(500);
}
EXAMPLE 31 – CREATING YOUR OWN FUNCTIONS

*When a button is pressed, the digitalRead function will return 1 ; if not pressed, it will
return 0. You can also substitute the 1 in the expression (if (btnval == 1)) with HIGH.
The expression will then be (if (btnval == HIGH)).

Activity 11

Who’s turn is it?


We love playing games! Instead of arguing who’s turn it is to play next, create a
function to determine who should get the next turn by following these instructions:
1. Build the circuit:
Components Used:

1 x Arduino Uno 220Ω Resistors – 1 per


1 x USB cable player + 1 for button
5mm LEDs – 1 per player 1 x Breadboard
1 x push button 7 x jumper wires

Creating your own functions 47


2. Create a variable for each colour and one for the button.
3. Add the following variables:
int cBtnState = 0;
int lBtnState = 0;
4. Set your lights as OUTPUT and the button as INPUT in the setup function.
5. Add this line of code in void setup() :
randomSeed(analogRead(A1));
6. Create a function:
a. Name: takingTurns
b. Type: void
c. Statements: Let each light come on, one at a time with a 350ms delay
between each. When all the lights are on, they must each go off one at
a time with a 350ms delay between each.
7. Create another function:
a. Name: allOFF
b. Type: void
c. Statements: switch all lights off; no delays
8. Add the following code in void loop() and see what happens when the button is
pressed:
cBtnState = digitalRead(btn);
if (cBtnState != lBtnState) {
takingTurns();
delay(400);
digitalWrite(random(2,8),HIGH);
delay(2000);
allOFF();
delay(10000);
}
lBtnState = cBtnState;

How does this work? Give each player a colour. Press the button to let the program
decide who’s turn it is!
To see an example, click here or scan the QR code:

48 Study guide for Arduino


Using sensors
Infrared Sensor (IR)
Red light is visible light with the longest wavelength. Light waves longer than red light
waves are called infrared light (IR).
Infrared sensors measure the amount of reflected light. In infrared sensors, an infrared
light source, which is typically an IR LED, is used to transmit light to a receiving
infrared sensor.

FIGURE 27 – INFRARED SENSORxxxv

Bright colours such as white, reflects more light than darker colours, like black, which
absorb light. We use these sensors to program line-following robots.

Photo Photo
Diode IR LED IR LED
Diode

High value of reflectance/voltage Low value of reflectance/voltage

FIGURE 28 – HOW IR SENSORS WORKxxxvi

xxxv (Flipkart, 2022)


xxxvi (mjrovai | Intructables, 2016)

Using sensors 49
IR receiver Distance adjust Power LED

IR emitter LED Obstacle LED

FIGURE 29 – IR SENSOR DIAGRAMxxxvii

The IR sensor has 3 pins:

+5V: This pin is used to power the sensor from the 5V power pin on the Arduino board.

GND: This pin is used to ground the circuit and is connected to the GND pin on the
Arduino board.

OUT: This pin is the sensors output pin. It is connected to one of the analog input pins
(A0 – A5) on the Arduino board. The board receives input from the sensor.

Programming the IR sensor


To program an IR sensor on a simulator such as Tinkercad.com, we need use a IR
sensor with only an receiver. A remote control is used to emit the IR light.
Example: – LED with IR sensor:

xxxvii (Robomart.com, 2022)

50 Study guide for Arduino


Components Used:

1 x Arduino Uno 1 x Breadboard


1 x USB cable 1 x IR sensor (R)
1 x 5mm LED 1 x IR Remote (T)
1 x 220Ω Resistors 7 x jumper wires

Code:

//Declaring variables:
int IR = 8;
int LED = 12;
int remote = 0;

void setup() {
pinMode(IR,INPUT);
pinMode(LED, OUTPUT);
}

void loop() {
digitalWrite(LED, LOW);
remote = digitalRead(IR); //Read the sensor and store value
in remote variable.
if (remote == LOW) { //A low value indicates a signal.
digitalWrite(LED, HIGH); //Turn on the LED if remote button
is pressed.
}
}
EXAMPLE 32 – IR SENSOR

When a button on the remote is pressed, the digitalRead function will return
0; if not pressed, it will return 1. HIGH is equal to 1 and LOW is equal to 0. Thus, you
can use either HIGH and LOW or 1 and 0 in your program.

Using sensors 51
Example: – Line following robotxxxviii

FIGURE 30 – LINE FOLLOWER ROBOT

Components Used:
1 x battery holder with
1 x Chasis
batteries
2 x wheels 1 x 5mm LED
1 x motor driver 1 x 220Ω Resistors
2 x DC motors 1 x switch
2 x IR sensors 1 x Arduino Uno
Jumper wires 1 x USB cable

Working:

xxxviii (Aarav G | Instructables, 2019)

52 Study guide for Arduino


If the left sensor is on the black line and the right sensor is on white, the robot should
turn left to keep following the line.

If the left sensor is on white and the right sensor is on the black line, the robot should
turn right to keep following the line.

If both sensors are on white, the robot moves forward.

Using sensors 53
If both sensors are on black, the robot stops.

Code:

//Declaring variables for motors:


int leftForward = 5;
int leftBack = 6;
int rightForward = 10;
int rightBack = 11;

//Declaring variables for sensors:


int T = 400; //Threshold value. *Black reading will be
higher than 400; white reading will be
lower.
int leftSensor = A1; //Even though the value contains a letter,
it is recognised as analog input 1 and the
letter is ignored; therefore, we can use
the int data type.
int rightSensor = A2;
int leftRead = 0; //Variable to store the input from the
left sensor.
int rightRead = 0; //Variable to store the input from the
right sensor.

//Declaring variables for motor speed; the sensors will only work
correctly if the robot drives at a slower speed.
int mspeed = 200; //Analog speed.

54 Study guide for Arduino


void setup() {
//Setting motor pins as output pins:
pinMode(leftForward, OUTPUT);
pinMode(leftBack, OUTPUT);
pinMode(rightForward, OUTPUT);
pinMode(rightBack, OUTPUT);

//Sensor pins do not need to be set as input using pinMode since the
pins can only receive input.
}

void loop() {
//Read the IR sensors:
leftRead = analogRead(leftSensor);
rightRead = analogRead(rightSensor);

//If the left sensor detects the line:


if (leftRead > T && rightRead < t) {
left();
}
//If the right sensor detects the line:
else if (leftRead < T && rightRead > t) {
right();
}

//If the line is not detected:


else if (leftRead < T && rightRead < t) {
forward();
}

//If both sensors detect the line:


else if (leftRead > T && rightRead > t) {
halt();
}

} //Important: remember to close your void loop function!

Using sensors 55
//Declaring the robot’s movement functions:

void left() {
//Right wheel turns forward; left wheel turns backwards:
analogWrite(rightForward, mspeed);
analogWrite(leftBack, mspeed);
digitalWrite(leftForward, LOW);
digitalWrite(rightBack, LOW);
}

void right() {
//Right wheel turns backwards; left wheel turns forwards:
analogWrite(rightBack, mspeed);
analogWrite(leftForward, mspeed);
digitalWrite(leftBack, LOW);
digitalWrite(rightForward, LOW);
}

void forward() {
//Right wheel turns forward; left wheel turns forward:
analogWrite(rightForward, mspeed);
analogWrite(leftForward, mspeed);
digitalWrite(leftBack, LOW);
digitalWrite(rightBack, LOW);
}

void halt() {
//Both wheels stop; the word ‘stop’ may not be used as a function or
variable name:
digitalWrite(rightForward, LOW);
digitalWrite(leftBack, LOW);
digitalWrite(leftForward, LOW);
digitalWrite(rightBack, LOW);
}
EXAMPLE 33 – LINE FOLLOWING ROBOT

*Take an IR reading on black and on white. The threshold value should be between
the black and white reading.

56 Study guide for Arduino


Ultrasonic sensor

FIGURE 31 – ULTRASONIC SENSORxxxix

An ultrasonic sensor is an electronic device that measures the distance of a target


object by sending ultrasonic sound waves and converts the reflected sound into an
electrical signal.
Ultrasonic waves travel faster than the speed of audible sound (i.e., the sound that
humans can hear).

xxxix (Bot Shop, 2022)

Using sensors 57
Ultrasonic sensors have two main components:

• the transmitter (which sends the sound) and


• the receiver (which receives the echo).xl

Transmitter for Receiver for


ultrasonic ultrasonic
waves waves

Voltage input Ground pin

Trig input pin Echo output pin

FIGURE 32 – IR SENSOR DIAGRAM

The transmitter and receiver are marked on the sensor with the letters T and R
respectively.

The ultrasonic sensor has 4 pins:

VCC: This pin is used to power the sensor from the 5V power pin on the Arduino board.

Trig: The trig pin sends a signal from the Arduino board to the sensor to trigger the
transmitter.

Echo: The echo pin receives the signal from the receiver and sends it back to the
Arduino board.

GND: This pin is used to ground the circuit and is connected to the GND pin on the
Arduino board.

xl (Jost, 2019)

58 Study guide for Arduino


T

FIGURE 33 – HOW AN ULTRASOUND SENSOR WORKS

The trig pin receives a signal from the Arduino board which triggers the transmitter
(T) to send out an ultrasonic sound wave. The wave bounces off any objects in its
path and is reflected. The receiver receives the echoed sound wave, converts it into
an electrical signal that is then sent to the Arduino board via the echo pin.

Creating a distance calculator for the sensor


To program an ultrasonic sensor, we must write a function that converts the electrical
signal into a distance value that we can use. To do that, we use the speed of sound.
The sensor records the time it takes for the ultrasonic wave to travel to the obstacle
and back.
The speed of the sound in air is 360 metres per second. To see the distance in cm
instead of metres, we will use a speed of 0.036 cm per second.
To calculate distance, we use:

distance = speed x time


Example:
distance = speed x time
0.036 x time
distance =
2

Since the ultrasonic burst travels towards the obstacle and reflects to the sensor, we
have twice the distance. So, we must divide the distance in half.
To determine the time, we must use a function called pulseIn().

pulseIn()
Pulse in written as pulseIn() reads a pulse (either HIGH or LOW) on a pin.
For example, if we set the function’s value to HIGH, pulseIn() waits for the pin to go
from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing.
It returns the length of the pulse in microseconds. This function works on pulses from
10 microseconds to 3 minutes in length.

Using sensors 59
pulseIn() has two parameters: pulseIn(pin, value)
pin: The number of the Arduino pin of which you want to read the pulse.
value: the type of pulse to read: HIGH or LOW.
Example:

void loop() {
duration = pulseIn(echo, HIGH); //Duration for the pin to go from
LOW to HIGH.
Serial.println(duration); //Prints the duration to the
serial monitor.
}
EXAMPLE 34 – PULSEIN()

We save this calculation for determining the distance, in a function:

int distance() {
long duration, distance; //The long datatype stores larger
numbers than int.
digitalWrite(trig, LOW); //Switch off the trig pin to clear out
noise.
delayMicroseconds(2);
digitalWrite(trig, HIGH); //Start sound wave.
delayMicroseconds(10);
digitalWrite(trig, LOW); //End sound wave.
duration = pulseIn(echo, HIGH); //Determines how long it takes
(in microseconds) for the sound
wave to travel to the obstacle
and back.
distance = (0.036 * duration) / 2; //Converts the duration to
distance in cm.
}
EXAMPLE 35 – DISTANCE CALCULATOR

60 Study guide for Arduino


Programming the ultrasonic sensor
Now that we have our own function to calculate the distance in cm, we can use it for
different tasks.
Example: LED with ultrasonic sensor:

int trig = 3; //Trig pin connected to pin 3.


int echo = 4; //Echo pin connected to pin 4.
int LED = 13; //LED anode connected to pin 13.
int cm = 0; //Initial cm value set to 0.

void setup() {
pinMode(trig, OUTPUT); //A signal is sent to the trig pin, thus
OUTPUT.
pinMode(echo, OUTPUT); //A signal is received by the echo pin,
thus INPUT.
pinMode(LED, OUTPUT);
}

void loop() {
cm = distance(); //Runs the distance function and saves the
distance reading in the cm variable.
digitalWrite(LED, LOW); //LED is off when distance is
determined.
if(cm <= 4) {
digitalWrite(LED,HIGH); //If the object is closer than 4cm to
the sensor, turn the LED on.
}
delay(500); //Wait half a second before repeating.
}

int distance() {
long duration, distance; //The long datatype stores larger
numbers than int.
digitalWrite(trig, LOW); //Switch off the trig pin to clear out
noise.
delayMicroseconds(2);
digitalWrite(trig, HIGH); //Start sound wave.
delayMicroseconds(10);
digitalWrite(trig, LOW); //End sound wave.

Using sensors 61
duration = pulseIn(echo, HIGH); //Determines how long it takes (in
microseconds) for the sound wave
to travel to the obstacle and
back.
distance = (0.036 * duration) / 2; //converts the duration to
distance in cm
}
EXAMPLE 36 – ULTRASOUND SENSOR

62 Study guide for Arduino


Index

A
F R
analog input pins .................. 11
analogRead() ....................... 35 float .......................................33 resistor ................................. 28
analogWrite()........................ 35 function name .......................45 return type ............................ 45
anode ................................... 27 functions ...............................22 round brackets () .................. 26
Arduino................................... 3
Arduino Software (IDE) .......... 4 I S
if 37 selecting the serial port: ....... 13
B indent ....................................26 Selecting your Arduino board12
baud rate .............................. 17 Infrared Sensor .....................49 serial monitor........................ 17
bool ...................................... 33 int 33 serial pins ............................. 16
Serial.begin() ........................ 17
L Serial.print().......................... 17
C Serial.println() ....................... 18
C++ ........................................ 3 LED.......................................27 single line comment ...........See
cathode ................................ 27 LED_BUILTIN .......................25 comments
comments ............................ 20 line following robot ................52 sketches ................................. 2
comparison operators .......... 41 line numbers .........................25 statement ............................. 45
compiled language ............... 14 structure ............................... 15
create a new project ............. 12 M
creating functions ................. 45 T
multi-line comment............. See
comments trig ..........See ultrasonic sensor
D
data types ............................ 33 P U
delay() .................................. 24
delayMicroseconds() ............ 24 parameters ...........................17 ultrasonic sensor .................. 57
digitalRead() ......................... 23 parentheses ..........................45 upload ................................... 2
digitalWrite() ......................... 22 pinMode() .............................22
double .................................. 33 polarity ..................................27 V
pulseIn()................................60
PWM (Pulse Width Modulation) variable................................. 31
E .........................................10 verify...................................... 2
echo ....... See ultrasonic sensor void ...................................... 16
else ...................................... 38 void loop() ............................ 15
void setup() .......................... 15

Index 63
Examples in this guide
Example 1 – Serial.begin() ....................................................................................... 17
Example 2 – Serial.print() ......................................................................................... 17
Example 3 – Serial.print() ......................................................................................... 18
Example 4 – Serial.println() ...................................................................................... 18
Example 5 – Single line comment ............................................................................ 20
Example 6 – Single line comment ............................................................................ 20
Example 7 – Multi-line comment .............................................................................. 21
Example 8 – pinMode () ........................................................................................... 22
Example 9 – digitalWrite() ........................................................................................ 23
Example 10 – digitalRead() ...................................................................................... 23
Example 11 – delay() ............................................................................................... 24
Example 12 – delayMicroseconds() ......................................................................... 24
Example 13 – LED_BUILTIN.................................................................................... 25
Example 14 – Constant variable .............................................................................. 31
Example 15 – Variable with a variable value ............................................................ 32
Example 16 – int ...................................................................................................... 33
Example 17 – float.................................................................................................... 33
Example 18 – double................................................................................................ 33
Example 19 – bool.................................................................................................... 33
Example 20 – long.................................................................................................... 34
Example 21 – analogRead()..................................................................................... 35
Example 22 – analogWrite ....................................................................................... 36
Example 23 – if statement ........................................................................................ 37
Example 24 – if statement ........................................................................................ 37
Example 25 – if…else .............................................................................................. 38
Example 26 – if…else .............................................................................................. 39
Example 27 – and (&&) ............................................................................................ 43
Example 28 – OR (||) ................................................................................................ 43
Example 29 – not (!) ................................................................................................. 43
Example 30 – keyword use for logical operators ...................................................... 44
Example 31 – Creating your own functions .............................................................. 47
Example 32 – IR sensor ........................................................................................... 51
Example 33 – Line following robot ........................................................................... 56
Example 34 – pulseIn() ............................................................................................ 60
Example 35 – Distance calculator ............................................................................ 60
Example 36 – Ultrasound sensor ............................................................................. 62

64 Study guide for Arduino


Table of figures
Figure 1 – Arduino IDE ............................................................................................... 2
Figure 2 – The toolbar ................................................................................................ 2
Figure 3 – Arduino Uno board .................................................................................... 3
Figure 4 – Arduino Uno Microcontroller ...................................................................... 3
Figure 5 – Arduino Uno USB port ............................................................................... 4
Figure 6 – USB type-B cable used for Arduino Uno ................................................... 4
Figure 7 – Arduino Uno Power Jack ........................................................................... 5
Figure 8 – Connecting a barrel jack to the power jack of the Arduino Uno ................. 5
Figure 9 – Reset button on the Arduino Uno .............................................................. 5
Figure 10 – Power pins on the Arduino Uno............................................................... 6
Figure 11 – DuPont Jumper Wires ............................................................................. 6
Figure 12 – LED lights on the Arduino Uno ................................................................ 7
Figure 13 – Digital Pins on the Arduino Uno .............................................................. 9
Figure 14 – The duty cycles of PWM........................................................................ 10
Figure 15 – Controlling LED lights with PWM........................................................... 10
Figure 16 – Analog pins on the Arduino Uno ............................................................ 11
Figure 17 – Creating a new project .......................................................................... 12
Figure 18 – Selecting the correct board in the IDE ................................................... 12
Figure 19 – Selecting the serial port ......................................................................... 13
Figure 20 – 5 Stages of development in Arduino programming ............................... 14
Figure 21 – Structure of an Arduino program ........................................................... 15
Figure 22 – Example of an error code when the setup function is omitted ............... 16
Figure 23 – Polarity of an LED ................................................................................. 27
Figure 24 – How to identify the leads of an LED ...................................................... 27
Figure 25 – Resistors ............................................................................................... 28
Figure 26 – The parts of a function .......................................................................... 45
Figure 27 – Infrared Sensor ..................................................................................... 49
Figure 28 – How IR sensors work ............................................................................ 49
Figure 29 – IR sensor diagram ................................................................................. 50
Figure 30 – Line follower robot ................................................................................. 52
Figure 31 – Ultrasonic sensor .................................................................................. 57
Figure 32 – IR Sensor Diagram ................................................................................ 58
Figure 33 – How an ultrasound sensor works .......................................................... 59

Table of figures 65
References
Aarav G | Instructables, 2019. How to Make Line Follower Robot Using Arduino : 5
Steps - Instructables. [Online]
Available at: https://www.instructables.com/Line-Follower-Robot-Using-Arduino-2/
[Accessed 19 10 2022].
Alibaba.com, 2022. 200Pcs Male To Female Red Black 26AWG 20CM 2.54mm
Dupont jumper Wire Cable. [Online]
Available at: https://www.alibaba.com/product-detail/200Pcs-Male-To-Female-Red-
Black_62263579453.html
[Accessed 28 09 2022].
Arduino, 2019. ! - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/structure/boolean-
operators/logicalnot/
[Accessed 15 11 2022].
Arduino, 2019. && - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/structure/boolean-
operators/logicaland/
[Accessed 19 10 2022].
Arduino, 2019. || - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/structure/boolean-
operators/logicalor/
[Accessed 15 11 2022].
Arduino, 2019. analogRead() - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/functions/analog-
io/analogread/
[Accessed 18 10 2020].
Arduino, 2019. analogWrite() - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/functions/analog-
io/analogwrite/
[Accessed 18 10 2022].
Arduino, 2019. digitalRead() - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/functions/digital-
io/digitalread/
[Accessed 10 10 2022].
Arduino, 2019. digitalWrite() - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/functions/digital-
io/digitalwrite/
[Accessed 10 10 2022].

66 Study guide for Arduino


Arduino, 2019. Else - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/structure/control-
structure/else/
[Accessed 19 10 2020].
Arduino, 2019. pinMode() - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/functions/digital-
io/pinmode/
[Accessed 10 10 2022].
Arduino, 2022. Arduino Integrated Development Environment (IDE) v1 | Arduino
Documentation | Arduino Documentation. [Online]
Available at: https://docs.arduino.cc/software/ide-v1/tutorials/arduino-ide-v1-basics
[Accessed 27 09 2022].
Arduino, 2022. Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/
[Accessed 10 10 2022].
Arduino, 2022. bool - Arduino reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/variables/data-
types/bool/
[Accessed 14 10 2022].
Arduino, 2022. if - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/structure/control-
structure/if/
[Accessed 11 10 2022].
Arduino, 2022. int - Arduino Reference. [Online]
Available at: https://www.arduino.cc/reference/en/language/variables/data-types/int/
[Accessed 14 10 2022].
Arduino, 2022. Serial.print() - Arduino Reference. [Online]
Available at:
https://www.arduino.cc/reference/en/language/functions/communication/serial/print/
[Accessed 27 09 2022].
Arduino, 2022. Using Variables in Sketches | Arduino Documentation. [Online]
Available at: https://docs.arduino.cc/learn/programming/variables
[Accessed 14 10 2022].
Arduino, 2022. What is Arduino? | Arduino. [Online]
Available at: https://www.arduino.cc/en/Guide/Introduction
[Accessed 27 09 2022].
Bot Shop, 2022. HC-SR04 Ultrasonic Sensor - Bot Shop. [Online]
Available at: https://botshop.co.za/products/hc-sr04-ultrasonic-
sensor?currency=ZAR&utm_medium=cpc&utm_source=google&utm_campaign=Go

References 67
ogle%20Shopping&gclid=EAIaIQobChMIus_bkrnu-
gIVxO7tCh0lpwgKEAQYASABEgJEt_D_BwE
[Accessed 20 10 2022].
Campbell, S., 2015. Getting Started with the Arduino - Controlling the LED (Part 1).
[Online]
Available at: https://www.circuitbasics.com/arduino-basics-controlling-led/#comments
[Accessed 11 10 2022].
codecademy, 2022. Learn C ++ | Codecademy. [Online]
Available at: https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-
hello-world/exercises/console-output
[Accessed 27 09 2022].
codecademy, 2022. Learn C++ | Codecademy. [Online]
Available at: https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-
compile-execute/exercises/comments
[Accessed 28 09 2022].
Codecademy, 2022. Learn C++ | Codecademy. [Online]
Available at: https://www.codecademy.com/courses/learn-c-plus-plus/lessons/cpp-
hello-world/exercises/introduction
[Accessed 27 09 2022].
Flipkart, 2022. TechInfo IHCRL IR PROXIMITY SENSOR FOR LINE FOLLOWER
ROBOT SET OF 2 Electronic Components Electronic Hobby Kit Price in India - Buy
TechInfo IHCRL IR PROXIMITY SENSOR FOR LINE FOLLOWER ROBOT SET OF
2 Electronic Components Electronic Hobby Kit online at Fl. [Online]
Available at: view-source:https://www.flipkart.com/techinfo-ihcrl-ir-proximity-sensor-
line-follower-robot-set-2-electronic-components-hobby-kit/p/itmbf7827fc7b433
[Accessed 19 10 2022].
Indeed Editorial Team, 2021. 10 Data Types (With Definitions and Examples) |
Indeed.com. [Online]
Available at: https://www.indeed.com/career-advice/career-development/data-type-
examples
[Accessed 18 10 2022].
Indiamart, 2022. Electronic Components - Carbon Film Resistors Wholesale Trader
from Pune. [Online]
Available at: https://www.indiamart.com/platinumelectronics/electronic-
components.html
[Accessed 11 10 2022].
JavaTPoint, 2022. Arduino Fuctions - JavaTPoint. [Online]
Available at: https://www.javatpoint.com/arduino-
functions#:~:text=The%20functions%20allow%20a%20programmer,from%20which

68 Study guide for Arduino


%20it%20is%20called.
[Accessed 18 10 2022].
Jost, D., 2019. What is an Ultrasonic Sensor? | Fierce Electronics. [Online]
Available at: fierceelectronics.com/sensors/what-ultrasonic-sensor
[Accessed 20 10 2020].
Khalil, Z., 2021. Light-emitting diodes (LEDs) - Arduino Video Tutorial | LinkedIn
Learning, formerly Lynda.com. [Online]
Available at: https://www.linkedin.com/learning/learning-arduino-foundations-2/light-
emitting-diodes-
leds?autoAdvance=true&autoSkip=false&autoplay=true&resume=false
[Accessed 12 01 2022].
mjrovai | Intructables, 2016. Line Follower Robot - PID Control - Android Setup : 12
Steps (with Pictures) - Instructables. [Online]
Available at: https://www.instructables.com/Line-Follower-Robot-PID-Control-
Android-Setup/
[Accessed 19 10 2022].
Prinsloo, P. L., 2021. Exam preparation notes. Nelspruit: Curro Nelspruit.
Robomart.com, 2022. Buy IR Proximity Sensor For Arduino Raspberry Pi and
Robotics. [Online]
Available at: https://www.robomart.com/ir-proximity-sensor
[Accessed 19 10 2022].
Robottronic, 2022. How to Power Up Arduino Uno: 4 Steps - Instructables. [Online]
Available at: https://www.instructables.com/3-Ways-to-Power-Up-Arduino-Uno/
[Accessed 28 09 2022].
Starting Electronics, 2015. Arduino Functions | How To Program and Use a
Function. [Online]
Available at: https://startingelectronics.org/software/arduino/learn-to-program-
course/15-functions/
[Accessed 18 10 2020].
TechTarget, 2021. What is a variable? - Definition from WhatIs.com. [Online]
Available at:
https://www.techtarget.com/whatis/definition/variable#:~:text=In%20programming%2
C%20a%20variable%20is,uses%20when%20it%20is%20running.
[Accessed 17 10 2022].
Wikipedia, 2022. Operators in C and C++ - Wikipedia. [Online]
Available at:
https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#C.2B.2B%5Foperator
%5Fsynonyms
[Accessed 15 11 2022].

References 69
Yse, D. L., 2020. Essential Programming | Control Structures | by Diego Lopez Yse |
Towards Data Science. [Online]
Available at: https://towardsdatascience.com/essential-programming-control-
structures-2e5e73285df4
[Accessed 11 10 2022].

70 Study guide for Arduino

You might also like