Coding and Robotics Study Guide - Grade 8 and 9
Coding and Robotics Study Guide - Grade 8 and 9
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.
This icon indicates steps that you should follow and practice.
This icon indicates important information that you should study and
memorise.
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
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.
Toolbar
buttons
Text editor
Uploading
status
Message
area
Configured
board and
serial port
Writing sketches
We need to understand the different parts of the Arduino Uno board so that we can
create amazing projects.
The microcontroller
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.
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
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 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.
v (Alibaba.com, 2022)
2
1
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.
vi (Prinsloo, 2021)
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.
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:
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.
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.
Code Save
Verify &
Execute
compile
Upload
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.
• Setup() function
• Loop() function
Beginning of a function
loop function
void setup()
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.
Activity 1
Let’s explore!
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.
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.
void loop() {
Serial.print(“Let’s learn to code!”);
}
EXAMPLE 2 – SERIAL.PRINT()
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 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()
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()
Hello
Goodbye
Activity 2
Use what you’ve learned so far to print something to the serial monitor.
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.
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)
void loop() {
/*This is all commented.
Serial.println(“Hello”);
None of this code will run!*/
}
EXAMPLE 7 – MULTI-LINE COMMENT
Activity 3
Red Lion
I want to better my mark by 10% this term.
Activity 4
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 ()
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)
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()
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.
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()
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?
• 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
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
Components Needed:
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:
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.
name
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.
Variables 31
Example of a variable with a variable value:
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
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:
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.
bool
A bool holds one of two values, true or false.xxii We can use the bool datatype in
variables.
Example:
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:
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:
Minimum: 0 → 0V
Maximum: 1024 → 5V
Example:
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 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).
Minimum: 0 → 0V → LOW
Example:
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:
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
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.
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
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
2. Use an if statement to program the buzzer to sound when the push button is
pressed.
Logical OR (||)
The logical OR results in a TRUE if either of the two operands is true. xxx
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:
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.
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);
}
*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
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:
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
Using sensors 49
IR receiver Distance adjust Power LED
+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.
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
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:
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.
Using sensors 53
If both sensors are on black, the robot stops.
Code:
//Declaring variables for motor speed; the sensors will only work
correctly if the robot drives at a slower speed.
int mspeed = 200; //Analog speed.
//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);
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.
Using sensors 57
Ultrasonic sensors have two main components:
The transmitter and receiver are marked on the sensor with the letters T and R
respectively.
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)
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.
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()
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
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
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
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].
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
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].