Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

Arduino Programming Course Contents

Introduction and Requirements


Overview of the course with hardware and software requirements.
Part 1: Arduino Sketch Structure and Flow
Explains the structure of an Arduino program and how program statements are executed. Demonstrates a
simple "Hello World" program.
Part 2: Arduino Sketch Main Loop and Calling Functions
How the Arduino main loop works and what it means to call a function.
Part 3: Variables
An introduction to Arduino variables showing the use of integer (int) and floating point (float) variables.
Part 4: Arithmetic Operators
Addition, subtraction, multiplication, division and remainder on an Arduino.
Part 5: Relational Operators
Comparing values in Arduino.
Part 6: Increment Operator and Commenting
How the Arduino increment operator works. Using comments in Arduino sketches.
Part 7: The Arduino for Loop
How the Arduino for loop works. Use the Arduino for loop to loop through code a set number of times.
Part 8: The Arduino while Loop
How to use the Arduino while and do-while loops.
Part 9: The Arduino if Statement
Using the Arduino if statement. How to get keyboard input to the Arduino from the Serial Monitor Window.
Part 10: Making Decisions with if-else
Arduino if-else construct. Switch an LED on and off using the Serial Monitor window.
Part 11: Decisions with if-else-if
Arduino if-else-if and if-else-if-else constructs. Control LED blink rates using if-else-if constructs.
Part 12: Logical Operators
OR, AND and NOT logical operators used in Arduino sketches to control an LED from the Serial Monitor
window.
Part 13: Switch & Break
Part 14: Conditional Operator
Part 15: Functions
Part 16: Returning a Value from a Function
Part 17: Arrays
Part 18: Strings
Part 19: Serial Input
Introduction and Requirements
Learn the Arduino programming language and start writing your own sketches.
This Arduino programming course concentrates on teaching the Arduino programming language and
consists of a number of different parts, each covering a different topic.
By the end of the course, you will have enough knowledge and confidence to start writing your own
sketches for the Arduino.

Course Prerequisites
Before starting, you will need the following hardware and basic Arduino knowledge.

Hardware Requirements
 Arduino Uno or similar Arduino board (e.g. Arduino Mega)
 USB cable for powering and programming the Arduino board from a PC USB socket
 Breadboard and components as specified in the various parts of this course

Skills Requirements
Before starting, you will need to know the basics on how to use your Arduino, such as loading new
sketches to it and connecting some basic electronic components to it.
The beginner's course in electronics found on this website is a good place to start learning basic
electronics and includes some Arduino examples.
At the very minimum, complete starting with Arduino, using the Arduino serial port and some of the
projects from ten Arduino projects for absolute beginners.
Software Requirements
You will need the newest Arduino IDE for your platform (available for Linux, Windows and Mac).
This course uses Arduino IDE version 1.8.1 which was the latest version at the time of updating this
course. Version 1.0 or newer should work.
With the above hardware, software and skills, you are ready to start the course.
Use the links below to move to each new part of the course or use the menu on the right
Part 1 of the Arduino Programming Course
In this first part of the Arduino programming course, we look at the basic structure of an Arduino sketch
and the top-to-bottom execution of program instructions (or program flow).

Arduino Sketch Structure


A basic Arduino sketch consists of two functionscalled setup() and loop().
Open the Arduino IDE and select File → Examples → 01.Basics → BareMinimum to see the two
functions. These two functions now appear in a default new Arduino IDE window, so it is not necessary to
open the BareMinimum example sketch in a new version of the IDE.

Basic Arduino Sketch Structure

What is a Function?
Functions will be covered in more detail later, for now you will just need to know the following about
functions:
 All functions must have a unique name, setup is one example of a unique function name
(setup and loop are special functions in Arduino programming and form part of the structure of a basic
sketch).
 The function name is followed by opening and closing parentheses () that may or may not contain
something.
 All functions must have a return type. Both setup and loop have a void return type.
 The body of a function consists of an opening and closing brace ({ and }).

"Hello, world!" Sketch Example


It is a programming tradition to write a "hello world" program whenever starting to learn a new
programming language.
The "hello world" program simply writes the text "Hello, world!" to the screen. The purpose of this program
is to verify that your programming environment is properly ins
installed
talled and working. If your "hello world"
program works, then you are ready to start learning the new programming language.
The Arduino doesn't have a screen to write the "hello world" text to, but we can use the USB port
and serial monitor window.

Writing the Sketch


Modify the BareMinimum sketch that you previously opened as follows:
void setup() {
Serial.begin(9600);
Serial.println("Hello, world!");
);
}

void loop() {
}
Save the modified program as hello_world in your sketches folder by selecting File → Save As... from
the Arduino IDE menu and then renaming the file to hello_world.

Running the Sketch


Plug your Arduino into your PC using a USB cable. Click the Upload button to load the program to the
Arduino.
Now open the Arduino IDE Serial Monitor Window to see the sketch run and print the text message.
The result of running the sketch should look as follows:

Running the hello_world Sketch

The text that the program outputs should be visible in the serial monitor window.
Fault Finding
Programming Errors
Anything in the above lines of code that is typed into the IDE window incorrectly will most likely cause a
compile error, so be sure to type everything in exactly as it is shown in the code above. The program is
compiled when the Verify button (the tick icon) or the Upload button (the horizontal arrow icon) is clicked.
A compile error will show up in the bottom of the Arduino IDE as shown in the image below.

Arduino IDE Compile Error

In this example, the semicolon (;) was left off the end of this line: Serial.println("Hello, world!") which
caused the Arduino IDE to display the error message.
Setup Faults
If you had problems uploading the sketch to the Arduino, make sure that the correct Arduino board is
selected under Tools → Board and that the correct serial port is selected under Tools → Serial Port.
Baud Rate Setting Fault
If the sketch uploaded successfully, then the only problem that can prevent the text from being shown in
the serial monitor window is if the baud rate at the bottom right of the serial monitor window is not set
to 9600 as shown in the "Running the hello_world Sketch" image above.

Arduino Sketch Program Flow


In an Arduino sketch, program statements (individual lines of code) are executed or run from top to
bottom. This top-to-bottom execution of statements can only be altered by flow control statements.

Parts of a Sketch
The image below shows the parts of an Arduino sketch. Statements are lines of code that are executed
as the program runs. Each statement is terminated with a semicolon.
Parts of an Arduino Sketch

How the Hello World Sketch Works


In the hello world sketch, statements in the setup() function are run n first, from top to bottom. The
statement Serial.begin(9600); is the first statement in the setup() function, so it is run first. This statement
sets up the speed of the serial port to 9600 baud. The baud setting in the serial monitor window must
match this
is value so that the Arduino and serial monitor window are communicating at the same speed.
The second statement to run in the setup() function is Serial.println("Hello, world!"); which sends the
text Hello, world! out of the serial / USB port for display in the serial monitor window. In this statement,
any text can be put between the opening and closing quotes (("")) and it will be displayed in the serial
monitor window.

The setup() Function


Statements in the setup() function are run only once, every time th
that
at the sketch is run. The program then
starts executing statements in the loop() function.
The sketch will run after it has been programmed into the Arduino. Opening the serial monitor window will
reset the Arduino and cause it to run the sketch again.
The sketch can also be rerun by pressing the reset button on the Arduino or disconnecting and then
reconnecting the power to the Arduino.

The loop() Function


Statements in the loop() function will run continuously from top to bottom and then back to the top.
If the loop() function contains two statements, the first statement will be executed, then the second
statement, then the first statement again and so on in a loop.
As there are no statements in the loop() function in our hello world example, program execu
execution will end
up in the loop and get stuck there doing nothing.
It is important to have the loop() function in the sketch, even if it is empty, because without it the
microcontroller on the Arduino board will try to execute whatever it finds next in memory after the
statements in the setup() function have been executed. The microcontroller will try to execute whatever it
finds in memory as an instruction, but the loop() function prevents it from doing this by keeping program
execution in the loop.
In the next
xt part of this course, we will put some program statements in the loop() function to see how it
works.
Part 2 of the Arduino Programming Course
Part 2 of the Arduino programming course explains what a loop is in software and demonstrates how the
main loopp of an Arduino sketch works.
A function in a sketch performs some task (i.e. performs a function). We say that we "call a function"
when we use a function to perform its specified task. This is explained in the second half of this part of the
course.

The Main Loop


As seen in the previous part of this course
course,, an Arduino sketch consists of two main functions
called setup() and loop().. The loop() function is the main loop in the Arduino sketch. After statements that
only need to be run once have finished being executed in the setup() function, program execution starts in
the loop() function.
Once program execution has started in the main loop, the statements in the main loop will be executed
continuously until the Arduino is switched off or reset. The main loop is where the actual operational
functionality of the Arduino takes place – for example, if the Arduino is programmed to be a flashing light
sequencer, then the flashing light functionality will be placed in the main loop.

Why is it Called a Loop?


Statements in the loop() function will be executed from top to bottom, until the bottom of the loop()
function is reached. When the bottom of the loloop
op function is reached, statements are executed from the
top of the loop() function again, thus completing the "loop" as shown in the image below.

Loop Demonstration Sketch


The main_loop sketch shown below, demonstrates how the main loop works in an Ardu Arduino sketch. Type
the sketch into your Arduino IDE, or copy and paste it into the IDE.
Load the sketch to the Arduino and then open the serial monitor window to see the sketch output text as it
runs.
void setup() {
Serial.begin(9600);
Serial.println("*** This message will only be displayed on start or reset. ***");
delay(2000);
}

void loop() {
Serial.println("-- Arduino now at top of main loop. --");
Serial.println("--------------------------------------
--------------------------------------");
delay(2000);
Serial.println("Executing instructions in main loop.");
delay(2000);
Serial.println("Arduino now at bottom of main loop.\r\n");
}
The text that the sketch prints to the serial monitor window is shown below.
The Output of the main_loop Sketch

As the above demonstration shows, the text in the setup() function is only displayed once when the serial
monitor window is first opened and the Arduino is reset. After this, program execution enters the loop()
function and repeatedly executes the statements in the loop from top to bottom and back to the top again
in a never ending loop.

Functions in the Loop Demonstration Sketch


In the main_loop sketch above, each statement in setup() and loop() consists of a function being called –
i.e. being called means that it is executed or run.

The delay() Function


When the delay() function is called in the statement delay(2000); then the delay function causes a
waiting period of 2 seconds (2000 milliseconds – there are 1000 milliseconds in one second, also written
1000ms). The time of the delay can be changed by passing a different value to delay(), e.g. 3000 will
cause a 3 second delay: delay(3000);

The println() Function


The println() function sends text out of the serial / USB port of the Arduino and is displayed in the serial
monitor window.
The println() function is different from the delay() function in that it has Serial and a dot (.) before
it: Serial.println("Text to print.");
The reason for this notation (Serial.function_name()) is because the function acts on the serial port or
Serial object. You will notice in setup() that Serial.begin() is called. This is the begin() function acting on
the serial port – in this case to set it to the desired speed.
These functions that are preceded by an object name (e.g. Serial) are called "methods" in object oriented
programming.

A Summary of Functions
The following will hopefully clear up what functions are and the terminology used with them. A deeper
understanding of functions will only be possible once we start writing our own functions.
setup() and loop()
setup() and loop() are two special functions that form part of the structure of an Arduino sketch.
We are actually writing these special functions by giving them a function body (between the opening and
closing braces: {}) and writing statements in the function body.
The statements in these functions in the above sketch were calling pre-existing functions that perform the
tasks that we want, e.g. set up the serial port speed, cause a time delay, write text to the serial monitor
window.
The setup() and loop() functions are automatically called at the right time because they are special
Arduino functions.

Calling Functions
By calling or using pre-existing functions, we are using code that someone else has already written.
The delay() function has a function body that contains statements that cause it to perform a delay. We do
not see these statements or the function body because they are either part of the Arduino programming
language or exist in an external function library.

Passing a Value to a Function


When a value (e.g. a number or text string) is used by a function, we must pass the value to the function.
Passing a Value to the delay() Function
We call the delay() function in the sketch as in the following statement:
delay(2000);
The delay value in milliseconds (2000) is said to be passed to the function.
Passing a Value to the println() Function
We pass a text string to the println() function as shown in this statement:
Serial.println("Executing instructions in main loop.");
We must pass the text string to the function so that the function knows what to send out of the serial /
USB port. The text between the opening and closing quotation marks ("") is known as a string in
programming.

A Commentary on the main_loop Sketch


The main_loop sketch from above can be seen here again, but with commentary explaining what is
happening in the sketch.
void setup() {
The Arduino sketch starts to run here when the setup() function is automatically called.

First we set up the serial port at the baud rate of 9600 which must match the baud rate
in the serial monitor window. The baud rate can be thought of as the speed that
communication is taking place at between the Arduino and serial monitor window.
Serial.begin(9600);

A line of text (known as a "string" of text in programming languages) is sent out of


the serial / USB port for display in the serial monitor window.
Serial.println("*** This message will only be displayed on start or reset. ***");

A 2 second delay has been added so that the next text to be displayed in the serial
monitor window does not appear immediately.
delay(2000);
}

The statements in the setup() functions have all finished being executed, so now the
loop() function is called automatically.
void loop() {
Now that execution is taking place in the loop, the statements inside the loop()
function will be executed from top to bottom. When the bottom of the loop is reached,
all the statements will be executed again from top to bottom.

This text is sent to the serial monitor window and is the first statement to be
executed in the loop.
Serial.println("-- Arduino now at top of main loop. --");

This text is just to highlight that we are at the top of the loop. Because there is
no delay between the above text and this text, both appear at the same time in the
serial monitor window.
Serial.println("--------------------------------------");

A two second delay so that the line of text that follows does not appear instantly
with the above text.
delay(2000);

We are now executing statements (also called instructions) in the middle of the main
Arduino loop. This statement sends more text to the serial monitor window.
Serial.println("Executing instructions in main loop.");

Another delay so that the line of text that follows does not appear at the same time
as the line of text above.
delay(2000);

The last statement in the loop and the last text that gets sent to the serial monitor
window before returning to the top of the loop to start executing statements again.
The println() function causes the invisible cursor to move to the next line in the
serial monitor window. This causes the next text sent to the serial monitor window
to appear on the line below the currently printed text.
The \r\n at the end of this text of string moves the invisible cursor down one more
line leaving a blank line between the text printed at the bottom of the loop and the
text printed at the top of the loop.
Serial.println("Arduino now at bottom of main loop.\r\n");
}
Part 3 of the Arduino Programming Course
A variable is used in programming to store a value that may change during the life of the program (or
sketch).
Memory is set aside for storing the variable and the variable is given a name which allows it to be
accessed in the sketch.
One example of a variable is if you were to write a sketch that keeps the total of a teams score in a sports
match. The value that the variable is holding (i.e. the teams score) would be displayed on a screen while
the sports match is being played. As the score increases, the value that the variable holds will be
increased and the display on the screen would be updated showing the new value that the score variable
now holds.
In this example, the score value may change several times during the match and the time that the sketch
is running. It is therefore variable as opposed to a fixed or constant value.

Using a Variable
The following sketch called variables demonstrates the use of a variable. Load this sketch to your
Arduino and open the serial monitor window to see the output of the sketch.
void setup() {
int count;

Serial.begin(9600);

count = 0;
Serial.println(count);
count = 1;
Serial.println(count);
count = 2;
Serial.println(count);
}

void loop() {
}

Variable Definition
The following statement from the above sketch is a variable definition as it defines the variable type and
name:
int count;
Variable Type
In the above example, the variable type is int. This means that the variable can hold an integer value.
An integer is a whole number – i.e. not a fraction. For example, the following numbers are integers 2, 5, 0,
100, 1024, -32, etc.
Variable Name
The above variable has been given the name count. This variable can now be referenced or used in the
sketch by using the name "count".
By giving the variable a type and name, space is made available in memory for this variable.

Using the Variable in a Sketch


After a variable has been defined, it can be assigned a value and the value of the variable can be
displayed in the serial monitor window.
In the following two statements, the count variable is first assigned a value of 0 and then the value that
this variable is holding is sent out of the serial port for display in the serial monitor window.
count = 0;
Serial.println(count);
In the sketch, the same lines of code are repeated, but each time the count variable is assigned a
different value.

Types of Variables
The integer (int) variable type is only one type of variable. An example of a different variable type is
a float or floating point variable.
A floating point variable is used to store a number that contains a fraction, e.g. 1.45, 99.99, 362.5634, -
200.21, etc.
A floating point variable is defined in the same way as an integer variable, except that the float keyword is
used instead of int as shown in the example below.
float average;
This floating point variable can now be assigned a floating point value e.g.:
average = 1.2;

Printing a Float Value


To print or send a floating point value to the Arduino serial monitor window, the println() function can be
used.
A second parameter can be passed to the println() function to specify the number of decimal places that
must be printed as shown in the floats sketch below.
void setup() {
float average;

Serial.begin(9600);

average = 12.3299;

Serial.println(average);

Serial.println(average, 4);
}

void loop() {
}
The output of the above sketch is shown here.

The above sketch assigns a value of 12.3299 to the average floating point variable. When the value of
the variable is sent to the serial monitor window, we can see that println() automatically rounds the
number off to two decimal places.
The second time that println() is used to send the value of the variable to the serial monitor window, the
number of decimal places is specified as 4. This is done by passing a second parameter value of 4 to the
println() function.

Other Variable Types


Other types of variables that are available can be seen in the Arduino language reference under
the Variables heading.
On this course, each variable type will be introduced and explained at the appropriate time.
Naming Variables
Variables can be given any name that you like, so long as it sticks to the rules set out below. It is best to
give variables meaningful names that help you and others to understand the sketch better,
e.g. score_total would be a good variable name for a variable that is storing the running total of a score
in a sports match.

Variable Naming Rules


 Variables can consist of any letters (a to z and A to Z)
 Variables can contain the numbers 0 to 9, but may not start with a number, e.g. 3var is not allowed,
but var3 is allowed
 Variables may not have the same names as Arduino language keywords, e.g. you can not have a variable
named int
 Variables must have unique names i.e. you can not have two variables with the same name
 Variable names are case sensitive, so Count and count are two different variables
 Variables may not contain any special characters, except the underscore (_), e.g. top_score

Initializing Variables
In the above example sketches, the variables that were used were first defined, and then assigned a
value.
A variable can also be assigned an initial value when it is defined as shown below:
int total = 0;
In this example, the integer value named total is defined and assigned a value of zero (0) in one
statement.

Notes
In this part of the course and other parts where concepts need to be explained, the example code will
often be put in the setup() part of the sketch, rather than the loop() part. This is because the code usually
only needs to run once to demonstrate some concept.
Most sketches that are written will have the bulk of the code in the loop() function and only code that
initializes hardware in the setup() function.
Part 4 of the Arduino Programming Course
The Arduino can do mathematics for us. In this part of the course, we look at how to do addition,
subtraction, multiplication, division, and find a remainder.
Below, five arithmetic operators are described and then all put into a sketch to demonstrate how they
work on the Arduino.

Addition
To add numbers on the Arduino, we use the addition operator (+).
The example below shows how to add two numbers together.
int a = 2;
int b = 7;
int sum;

sum = a + b;
In the above code, three variables are defined. Variables a and b are each assigned a value when they
are defined.
The sum variable is defined, but not initialized, so contains any random number. We will use this variable
to store the result of the addition calculation, so the random value that sum contains will be overwritten
when we put the addition result (or sum) into it.
After the statement shown below has been executed, sum will contain the value 9 i.e. the result of the
addition of variable a and b.
sum = a + b;

We can also add two constant values and store the result in a variable as shown below.
int sum;

sum = 2 + 10;
The result stored in sum after execution of the addition statement will be 12 in this example.
Constant values and variables can also be added together and the result stored in a variable as shown
here.
int a = 3;
int sum;

sum = a + 24;
After execution of the addition, sum will contain 27.
The remaining arithmetic operators can also operate on constant values, variables and a mixture of both.

Subtraction
The subtraction operator subtracts one number from another using the minus sign (-) as the following
example shows.
int result;

result = 10 - 2;
The result of this calculation will be 8 and will be stored in the result variable.

Multiplication
Multiplication is done by using the multiplication operator (*).
int result;

result = 4 * 3;
The result of the above calculation will be 12 and will be stored in the result variable.
Division
The division operator (/) is used to perform division in the Arduino.
int result;

result = 12 / 3;
The result of the above calculation is 4.

Integers vs. Floating Point


So far we have only been using integer values to perform arithmetic. If the result of a division is not an
integer (or whole number), but contains a fraction part, the fraction part will be discarded if the result is
stored in an integer variable.
The following examples will demonstrate what happens when a result with a fractional part is stored in an
integer and then a floating point variable.
int result;

result = 5 / 4;
The result will be 1 because the fraction is discarded when the result is stored in the integer
variable result.
The same calculation, but this time defining result as a floating point variable (float).
float result;

result = 5.0 / 4.0;


The result now contained in the result variable is 1.25.
When using constant values in calculations that store the result in a floating point variable, we use a
decimal point and a zero for whole numbers, i.e. 5.0 instead of 5 on its own.

Remainder (Modulo Division)


The remainder operator (or modulo operator) is used to find the remainder after the division of two
numbers. The percentage sign (%) is used as the modulo operator.
int result;

result = 11 % 4;
The result of this calculation will be the remainder of 11 divided by 4 which is 3 (4 goes into 11 twice
leaving a remainder of 3).

Arithmetic Sketch
The following sketch called arithmetic demonstrates all of the above arithmetic operators.
Load the sketch to your Arduino and try it out. Also add the examples from above that are not in the
sketch, such as mixing constant values and variables.
void setup() {
int a = 2;
int b = 7;
int result;
float result_fl;

Serial.begin(9600);

Serial.print("Addition (a + b): ");


result = a + b;
Serial.println(result);

Serial.print("Subtraction (10 - 2): ");


result = 10 - 2;
Serial.println(result);

Serial.print("Multiplication (4 * 3): ");


result = 4 * 3;
Serial.println(result);

Serial.print("Int Division (5 / 4): ");


result = 5 / 4;
Serial.println(result);

Serial.print("Float Division (5.0 / 4.0): ");


result_fl = 5.0 / 4.0;
Serial.println(result_fl);

Serial.print("Remainder (11 % 4): ");


result = 11 % 4;
Serial.println(result);
}

void loop() {
}

Comments on the Sketch


print() Function
The sketch contains a mix of print() and println() functions. print() is called when the invisible cursor
must stay on the same line so text printed in the println() statement that follows will be printed on the
same line as well.
println() Function
println() is used when text must be printed and then the invisible cursor moved to the next line so that the
next print() statement will print text on a new line.
Floating Point Variable
A separate result_fl variable was defined to hold the result of the floating point calculation.
Integer Variable
The integer variable result is reused many times during the sketch. The important thing is to display its
result before placing the result of the next calculation into it.
Constants and Variables
We looked at variables in the last part of this course. Constants are numbers that remain constant
throughout a sketch – i.e. they never change.
Examples of constants are the numbers that are used directly in a calculation and are not assigned to a
variable, e.g. sum = 2 + 3 contains the constants 2 and 3.
Constants do not have a name and their values can not be changed when the sketch is running.
Floating Point Arithmetic
Although not shown in the above examples, addition, subtraction and multiplication can also be done on
floating point values.
Part 5 of the Arduino Programming Course
Relational operators test the relationship between values, for example is the number 7 greater than the
number 5; or is the value that a variable holds less than 10.
The result of a comparison of two values by a relational operator will either be true or false, for example is
the value contained in a variable equal to 8? The answer will either be true (it does hold the value 8) or
false (it does not hold the value 8).
In programming, true is represented by the value 1 and false is represented by the value 0. The example
that follows will help to clarify this explanation of relational operators.

Relational Operator Example


The following sketch uses the greater than (>) relational operator and the less than (<) relational operator
to compare two numbers.
void setup() {
Serial.begin(9600);

Serial.print("Is 7 greater than 5? ");


Serial.println(7 > 5);

Serial.print("Is 7 less than 5? ");


Serial.println(7 < 5);
}

void loop() {
}
The output of the above sketch is shown here.

The first relational operator tests whether 7 is greater than 5: 7 > 5


7 is greater than 5, so the output from this comparison is true or 1.
The second relational operator tests whether 7 is less than 5: 7 < 5
7 is not less than 5, so the output from the comparison is false or 0.

Types of Relational Operators


The Arduino programming language has 6 relational operators listed below.

Greater Than >


We have already seen the greater than relational operator working in the above example. Here is another
example using the same operator to compare the contents of two variables.
int a = 2;
int b = 3;

Serial.println(a > b);


The relational operator asks the question "Is a greater than b?".
The result of the comparison will be 0 (false) in this example because the value that variable a contains is
not greater than the value that variable b contains.

Less Than <


Here we use the less than relational operator to compare the contents of the same two variables.
int a = 2;
int b = 3;

Serial.println(a < b);


The relational operator asks the question "Is a less than b?".
The output of this sketch will be 1 (true) because the value that variable a contains is less than the value
that variable b contains.

Greater Than or Equal To >=


This operator acts in the same way as the greater than operator, but will also evaluate to true (1) if the
two values being compared are equal to each other.

Less Than or Equal To <=


This operator will evaluate to true (1) if the value on the left of the operator is less than the value on the
right of the operator; or if the two values are equal.

Equal To ==
The equal to relational operator will only evaluate to true (1) if both values being compared are equal,
otherwise it will evaluate to false (0).
It is easy to forget to use two equals signs (==) and use only one equals sign for the equal to relational
operator. Using only one equals sign will cause the variable on the left of the operator to be assigned the
value of the variable or constant on the right. If the value on the left is a constant, a compile error will
occur if a single equals (=) is used instead of a double equals (==).

Not Equal To !=
The not equal to relational operator will only evaluate to true if the two values being compared to each
other are not equal to each other, otherwise it will evaluate to false.zon.com
Relational Operator Sketch
The Arduino sketch below demonstrates relational operators.
void setup() {
int a = 2;
int b = 3;

Serial.begin(9600);

Serial.print("Is a greater than b? ");


Serial.println(a > b);

Serial.print("Is a less than 25? ");


Serial.println(a < 25);

Serial.print("Is a greater than or equal to b? ");


Serial.println(a >= b);

a = 3;
Serial.print("Is a greater than or equal to b? ");
Serial.println(a >= b);

a = 4;
Serial.print("Is a greater than or equal to b? ");
Serial.println(a >= b);

Serial.print("Is a equal to b? ");


Serial.println(a == b);

b = 4;
Serial.print("Is a equal to b? ");
Serial.println(a == b);

void loop() {
}
Copy this sketch and run it on your Arduino. Experiment with relational operators to make sure that you
understand them.
Things to Note in the Sketch
Evaluating and Printing an Expression
Something to note in the above sketches is that an expression is evaluated and printed in one statement.
The result of the relational operator expression is not first saved to a variable and then printed.
This can also be done with arithmetic operators as shown here:
void setup() {
int a = 2;
int b = 3;

Serial.begin(9600);

Serial.print("a + b = ");
Serial.println(a + b);
}

void loop() {
}
The output of the above sketch is shown here:

The expression a + b is both evaluated (to get the value of 5) and printed in the same statement.
Confusing = and ==
As already noted, it is easy to forget the second equals sign when using the equal to operator. The
sketch below shows what can happen with this mistake.
void setup() {
int a = 2;
int b = 3;

Serial.begin(9600);

Serial.print("a == b: ");
Serial.println(a == b);

Serial.print("a = b: ");
Serial.println(a = b);
}

void loop() {
}
The comparison of a and b in the expression a == b is correct and evaluates to 0 as expected.
If the second equals sign is left off as shown in the second expression a = b, the assignment operator (=)
is accidentally used instead of the equal to operator (==).
This causes a to be assigned the value of b which is 3 and then 3 is printed out. A non-zero number will
actually evaluate to true as we will see later in this course.
Part 6 of the Arduino Programming Course
The increment operator is an Arduino arithmetic operator that is used to increment an integer variable by
a value of one. We look at how to use the increment operator in this part of the Arduino programming
course.
Comments in programming are notes that are written in a program (or sketch) by the programmer. These
notes are used to explain what the code is doing, or to add other useful human readable information to
the code. How, when and why to use comments are explained at the end of this part of the course.

Arduino Increment Operator


The Arduino increment operator is used to increase the value that a variable holds by one. This is useful
in certain types of loops as will be shown later in this course.

Increment Operator Example 1


The example below shows the increment operator being used to increment a value several times.
void setup() {
int count = 0;

Serial.begin(9600);

Serial.println(count++);
Serial.println(count++);
Serial.println(count++);

Serial.println(count);
}

void loop() {
}
Sketch Output
The output of the sketch in the Arduino serial monitor window is shown here.

Initializing the Variable to Increment


In the above example, the variable count is defined and initialized to a value of 0 (zero).
It is important to initialize this variable before using the increment operator because if it is not initialized, it
can contain any random value. Here we initialize it to 0, but could have used any other integer value.
Printing and Incrementing
Serial.println() is used to print the value of count, but in the same statement, the increment operator (++)
is used to increase the value that the count variable holds.
The increment operation causes the value in count to increase from 0 to 1.
Post Incrementing
Placing the ++ after the variable name (count++) is a post increment operation. This means that the
variable is used in the statement and only incremented after this.
Because of the post increment operation, the initial value of count (which is 0) is printed by the first
println() function, and only incremented after this.
The next println() function prints the new incremented value (now 1) and then the increment operator in
the statement increments the value of count after it has been printed – it is now incremented to 2.
The third println() statement prints out 2 and increments the value in count to 3.
The final println() statement prints out the value of count but does not use the increment operator. It
prints out the value of 3 which the variable was previously incremented to.

Increment Operator Example 2


The following sketch does exactly the same as the previous sketch, but the increment operations and
print operations have been separated into their own statements.
This example may help to clarify what is happening in the previous example. We can see that the first
println() statements prints the value of count and only after this is the value in count incremented.
void setup() {
int count = 0;

Serial.begin(9600);

Serial.println(count);
count++;
Serial.println(count);
count++;
Serial.println(count);
count++;

Serial.println(count);
}

void loop() {
}
From these two examples, we can see that this single line of code:
Serial.println(count++);
Is the same as these two lines of code:
Serial.println(count);
count++;
The important thing to note is that the incrementing of the variable takes place after printing it, so the
value that the variable holds is printed before it is updated to the new incremented value.
As always, load the code to your Arduino and experiment with it.

Amazon.co.uCommenting Sketches
Commenting sketches allows you to write your own text notes along with the code of the sketch. The next
sketch shows two ways of writing comments.
/*
Sketch Name: comments

Purpose: Demonstrates how to use comments.


Increments and displays a number in the main loop.

Date: 28 September 2014

Author: W.A. Smith


*/
void setup() {
Serial.begin(9600); // use the serial port for printing the number
}

int count = 0; // the number to print

void loop() {
Serial.println(count++); // print and increment the number
delay(1000); // 1 second delay between printing
}

Multi-line Comments
Comments can be written on multiple lines when using the opening forward slash asterisk (/*) and closing
asterisk forward slash (*/) as shown at the top of the sketch.
Any text comments can be written between the opening and closing of the comment and can span
multiple lines. All text in the comment will be ignored by the compiler.
This style of commenting can also be used on a single line, but must always be closed with the asterisk
and forward slash as shown below.
delay(1000); /* 1 second delay between printing */
There is an easier way to comment a single line of code, by using the single line comment, explained
next.

Single Line Comments


The double forward slash (//) is used to create a single line comment. All text to the right of the double
forward slash on the same line will be a comment and will be ignored by the compiler.
The single line comment can be used on its own line or to the right of a program statement.
// the delay slows down the printing of the numbers
delay(1000); // 1 second delay between printing

What Comments are Used For


Comments are used to explain how parts of a sketch work, rather than explain the actual programming
language that is being written.
When you come back to a program or sketch that you wrote a month or a year ago, you may not
remember why you wrote some part of the sketch a particular way. By writing comments in the sketch,
you are making notes for yourself to help explain what you were doing when you first wrote the sketch.
Comments can also be arranged as a header section or comment block, like the multi-line comment block
at the top of the example sketch. The block contains the name of the sketch, description or purpose of the
sketch, date that it was written and the authors name. Comments can also contain references to any
books, websites or other resources that were used when writing the sketch.
In short, comments and comment blocks communicate helpful information about the sketch for yourself
and for other programmers who may also use the sketch.
Part 7 of the Arduino Programming Course
We have already looked at one type of loop on this course namely, the Arduino main loop in part 2.
In this part of the Arduino programming course, we look at anothe
anotherr kind of loop called the "for" loop.
Whereas statements or code in the Arduino main loop will run continually and never exit the loop,
the for loop allows us to loop through code a certain number of times before exiting the loop.
A common way to use the for loop is with the increment operator that was covered in the previous part of
this course.
Using the for Loop
The following sketch demonstrates the use of the for loop.
void setup() {
int i;

Serial.begin(9600);

for (i = 0; i < 10; i++) {


Serial.print("i = ");
Serial.println(i);
}
}

void loop() {
}
How the for Loop Works
The image below shows the parts of the for loop.

Parts of a for Loop in an Arduino Sketch


for Loop Structure
A basic for loop is started as follows:
for () {
}
Three expressions are added between the opening and closing parentheses () that determine how many
times the statements in the loop are run before exiting the loop. When the loop is exited, program
execution continues below the loop – i.e. statements outside and below the loop are executed from top to
bottom.
The body of the loop between the opening and closing braces {} contains statements that will run in the
loop.
The expressions between the parentheses ar are
e called the initialize expression, test expression and
increment expression.
A variable must be defined to use in the three loop expressions. In the example sketch an integer variable
called i is used.
The three loop expressions must appear in the order: initialize, test and increment. They are separated by
semicolons (;). ). The increment expression does not end with a semicolon.
Initialize Expression
The initialize expression is only run once at the time that the loop starts. It initializes our i variable to zero
(0) in the example sketch.
Test Expression
The test expression determines when we break out of the loop. It is used to set the number of times that
the statements in the body of the loop are run.
When the test expression evaluates to true, the statements
ments in the loop body will be run. When the test
expression evaluates to false the loop will not be run again, but will be exited.
The test expression is evaluated every time that execution starts at the top of the loop.
Increment Expression
The increment expression is used to change the value that the i variable holds. It is run every time that
execution starts at the top of the loop.
Program Flow in the Loop
The image below shows how program flow works in the for loop.

for Loop Program Flow


First Time Through the Loop
The first time through the loop, i is initialized to 0, the test expression tests whether i < 10 (0 < 10) which
is true, so the statements in the loop will run.
Because the post increment operator is used with the variable, i will only be incremented at the end of the
loop. The statements in the loop run and print the value of i as 0 because it has not yet been
incremented.
We therefore have this:
i is initialized to 0
i contains 0
i < 10 evaluates to true or 1 because i is less than 10
The two statements in the loop run, print i as 0
At the end of the loop i is incremented so i == 1

Second Time Through the Loop


The second time through the loop, i now contains 1 as it was incremented at the bottom of the loop. The
test expression now tests whether i < 10 (1 < 10) which is true, so the statements in the loop will run
again. The i variable will only be incremented to 2 at the bottom of the loop, so 1 is printed to the serial
monitor window.
We now have this:
i is not initialized again
i contains 1
i < 10 evaluates to true or 1 because i is less than 10
The two statements in the loop run, print i as 1
At the end of the loop i is incremented so i == 2

Last Time Through the Loop


Execution of the loop will continue and i will be incremented every time.
The last time through the loop, we have this:
i is not initialized again
i contains 9
i < 10 evaluates to true or 1 because i is less than 10
The two statements in the loop run, print i as 9
At the end of the loop i is incremented so i == 10

Execution starts at the top of the loop again, the evaluation expression is tested.
We now have this:
i is not initialized again
i contains 10
i < 10 evaluates to false or 0 because i is not less than 10 (it is equal to 10)
The statements in the loop are not run again
The loop is exited
The statement below the closing bracket of the loop will be run

Alternative Way of Writing the for Loop


The sketch that follows shows that the variable used in the loop expressions can also be defined in the
loop and does not have to be defined outside the loop as the previous sketch did.
void setup() {
Serial.begin(9600);

for (int i = 0; i < 10; i++) {


Serial.print("i = ");
Serial.println(i);
}
}

void loop() {
}
This sketch works exactly the same as the previous sketch and outputs the numbers 0 to 9.

A Loop Within a Loop


The next sketch uses a for loop within the Arduino main loop.
void setup() {
Serial.begin(9600);
}

void loop() {
for (int i = 0; i < 10; i++) {
Serial.print("i = ");
Serial.println(i);
}
delay(1000);
}
The for loop works exactly the same as it did before, but now after it has been exited, the delay() function
is run to give a 1 second delay. The end of the Arduino main loop loop() is reached, so the for loop is run
again.
When the for loop is run again, i is initialized to 0 because the for loop is being started from the top again.
It then runs again as previously described.
The for loop and delay() function will be run continually because the main Arduino loop never exits.
Notes on the for Loop Sketch Examples
Note the following about the sketch examples in this part of the course.

Initialize Expression
The initialize expression in the for loop does not have to be initialized to zero (0), but can be initialized to
any integer value, even a negative value.
Increment Expression
The increment expression is used to change the value of the variable that the test expression tests. This
does not have to be an increment operator, but can be the decrement operator (subtracts 1 from the
variable) or any other arithmetic expression.
The increment operator has been used in the example sketches to keep things simple at the beginning of
the course, and because it is a common way of using the for loop. We will look at other ways to use
the for loop later in the course.

Counting from Zero (0)


Note that in the example sketches, that the value that the i variable contains is initialized to 0 and not 1.
We therefore print out a count value that starts at 0 and ends at 9.
The loop is actually run 10 times and not 9 times. This is because we are starting at 0 – 0 to 9 are 10
numbers, 1 to 9 are 9 numbers, 1 to 10 are 10 numbers.
This list shows the number of times through the loop on the left and the value of i on the right.
1. i = 0
2. i = 1
3. i = 2
4. i = 3
5. i = 4
6. i = 5
7. i = 6
8. i = 7
9. i = 8
10. i = 9
Part 8 of the Arduino Programming Course
The while loop is similar to the for loop that was explained in the previous part of this Arduino
programming course. The main difference is that the while loop separates the elements of the forloop as
will be shown.
Another loop called the do while loop is also covered. The do while loop is always run at least once before
any tests are done that could break program execution out of the loop.
The while Loop
The sketch that follows does exactly the same as the for loop sketch from part 7 of this course, except
that it uses the while loop so that we can see the similarities between the two loops.
void setup() {
int i = 0;

Serial.begin(9600);

while (i < 10) {


Serial.print("i = ");
Serial.println(i);
i++;
}
}

void loop() {
}
while Loop Structure
The while loop has a structure as follows:
while (loop test expression goes here) {
Statements that run in the loop go here
Statement 1
Statement 2
...
}
The while loop starts with the while keyword followed by a test expression between opening and closing
parentheses. Opening and closing braces denote the body of the loop.
Test Expression
As with the for loop, the while loop has a test expression that will determine whether the statements in the
loop will run or not. If the test expression evaluates to true, the loop statements are run. If the test
expression evaluates to false, the loop statements will not be run, but the statements that follow the
closing brace of the loop will be run – i.e. execution continues outside and below the loop.
Initialize Expression
The for loop had an initialize expression as part of the loop. The while loop can use any variable from the
sketch that contains a valid value. In the example sketch, the variable used in the loop (i) must be
initialized when it is defined, otherwise it will contain any random value.
Increment Expression
An increment expression was used in the for loop examples in the previous part of this course. In
the while loop example, the increment expression is placed inside the loop body.
How the while Loop Example Works
In the example sketch, the following happens:
1. The variable i is initialized to 0 when the sketch starts running.
2. The while loop evaluates the test expression (i < 10).
3. The test expression evaluates to true because i is less than 10.
4. Because the test expression is true, the statements in the loop run.
5. The current value of i is printed and then incremented.
6. When the bottom of the loop is reached, execution is started at the top of the loop again.
7. The test expression is evaluated again, it is true again, so the loop runs again.
Only when the variable i has been incremented to 10, will the loop expression evaluate to false and the
loop will be exited.
while Loop Example 2
In the example sketch below, the while loop is used to count up to twenty-five in fives by adding five to a
variable each time through the loop.
void setup() {
int sum = 0;

Serial.begin(9600);

// count up to 25 in 5s
while (sum < 25) {
sum = sum + 5;
Serial.print("sum = ");
Serial.println(sum);
delay(500); // 500ms delay
}
}

void loop() {
}
In this sketch, a variable called sum is defined and initialized to 0. The test expression in the while loop
tests if sum contains a value less than 25.
Inside the loop, the sum variable is incremented by 5 each time through the loop by the arithmetic
expression:
sum = sum + 5;

This expression means "add 5 to the sum variable".


The value that the sum variable holds is then printed out, followed by a half-second delay.
Because the value of the variable is first incremented and then printed out, we see the value 5 printed first
and not the value of 0 that it was initialized to.
Although the test expression will evaluate to false when sum == 25, 25 is still the last number that is
printed. This is because the last time that the test expression evaluates to true is when sum == 20,
but sum is then incremented to 25 and printed before the test expression is evaluated again.

The do while Loop


The do while loop works in the same way as the while loop, except that it always runs once even if the
test expression evaluates to false.
do while Loop Structure
The do while loop consists of two keywords do and while, as shown below.
do {
Statements that run in the loop go here
Statement 1
Statement 2
...
} while (test expression goes here);
The body of the do while loop falls between opening and closing braces and contains statements that are
to be run in the loop.
The while keyword and test expression come after the body of the loop and are terminated by a
semicolon (;).
do while Loop Example
This example demonstrates the do while loop.
void setup() {
int sum = 0;

Serial.begin(9600);

// count up to 25 in 5s
do {
sum = sum + 5;
Serial.print("sum = ");
Serial.println(sum);
delay(500); // 500ms delay
} while (sum < 25);
}
void loop() {
}
All the statements are run in the loop body before the test expression is evaluated.
If sum is initialized to a value of 25 when it is defined, as shown in the sketch below, the loop will run
once and 30 will be printed. The loop will then not run again because the test expression evaluates to
false.
void setup() {
int sum = 25;

Serial.begin(9600);

// count up to 25 in 5s
do {
sum = sum + 5;
Serial.print("sum = ");
Serial.println(sum);
delay(500); // 500ms delay
} while (sum < 25);
}

void loop() {
}
Using the same sketch, but changing the do while loop to a while loop, as shown below, the statements in
the loop body will never run. This is because the test expression is evaluated before executing statements
in the loop body. The test expression immediately evaluates to false, so the loop statements will never
run.
void setup() {
int sum = 25;

Serial.begin(9600);

// count up to 25 in 5s
while (sum < 25) {
sum = sum + 5;
Serial.print("sum = ");
Serial.println(sum);
delay(500); // 500ms delay
}
}

void loop() {
}
In the above example, no output will be seen in the serial monitor window when the sketch is run.
The while loop evaluates to false and then execution drops straight into the empty main Arduino loop.
Part 9 of the Arduino Programming Course
In this part of the Arduino programming course, the if statement is used to show how decisions can be
made in a sketch.
An if statement is used to check for keyboard input to the Arduino that a user types into the Serial Monitor
Window of the Arduino IDE.
Further decisions can be made, depending on which key the user presses, for example, if the '1' key is
pressed, the on-board LED of the Arduino can be switched on and if the '0' key is pressed, the LED can
be switched off while all other key presses are ignored.

Using the if Statement


The sketch below shows the if statement being used in a sketch to check if a character has been sent
from the Arduino IDE serial monitor window.
void setup() {
Serial.begin(9600);
}

void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read(); // get the character
Serial.print("You typed: ");
Serial.println(rx_byte);
}
}
If the user sends a character from the serial monitor window, the Arduino sends back the text "You typed:
X", where X is the character that the user typed.

How the Sketch Works


Arduino if Statement Structure
The structure of an if statement is shown here:
if (conditional expression) {
Body of if statement
}
If the conditional expression evaluates to true, the code in the body of the statement is run. If the
conditional statement evaluates to false, none of the code in the body of the if statement will be run.
Checking for a Character from the Serial Monitor Window
In the example sketch, the value that Serial.available() returns will only be greater than 0 if one or more
characters has been received by the Arduino from the serial monitor window.
The if statement will only evaluate to true if one or more characters has been received.
When no characters have been sent to the Arduino, the if statement will be evaluated each time through
the main loop and evaluate to false each time. The code in the body of the if statement will therefore not
be run.
As soon as a character is sent from the serial monitor window, Serial.available() returns 1. When
the ifstatement is evaluated again, it evaluates to true (because 1 > 0) and the code in the body of
the ifstatement is run.
The character that was sent from the serial monitor window is the stored in the rx_byte variable using the
following line of code.
rx_byte = Serial.read(); // get the character
Because the character has been stored, it can now be sent back to the serial monitor window with some
preceding text.

Using the if Statement to Switch On an LED


The if statement can be used to make a decision to switch on an LED if a certain character is received as
this next example shows.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}
void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read();
if (rx_byte == 'a') {
digitalWrite(13, HIGH);
}
}
}
In this sketch, if the character sent from the serial monitor window is 'a', then the LED on pin 13 of the
Arduino will be switched on. If any other character is sent, nothing will happen.
The if statement:
if (rx_byte == 'a')
will only evaluate to true if the character received from the serial monitor window and stored in the
variable rx_byte is equal to 'a'.

Switching the LED Off Again


The above sketch can be modified to add another if statement that can be used to switch the LED off
again.
The sketch below will switch the LED on if 'a' is sent to the Arduino and switch the LED off if 'b' is sent to
the Arduino (note that these are case sensitive, so 'A' and 'B' won't work).
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read(); //
if (rx_byte == 'a') {
digitalWrite(13, HIGH);
}
if (rx_byte == 'b') {
digitalWrite(13, LOW);
}
}
}
Now it the character 'b' is sent, the if statement testing for 'a' evaluates to false, but the if statement
testing for the character 'b' evaluates to true and the LED is switched off.
A more efficient way of dealing with switching the LED on and off is dealt with in the next part of the
course which covers the else and else if statements that are used with the if statement.
Part 10 of the Arduino Programming Course
Following on from part 9 of the Arduino programming course which covered the ifstatement, we now look
at the if-else construct.
This construct adds more decision making capability to the if statement.
Using if-else
When using an if statement, the code in the body of the if statement is run only when the ifstatement
evaluates to true. When it evaluates to false, program execution skips the code in the body of
the if statement and continues below the body of the if statement.
By adding an else statement, code in the body of the else statement will run only when its
corresponding if statement evaluates to false.
The following code shows the syntax of the if-else construct.
if (conditional expression) {
}
else {
}
The code below shows how the functioning of the if statement compares to the functioning of the if-
elseconstruct.
// "if" statement
if (conditional expression) {
// Code placed here only runs if conditional expression is true
}
// Whether the conditional expression evaluates to true or false,
// code placed here will run

// "if-else" construct
if (conditional expression) {
// Body of the "if" statement between { and }
// Works as a normal "if" statement, code placed here will only
// run if the conditional expression evaluates to true
}
else {
// Body of the "else" statement between { and }
// Code placed here will always run if the conditional expression
// from the "if" statement evaluates to false
}
// Code placed below the if-else construct will always run whether
// the conditional expression evaluated to true or false
When the conditional expression evaluates to true:
1. Code in the body of the if statement is run.
2. Code in the body of the else statement is not run.
When the conditional expression evaluates to false:
1. Code in the body of the if statement is not run.
2. Code in the body of the else statement is run.

Amazon.comif-else Example Sketch


The sketch below shows an example of using the if-else construct. The LED will switch on if the character
'a' is sent to the Arduino using the serial monitor window. If any other character except 'a' is sent, then
the if statement evaluates to false and the code in the else block is run which switches the LED off.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read();
if (rx_byte == 'a') {
// switch the LED on if the character 'a' is received
digitalWrite(13, HIGH);
}
else {
// switch the LED off if any character except 'a' is received
digitalWrite(13, LOW);
}
}
}
Notes on the if-else Sketch Example
Nested if-else Construct
The if-else construct in the above example is actually placed inside the body of another if statement. This
is called "nesting" and we say that the if-else is nested inside the first if statement.
To make this clearer, this is the if-else construct that is nested:
if (rx_byte == 'a') {
// switch the LED on if the character 'a' is received
digitalWrite(13, HIGH);
}
else {
// switch the LED off if any character except 'a' is received
digitalWrite(13, LOW);
}
The above code is nested inside this if statements body:
if (Serial.available() > 0) { // is a character available?
}
How the Sketch Works
The example sketch is based on the sketch from the previous part of this course. Instead of switching the
LED off when only 'b' is sent, the LED will switch off when any character except 'a' is sent.
The character 'a' will switch the LED on as in the previous sketch because the if conditional expression
evaluates to true when 'a' is received. Any other character received will cause the conditional expression
to evaluate to false. When the expression evaluates to false, the body of the if statement is not run, but
the body of the else statement is run instead which turns the LED off.
Part 11 of the Arduino Programming Course
The if-else-if construct allows further conditional expressions to be evaluated than the if-elseconstruct
covered previously.
What this means is that we can add even more decision making capability to our Arduino sketches. A
single variable can be checked to see if it contains any one of a number of different values and a decision
can be made depending on which value the variable contains.

Using the if-else-if Construct


The if-else-if construct is shown below.

if (conditional expression 1) {
}
else if (conditional expression 2) {
}
As can be seen, the if-else-if construct allows a second conditional expression to be evaluated after the
first if.
If the first conditional expression evaluates to true, then the code in the body of the if statement will be run
and the code in the body of the else-if statement will not be run.
Only if the first conditional expression evaluates to false, will the second conditional expression be
evaluated. If the second conditional expression evaluates to true, the the code in the block below
the else-if statement will run. If the second conditional expression evaluates to false, program execution
will continue below the closing brace of the body of the else-if statement.
if-else-if Example Sketch
The sketch below demonstrates the use of the if-else-if construct. If the character 'a' is sent from the serial
monitor window, then the LED will blink at a certain rate. If the character 'b' is sent, the LED will blink at a
faster rate.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

char rx_byte = 0;

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read();
}
if (rx_byte == 'a') {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
else if (rx_byte == 'b') {
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(200);
}
}
The first if statement gets a character from the serial port if one is available. The if-else-if construct follows
this (shown below).
if (rx_byte == 'a') {
digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(500);
}
else if (rx_byte == 'b') {
digitalWrite(13, HIGH);
delay(200);
digitalWrite(13, LOW);
delay(200);
}
Deciding the Rate at which to Blink the LED
This code simply checks which character the rx_byte variable holds. If this variable contains 'a', then the
code in the if block will run which will blink the LED with a 500ms delay. This switches the LED on for
500ms using the delay() function and then off for 500ms.
If the variable holds the value 'b', then the LED will be blinked at a faster rate by changing the on and off
times of the LED to 200ms.
Stopping the LED from Blinking
If any character besides 'a' or 'b' is sent, then the LED will stop flashing because neither of the conditional
expressions will evaluate to true.
When the Expression is Evaluated
Note that this code is in the main Arduino loop, so the conditional expression(s) will be evaluated each
time through the loop. If a character is received that causes a conditional expression to be true, then this
condition will be true each time through the loop until a new character is received. This is because the
character is stored in the variable and does not change until it is overwritten by a new character.

The if-else-if-else Construct


In the same way that we could add an else statement below an if statement, we can add
an elsestatement below the if-else-if construct as the sketch below shows.
This sketch works in the same way as the previous sketch, except that when any character except 'a' or
'b' is sent, the else block is run which flashes the LED even faster than the previous two blink rates.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

char rx_byte = 0;

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read();
}
if (rx_byte == 'a') {
// the character 'a' was received, blink the LED once per second
digitalWrite(13, HIGH); // switch the LED on
delay(500); // leave the LED on for 500ms
digitalWrite(13, LOW); // switch the LED off
delay(500); // leave the LED off for 500ms
}
else if (rx_byte == 'b') {
// the character 'b' was received, blink the LED every 400ms
digitalWrite(13, HIGH); // switch the LED on
delay(200); // leave the LED on for 200ms
digitalWrite(13, LOW); // switch the LED off
delay(200); // leave the LED off for 200ms
}
else {
// any character except 'a' or 'b' was received
digitalWrite(13, HIGH); // switch the LED on
delay(100); // leave the LED on for 100ms
digitalWrite(13, LOW); // switch the LED off
delay(100); // leave the LED off for 100ms
}
}
When the sketch starts running, the LED immediately blinks at the fastest rate by running the code in
the else block. This is because the variable rx_byte is initialized to 0 which of course is not 'a' or 'b'.
If you want the sketch to blink the LED at the slowest rate when the sketch starts running, then initialize
the variable to 'a' as shown here.
char rx_byte = 'a';
Evaluating More Conditional Expressions
Even more conditional expressions can be evaluated by adding more else if statements after the
first ifstatement as shown here.
if (conditional expression 1) {
}
else if (conditional expression 2) {
}
else if (conditional expression 3) {
}
else if (conditional expression 4) {
}
etc. ...
To perform a task only if none of the the conditional expressions evaluate to true, an else condition can
be added at the end as shown below.
if (conditional expression 1) {
}
else if (conditional expression 2) {
}
else if (conditional expression 3) {
}
else if (conditional expression 4) {
}
else {
}
Part 12 of the Arduino Programming Course
Logical operators can be used with if and if-elseto simplify and extend decision making.
The three logical operators are OR (||), AND (&&) and NOT (!) which are explained and demonstrated in
this part of the course.

The OR Logical Operator (||)


The OR logical operator is written in sketches as two vertical pipe symbols (||) found on the same key as
the backslash (\) on USA and other keyboards. Pressing Shift + \ (Shift and back slash keys) will type the
vertical pipe character.
The following sketch demonstrates the use of the OR logical operator to check for the upper and lower-
case versions of an alphabet character.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read();
if (rx_byte == 'a' || rx_byte == 'A') {
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
}
}
The sketch will switch the LED on the Arduino Uno board on if the lower-case character 'a' or the upper-
case character 'A' is sent from the serial monitor window. If any other character is sent, the LED is
switched off.

How the Logical OR Operator Works


The code below is taken from the above sketch and shows the logical OR operator.
if (rx_byte == 'a' || rx_byte == 'A') {
digitalWrite(13, HIGH);
}
The code in the body of the if statement will run if the variable rx_byte contains 'a' OR (||) if it contains 'A'.
The OR operator has been used to test for one or the other character (A OR a).
The code can be modified to switch the LED on if the character 'a' or the character 'b' or the character 'c'
is received, as this next code demonstrates.
if ((rx_byte == 'a') || (rx_byte == 'b') || (rx_byte == 'c')) {
digitalWrite(13, HIGH);
}
In the above code, each equal to relational operator comparison has been put in parentheses () to make
the code easier to read. This also avoids any misunderstanding about which operator is evaluated first
(does the == or the || get evaluated first?).
The == has a higher precedence than the || which means that == is evaluated first. Parentheses have the
highest precedence, so anything placed in parentheses will be evaluated first. In this case it is not
necessary to place the parentheses, but makes it easier to read.
The AND Logical Operator (&&)
The next sketch demonstrates the use of the logical AND operator. The sketch tests to see that a
sequence of two characters has been received before turning the LED on.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

char first_char = 0;

void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read(); // read the character
if ((first_char == 'c') && (rx_byte == 'd')) {
digitalWrite(13, HIGH);
}
else {
first_char = rx_byte; // save the character for next comparison
digitalWrite(13, LOW);
}
}
}
In this sketch, two characters must be sent in the right order to switch the LED on. First 'c' must be sent,
followed by 'd'.

How the Logical AND Operator Works


The AND operator from the above sketch is shown below.
if ((first_char == 'c') && (rx_byte == 'd')) {
digitalWrite(13, HIGH);
}
The LED will only switch on when the variable first_char contains 'c' AND the variable rx_byte contains
'd'.
The variable first_char is used to store the current character received so that the next time
the ifstatement is evaluated, we can see if it was followed by 'd' and if it contains 'c'.

The Logical NOT Operator (!)


The NOT operator can be used to check if a variable contains the value 0 – in other words it can be used
to check if a variable evaluates to false.
int x = 0;
if(!x) {
// if not x - if x evaluates to false, code here will run
}

// this code is another way of writing the above code


if (x == 0) {
}

NOT Operator Example


The following example shows the logical NOT operator being used in a sketch. Although this sketch is not
a very practical application of the NOT operator, it does demonstrate how it works.
In the sketch, every character sent to the Arduino from the Serial Monitor window will switch the LED on,
except the character 'a'.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

void loop() {
char rx_byte;

if (Serial.available() > 0) { // is a character available?


rx_byte = Serial.read(); // read the character
if (!(rx_byte == 'a')) {
digitalWrite(13, HIGH);
}
else {
digitalWrite(13, LOW);
}
}
}

The not operator inverts the logic in the second if statement as shown below.
if (!(rx_byte == 'a')) {
digitalWrite(13, HIGH);
}

If the variable rx_byte contains the character 'a', the expression in the if statement would then evaluate to
true, however the NOT operator changes the result to false so that when 'a' is received the LED is
switched off.
Similarly if the variable rx_byte contains any character except 'a', the expression would normally evaluate
to false, but the NOT operator inverts the false result to true.
The above code could more easily be written using the not equal to (!=) relational operator as follows.
if (rx_byte != 'a') {
digitalWrite(13, HIGH);
}

The logical NOT operator does have practical application in more complex sketches. Just remember that
if the result of a comparison ever needs to be inverted, the logical NOT operator can be used. It can be
used to force an if statement to evaluate to true when it would normally evaluate to false, thus executing
the code in the body of the if statement instead of having to have an empty if statement and the code run
in a corresponding else block.
Part 13 of the Arduino Programming Course
The switch statement is similar to using if with multiple else-if constructs. switch is used in conjunction
with break which will also be explained in this part of the course.
Using switch instead of multiple else-if constructs is easier to read and has more flexibility.
switch Statement Example
The following Arduino sketch shows the switchstatement being used in conjunction with
the break statement.
Load the sketch to the Arduino and then start the Serial Monitor window. Sending 1 from the serial
monitor window to the Arduino will switch the on-board LED on and sending 2 will switch the LED off.
Sending 3 will show the menu of options that the sketch operates on. Sending any other character will
bring up a default message showing that the option chosen is invalid.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT); // LED on pin 13 of UNO
}

char rx_byte = 0;

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read();

switch (rx_byte) {
case '1':
digitalWrite(13, HIGH);
Serial.println("LED is ON");
break;

case '2':
digitalWrite(13, LOW);
Serial.println("LED is OFF");
break;

case '3':
Serial.println("------- MENU -------");
Serial.println("1. Switch LED on.");
Serial.println("2. Switch LED off.");
Serial.println("3. This menu.");
Serial.println("--------------------");
break;

default:
Serial.println("Invalid option");
break;
} // end: switch (rx_byte)
} // end: if (Serial.available() > 0)
}
How the sketch works will be explained later on this page, but first we must look at the structure of
the switch statement and how the break statement works.

Amazon.comStructure of the switch Statement


The image below shows the structure of a switch statement.
Structure of an Arduino switch Statement
The switch statement has a variable ((switch_var in the above image or rx_byte in the example sketch)
which can be an integer (int) or character (char) variable.
The switch variable will be tested against the value in each case to see if they match. When a case is
found that matches, the statements below the case will be run until the break keyword is reached.
re This
will break the program flow out of the body of the switch statement and execution of the sketch will
continue below the closing brace of the switch statement.
If no matching case is found, then the code under the default keyword will be run until
unt its break statement
is found.

How the Example Sketch Works


In the example sketch, the switch statement is placed inside an if statement in the main loop.
The switchstatement
statement will then only run if a new character is received from the Serial Monitor windo
window.
When a character is received from the Serial Monitor window, the switch statement will check for a
matching case value. If the character '1' is received, then the LED is switched on and a message
displayed in the Serial Monitor window.
If '2' is received,
d, the LED is switched off. '3' displays a menu of the options available in the sketch.
If any character is sent that does not match the characters in any of the case statements, then the code in
the default part of the switch body is run which displays a default message.
The break Statement
The break statement is used in the example sketch to break out of the body of the switch statement.
break can also be used to break out of any loop such as a while or for loop. As an example, a certain
condition can be tested for in a loop using an if statement and if the statement evaluates to true,
the breakstatement
statement can be run to break out of the loop.
Part 14 of the Arduino Programming Course
The conditional operator is another decision making construct in Arduino programming.
The conditional operator consists of a condition, which can evaluate to true or false, and two expressions.
If the condition evaluates to true, the conditional expression becomes equal to the first expression. If the
condition evaluates to false, the expression becomes equal to the second expression.
The rest of this part of the Arduino programming course will explain and illustrate how the conditional
operator works.

Structure of the Conditional Operator


The conditional operator has the following structure:
condition ? first_expression : second_expression;

Where condition will evaluate to either true or false resulting in the entire expression becoming equal to
the first expression (if condition evaluates to true) or the second expression (if condition evaluates to
false).
As can be seen from the above code, the conditional expression consists of a question mark (?) and a
colon (:).
An example sketch follows to show how to use the conditional expression.

Amazon.Conditional Expression Example Sketch


The sketch below uses the conditional operator to determine which number is the bigger of two numbers.
int val1, val2, result;

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

// change the values of val1 and val2 to see what the


// conditional expression does
val1 = 2;
val2 = 5;
// if val1 is bigger than val2, return val1
// else if val1 is less than val2, return val2
result = (val1 > val2) ? val1 : val2;

// show result in serial monitor window


Serial.print("The bigger number is: ");
Serial.println(result);
}

void loop() {
}
Change the value of the variables val1 and val2 in the sketch, and the bigger of the two numbers will
always be displayed in the Serial Monitor window of the

How the Sketch Works


The condition (val1 > val2) is evaluated and will either evaluate to true or false.
The Condition Evaluates to False
If val1 is less than val2, the condition evaluates to false. The conditional expression now takes on the
value of the second expression – which is val2.
The variable result is then assigned the value of the expression which is val2 (5 in the sketch) and is the
bigger number of the two values val1 and val2.
The Condition Evaluates to True
If we change the value of val1 to 12 so that we have:
val1 = 12;
val2 = 5;

val1 is now bigger than val2 and the condition evaluates to true. The conditional expression takes on the
value of the first expression – which is val1.
The variable result is assigned the value of the expression which is val1. val1 is the bigger of the two
values (with a value of 12).
Part 15 of the Arduino Programming Course
In this part of the Arduino programming course, you will learn h
how
ow to write your own functions and use
them in your sketches. The structure and use of functions is fully explained.
Functions were briefly encountered in part 1 of this programming course where some basic facts about
functions where stated – 1) each function must have a unique name, 2) the function name is followed by
parentheses () 3) functions have a return type, e.g. void, 4) the body of a function is enclosed in opening
and closing braces {}.
We will start by examining the structure of a function and then see how to write functions.

The Structure of a Function


Before a function can be used in a sketch, it must be created. The following cod
code is an example of a
function that was created to print a dashed line in the Arduino IDE.
void DashedLine()
{
Serial.println("----------------
----------------");
}
The code above that creates the function is called the function definition. The image below shows the
components of a function.

Structure of a Simple Arduino Function

Function Name
When we create a function, it must be given a name. The naming convention for functions is the same as
for variables:
 The function name can be made up of alphanumeric characters (A to Z; a to z; 0 to 9) and the underscore
(_).
 The function name may not start with a number i.e. the numbers 0 to 9.
 A function name must not be used that is the same as a language keyword or existing function.
The function name ends with parentheses (().
). Nothing is passed to the example function above, so the
parentheses are empty. Passing values or parameters to functions will be explained later in this tutorial.

Return Type
A function must have a return type. The example function does not return anyth
anything, so has a return type
of void. Returning a value from a function will be explained in the next part of this course.
Function Body
The function body is made up of statements placed between braces {}. The statements make up the
functionality of the function
ion (what the function will do when it is called).
When a function is used, it is said to be "called". We will look at how to call a function next.

Calling a Function
To use the function that was created above, it must be called in a sketch as shown in the sketch below.
void setup() {
Serial.begin(9600);

DashedLine();
Serial.println("| Program Menu |");
DashedLine();
}

void loop() {
}

void DashedLine()
{
Serial.println("----------------
----------------");
}

In the sketch above, the DashedLine() function is created at the bottom of the file and then called twice at
the top of the file as shown in the image below.

Calling a Function in an Arduino Sketch

To call a function, use the function name followed by opening and closing parentheses. Finally terminate
the
he statement that calls the function with a semicolon.
Load the sketch to an Arduino and then open the terminal window. The sketch prints some text in a box
as shown below.
Output from the DashedLine() Function

The first time that the function is called, it prints the dashed line shown in the top of the image. Text is
then written to the serial monitor window by the statement below the function call. The function is then
called again to print the same dashed line that completes the box.

Amazon.comWhy Use Functions


The function used in the example above is very simple, so all the benefits of using functions will not be
seen immediately.
One advantage of using functions is that they avoid having to write the same code over and over again in
a sketch which saves time and memory. Every time that a function is called, we are just reusing code that
has been written once.
If a function needs to be modified, it only has to be done once and the modifications will take effect every
place in a sketch that the function is called. If a function was not used, each place that the statements are
found in a sketch to do a particular task would need to be located and modified.
Functions can be used to break a sketch up into pieces which make it more modular and easier to
understand. Functions can be reused in other sketches.

Passing a Value to a Function


In the sketch above, the length of the line that the function prints out is fixed in the function. If we change
the text that is in the box, it may not fit in the box properly. The function needs to be modified so that we
can tell it what size line it must draw.
The above function can be modified to pass a value to it that will tell it how many characters long to make
the line that it draws.
The modified sketch is shown below.
void setup() {
Serial.begin(9600);

// draw the menu box


DashedLine(24);
Serial.println("| Program Options Menu |");
DashedLine(24);
}

void loop() {
}

void DashedLine(int len)


{
int i;

// draw the line


for (i = 0; i < len; i++) {
Serial.print("-");
}
// move the cursor to the next line
Serial.println("");
}

The DashedLine() function in the above sketch is modified so that an integer value can be passed to it.
The line needs to be 24 characters long to fit the new menu text into it, so we pass it a value of 24.
DashedLine(24); // passing a value of 24 to the function
Of course the function has to be modified to handle the value that is being passed to it:
void DashedLine(int len)
{
int i;

// draw the line


for (i = 0; i < len; i++) {
Serial.print("-");
}
// move the cursor to the next line
Serial.println("");
}
The function needs to be able to accept an integer value that is passed to it. The variable type and the
name of the variable are inserted between the opening an closing parentheses after the function name.
void DashedLine(int len)
We can now use the len integer variable in the body of the DashedLine() function. The variable will
contain whatever value was passed to it when the function was called.
The body of the sketch uses the len variable in a for loop to print out the correct number of dashes that
make up the dashed line of the menu box.
The cursor is moved to the next line in the serial monitor by calling Serial.println(""); with an empty
string.
After the function has run the last statement in its body, it is said to "return". When a function returns,
program execution continues below the statement that called the function – i.e. the statement below the
function call is run next.
Part 16 of the Arduino Programming Course
In the previous part of this Arduino programming course, we looked at how to pass a value to a function.
Now we look at how to get a value back from a function.
Getting a value back from a function is called "returning" the value from the function. The return keyword
is used at the end of the function to get the value back. We must also say what type of value the function
is returning, e.g. int, float, etc.
The example sketch below uses a function to do a mathematical calculation and then return the result of
the calculation which can then be used in the main Arduino sketch.

Function that Returns a Value


void setup() {
float area;

Serial.begin(9600);
// calculate the area of a circle with radius of 9.2
area = CircleArea(9.2);
Serial.print("Area of circle is: ");
// print area to 4 decimal places
Serial.println(area, 4);
}

void loop() {
}

// calculate the area of a circle


float CircleArea(float radius)
{
float result;

result = 3.141592654 * radius * radius;

return result;
}

What the Sketch Does


The sketch calculates the the area of a circle from a radius value of the circle that is hard-coded into the
sketch – in the example sketch the value is set to 9.2, but you can set it to any value that you want. The
result of the calculation is then sent out of the serial port so that it can be seen in the Arduino IDE Serial
Monitor window.
The formula for calculating the area of a circle is:
A = π × r²
OR
A = π × r × r
Where:
A = area of the circle
π = PI = 3.141592654
r = radius of the circle

In other words, if we know the radius of the circle (radius is the distance from the centre of the circle to the
edge) we can calculate the area of the circle.
The unit that the radius is in can be any unit that is used to measure distance and the area will be squares
of the unit used, e.g. if the radius is in centimetres, the area will be in square centimetres, if the radius is
in feet, the result will be in square feet.
How the Sketch Works
The CircleArea() function must return a value, so is preceded by the type of value that it must return – in
this case float. A float value called radius is also passed to the function as explained in the previous part
of this course.
float CircleArea(float radius)
Inside the function body, the radius calculation is done and the result of the calculation is put into the
variable result which is a variable created in the function.
The function then returns the result using the return keyword at the bottom of the function.
return result;
The formula is translated into code for the Arduino as follows:
A = π × r × r
Becomes:
result = 3.141592654 * radius * radius;

In the part of the sketch that calls the CircleArea() function, the function basically becomes the value that
it returns and can be assigned to a variable.
The variable area is assigned the value that the CircleArea() function returns:
area = CircleArea(9.2);

After this, the result of the calculation, which is the area of the circle, is sent out the serial port to be
displayed in the Arduino IDE Serial Monitor window.

A Shorter Version of the Sketch


The sketch above can be written in a shorter way without using some of the intermediate variables as
shown below.
void setup() {
Serial.begin(9600);
Serial.print("Area of circle is: ");
// print area to 4 decimal places
Serial.println(CircleArea(9.2), 4);
}

void loop() {
}

// calculate the area of a circle


float CircleArea(float radius)
{
return (3.141592654 * radius * radius);
}

In this sketch, the CircleArea() function returns the result of the calculation on one line without first
assigning it to a variable.
return (3.141592654 * radius * radius);
This method of doing the calculation and returning the value is fine, although it may not be as easy to
read the code as the first example.
When the CircleArea() function is called in the sketch, it is passed to Serial.println() as if it were a
variable. This is possible because when a function returns a variable, it takes on the value of the variable.
The sketch therefore works the same way as the first sketch, although again, it is more difficult to read the
code.
Serial.println(CircleArea(9.2), 4);
The size of the binary output file (the file that gets loaded to the Arduino after compiling) from the Arduino
compiler is 4,040 bytes for both sketches in Arduino IDE version 1.0.6.
Part 17 of the Arduino Programming Course
Arrays are groups of the same kind of data that are placed consecutively in memory. For example, we
can have an array of integers (type int) which is two or more integer numbers occurring one after the
other.
The key here is that each element in an array is placed directly after the previous element which allows us
to access each element in turn using a loop.
An element in an array refers to each value in the array. If we have an array of integers, then each
individual integer is referred to as an element of the array. In an array of bytes, each element is a byte (of
the Arduino byte type).

Using Arrays
The sketch below shows the basic use of an array.
void setup() {
int my_array[5]; // an array with 5 integer elements
int i; // used as an index into the array

Serial.begin(9600);

my_array[0] = 23; // assign a value of 23 to the 1st element


my_array[1] = 1001; // assign a value of 1001 to the 2nd element, etc.
my_array[2] = 9;
my_array[3] = 1234;
my_array[4] = 987;

// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial.println(my_array[i]);
}
}

void loop() {
}

Defining the Array


In this sketch, an array of 5 elements is defined. This makes space in memory for 5 integers that are put
in the memory one after the other. The values that each element contains after the array is defined can
contain any random data – whatever happens to be in the memory at the time. It is also possible that the
compiler is set to make the values zero, but we can not rely on this.
Defining an array of 5 integers:
int my_array[5]; // an array with 5 integer elements
In this example the array is of type int, but could be a float, byte, etc.
The array has a name which is my_array in the example.
The array has a length [5] which means that space for 5 consecutive integers is made in memory.

Assigning Values to Elements in the Array


Each element is assigned an integer value by referencing it using square brackets [] with the number of
the element to access in the brackets.
my_array[0] = 23;
my_array[1] = 1001;
my_array[2] = 9;
my_array[3] = 1234;
my_array[4] = 987;
Note that the element numbering starts from zero [0] and not one [1], so the first element in the array is
element 0.
In the same way, the last element in the array is numbered one less than the size of the array. In the
example, the size of the array is 5, so the number of the last element is 4 – again this is because we are
numbering the elements starting with 0.

Accessing an Array in a Loop


A for loop is used to get the contents of each element in the array in turn and print the values to the Serial
Monitor window.
for (i = 0; i < 5; i++) {
Serial.println(my_array[i]);
}
The variable i is used in the for loop as an index into the array to access each element of the array.
In the loop, i is initialized to 0 and then incremented by one each time through the loop so that it counts
from 0 to 4. The loop is exited when i becomes 5.
The i variable is used in the array to get the value that the array element is holding starting with element 0
and ending with 4.
(my_array[i]);

In the above code snippet, when i is 0, the first element of the array is accessed and we can then get the
value that it contains which is 23 in the example sketch.

Amazon.com

Amazon.co.uk

More on Initializing Arrays


Instead of initializing each element in the array individually, the array can be defined and initialized in one
line as shown in this code.
This sketch does exactly the same as the previous sketch.
void setup() {
int my_array[5] = {23, 1001, 9, 1234, 987};
int i;

Serial.begin(9600);

// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial.println(my_array[i]);
}
}

void loop() {
}

The values to initialize each element with are placed between braces {} after the assignment operator (the
equals sign =). The first value between the braces will be assigned to the first element in the array
(element number 0), the second number between braces will be assigned to the second element in the
array (element number 1), etc.
The code that does the defining and initializing can also be written without the number of elements in the
array between the square brackets:
int my_array[] = {23, 1001, 9, 1234, 987};
In this case, the compiler will work out how many elements the array must have based on the number of
values that are used to initialize it.

Uses of Arrays
This part of the course shows that arrays can store data variables of the same type consecutively in
memory which allows easy access using a loop.
There are many uses for arrays in programming, for example, arrays can store data that is being logged,
such as temperatures. Strings, which are lines of text, are actually arrays as we will see in the next part of
this course.
Actual practical uses of arrays will be shown as the course progresses.
Part 18 of the Arduino Programming Course
Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE Serial
Monitor window.
Strings are also useful for storing user input – for example the characters that a user types on a keypad
connected to the Arduino.
There are two types of strings in Arduino programming:
1) Arrays of characters which are the same as the strings used in C programming
2) The Arduino String which lets us use a string object in a sketch
Strings, objects and how to use strings in Arduino sketches are fully explained in this part of the Arduino
programming course. The question of which type of sting to use in a sketch is answered at the end of this
article.

String Character Arrays


The first type of string that we will look at is the string that is a series of characters of type char. The
previous part of this course showed what an array is – a consecutive series of the same type of variable
stored in memory. A string is an array of char variables.
A string is a special array that has one extra element at the end of the string which always has the value
of 0 (zero). This is known as a "null terminated string".

String Character Array Example Sketch


This sketch will show how to make a string and print it to the serial monitor window.
void setup() {
char my_str[6]; // an array big enough for a 5 character string

Serial.begin(9600);

my_str[0] = 'H'; // the string consists of 5 characters


my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // 6th array element is a null terminator

Serial.println(my_str);
}

void loop() {
}

The sketch shows what a string is made up of – it consists of a character array with printable characters
and a 0 in the last element of the array to show that this is where the string ends.
The string can be printed out to the Arduino IDE Serial Monitor window by using Serial.println() and
passing it the name of the string.
This same sketch can be written more conveniently this way:
void setup() {
char my_str[] = "Hello";

Serial.begin(9600);

Serial.println(my_str);
}

void loop() {
}
In this sketch, the compiler calculates the size of the string array and also automatically null terminates
the string with a zero. An array that is six elements long and consists of five characters followed by a zero
is created exactly the same way as in the previous sketch.
Strings and Characters
Characters are written between single quotes like this:
'w'

Strings are written between double quotes like this:


"This is a string"

Manipulating String Arrays


We can alter a string array within a sketch as the following sketch shows.
void setup() {
char like[] = "I like coffee and cake"; // create a string

Serial.begin(9600);

// (1) print the string


Serial.println(like);

// (2) delete part of the string


like[13] = 0;
Serial.println(like);

// (3) substitute a word into the string


like[13] = ' '; // replace the null terminator with a space
like[18] = 't'; // insert the new word
like[19] = 'e';
like[20] = 'a';
like[21] = 0; // terminate the string
Serial.println(like);
}

void loop() {
}

Creating and Printing the String


In this sketch, a new string is created and then printed for display in the Serial Monitor window (1).
Shortening the String
The string is shortened by replacing the 14th character in the string with a null terminating zero (2). This is
element number 13 in the string array counting from 0.
When the string is printed out, all the characters are printed up to the new null terminating zero. The other
characters do not disappear – they still exist in memory and the string array is still the same size. The
only difference is that any function that works with strings will only see the string up to the first null
terminator.
Changing a Word in the String
Finally the sketch replaces the word "cake" with "tea" (3). It first has to replace the null terminator
at like[13] with a space so that the string is restored to how it was originally created.
New characters overwrite "cak" of the work "cake" with the word "tea". This is done by overwriting
individual characters. The 'e' of "cake" is replaced with a new null terminating character. The result is that
the string is actually terminated with two null characters – the original one at the end of the string and the
new one that replaces the 'e' in "cake". This makes no difference when the new string is printed out
because the function that prints the string stops printing string characters when it encounters the first null
terminator.
Functions to Manipulate String Arrays
The previous sketch manipulated the string in a very manual way by accessing individual characters in
the string. To make it easier to manipulate string arrays, you could write your own functions to do so, or
use some of the string functions from the C language library.
The next sketch uses some C string functions.
void setup() {
char str[] = "This is my string"; // create a string
char out_str[40]; // output from string functions placed here
int num; // general purpose integer

Serial.begin(9600);

// (1) print the string


Serial.println(str);

// (2) get the length of the string (excludes null terminator)


num = strlen(str);
Serial.print("String length is: ");
Serial.println(num);

// (3) get the length of the array (includes null terminator)


num = sizeof(str); // sizeof() is not a C string function
Serial.print("Size of the array: ");
Serial.println(num);

// (4) copy a string


strcpy(out_str, str);
Serial.println(out_str);

// (5) add a string to the end of a string (append)


strcat(out_str, " sketch.");
Serial.println(out_str);
num = strlen(out_str);
Serial.print("String length is: ");
Serial.println(num);
num = sizeof(out_str);
Serial.print("Size of the array out_str[]: ");
Serial.println(num);
}

void loop() {
}

The sketch works in the following way.


(1) Print the String
The newly created string is printed to the Serial Monitor window as done in previous sketches.
(2) Get the Length of the String
The strlen() function is used to get the length of the string. The length of the string is for the printable
characters only and does not include the null terminator.
The string contains 17 characters, so we see 17 printed in the Serial Monitor window.
(3) Get the Length of the Array
The operator sizeof() is used to get the length of the array that contains the string. The length includes
the null terminator, so the length is one more than the length of the string.
sizeof() looks like a function, but technically is an operator. It is not part of the C string library, but was
used in the sketch to show the difference between the size of the array and the size of the string (or string
length).
(4) Copy a String
The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies
the second string passed to it into the first string. A copy of the string now exists in the out_num[] array,
but only takes up 18 elements of the array, so we still have 22 free char elements in the array. These free
elements are found after the string in memory.
The string was copied to the array so that we would have some extra space in the array to use in the next
part of the sketch which is adding a string to the end of a string.
(5) Append a String to a String (Concatenate)
The sketch joins one string to another, which is known as concatenation. This is done using
the strcat()function. The strcat() function puts the second string passed to it onto the end of the first
string passed to it.
After concatenation, the length of the string is printed to show the new string length. The length of the
array is then printed to show that we have a 25 character long string in a 40 element long array.
Remember that the 25 character long string actually takes up 26 characters of the array because of the
null terminating zero.

Array Bounds
When working with strings and arrays, it is very important to work within the bounds of the string or array.
In the example sketch an array was created that was 40 characters long in order to allocate memory that
could be used to manipulate strings.
If the array was made too small and we tried to copy a string that is bigger than the array to it, the string
would be copied over the end of the array. The memory beyond the end of the array could contain other
important data used in the sketch which would then be overwritten by our string. If the memory beyond
the end of the string is overrun, it could crash the sketch or cause unexpected behaviour.

The Arduino String Object


The second type of string used in Arduino programming is the String object.

What is an Object?
An object is a construct that contains both data and functions. A String object can be created just like a
variable and assigned a value or string. The String object contains functions (which are called "methods"
in object oriented programming (OOP)) which operate on the string data contained in the String object.
The following sketch and explanation will make it clearer what an object is and how the String object is
used.
void setup() {
String my_str = "This is my string.";

Serial.begin(9600);

// (1) print the string


Serial.println(my_str);

// (2) change the string to upper-case


my_str.toUpperCase();
Serial.println(my_str);

// (3) overwrite the string


my_str = "My new string.";
Serial.println(my_str);

// (4) replace a word in the string


my_str.replace("string", "Arduino sketch");
Serial.println(my_str);

// (5) get the length of the string


Serial.print("String length is: ");
Serial.println(my_str.length());
}

void loop() {
}

A string object is created and assigned a value (or string) at the top of the sketch.
String my_str = "This is my string.";
This creates a String object with the name my_str and gives it a value of "This is my string.".
This can be compared to creating a variable and assigning a value to it such as an integer:
int my_var = 102;
(1) Printing the String
The string can be printed to the Serial Monitor window just like a character array string.
(2) Convert the String to Upper-case
The string object my_str that was created has a number of functions or methods that can operated on it.
These methods are invoked by using the objects name followed by the dot operator (.) and then the name
of the function to use.
my_str.toUpperCase();

The toUpperCase() function operates on the string contained in the my_str object which is of
type Stringand converts the string data (or text) that the object contains to upper-case characters.
A list of the functions that the String class contains can be found in the Arduino String reference.
Technically String is called a class and is used to create String objects.
(3) Overwrite a String
The assignment operator is used to assign a new string to the my_str object that replaces the old string.
my_str = "My new string.";
The assignment operator can not be used on character array strings, but works on String objects only.
(4) Replacing a Word in the String
The replace() function is used to replace the first string passed to it by the second string passed to
it. replace() is another function that is built into the String class and so is available to use on
the Stringobject my_str.
(5) Getting the Length of the String
Getting the length of the string is easily done by using length(). In the example sketch, the result returned
by length() is passed directly to Serial.println() without using an intermediate variable.

When to use a String Object or String Character Array


A String object is much easier to use than a string character array. The object has built-in functions that
can perform a number of operations on strings which are fully documented in the reference section on the
Arduino website.
The main disadvantage of using the String object is that it uses a lot of memory and can quickly use up
the Arduinos RAM memory which may cause the Arduino to hang, crash or produce unexpected
behaviour.
If a sketch on an Arduino is small and limits the use of objects, then there should be no problems.
Character array strings are more difficult to use and you may need to write your own functions to operate
on these types of strings. The advantage is that you have control of the size of the string arrays that you
make, so you can keep the arrays small to save memory.
You need to make sure that you do not write over the end of the array bounds with string arrays.
The String object does not have this problem and will take care of the string bounds for you, provided
that there is enough memory for it to operate on. The String object can try to write to memory that does
not exist when it runs out of memory, but will never write over the end of the string that it is operating on.

Where Strings are Used


This part of the Arduino programming course has looked at what strings are, how they look in memory
and some operations that can be done on strings.
Actual practical uses of strings will be covered in the next part of this course when we look at how to get
user input from the Serial Monitor window and save the input in a string.
Part 19 of the Arduino Programming Course
This part of the Arduino programming course shows how to get data into an Arduino sketch from the
serial port. Data can be sent to the Arduino from the Serial Monitor window in the Arduino IDE.
A user can enter data in the input field in the serial monitor window to send values and data to the
Arduino. Any serial program, or even a custom serial application can be used to send data to the Arduino
instead of using the Serial Monitor window.
Except for part 13 of this course, the Serial Monitor window has only been used for output purposes. It
was used to display the results or outputs from various example sketches in each part of the course. Let's
now look at how to handle both serial input and output.

Getting Serial Input


The following sketch shows how to get a single character from the Serial Monitor window and determine if
the character is a number or not.
void setup() {
Serial.begin(9600);
}

char rx_byte = 0;

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character

// check if a number was received


if ((rx_byte >= '0') && (rx_byte <= '9')) {
Serial.print("Number received: ");
Serial.println(rx_byte);
}
else {
Serial.println("Not a number.");
}
} // end: if (Serial.available() > 0)
}

How the Sketch Works


Checking for a Character
In the Arduino main loop (loop() function), an if statement is used to check if a character is available on
the serial port – i.e. if a character has been sent from the Serial Monitor window and received by the
Arduino.
This if statement is run as fast as it takes to run the if statement and get back to the top of the loop to run
it again.
if (Serial.available() > 0) { // is a character available?
}
Nothing in the body of the if statement is run until a character is received.
Getting a Character
When a character is received on the serial port, it is stored in a character variable (of type char)
called rx_byte.
rx_byte = Serial.read(); // get the character
A copy of the received character is now stored in the rx_byte variable and we can use the received
character in our sketch.
Check if the Received Character is a Number
The sketch tests whether the received character is a number or not by checking if the character is greater
than or equal to '0' and less than or equal to '9'.
if ((rx_byte >= '0') && (rx_byte <= '9')) {
}
We are actually checking for the character numbers '0' to '9' and not the actual integer numbers 0 to 9.
This is because the data received from the Serial Monitor window is in ASCII format.
From the table that shows the printable ASCII characters, we can see that the ASCII character '0' has the
integer value of 48 decimal and the ASCII character '9' has the decimal value of 57. In other words when
'0' is typed on the keyboard in the Serial Monitor window "send" field and the Send button is clicked, the
integer value of 48 is sent to the Arduino. In the sketch, we can refer to this character as '0' or 48.
The same if statement could be written using decimal integers as follows:
if ((rx_byte >= 48) && (rx_byte <= 57)) {
}
This code would do exactly the same as the version that checks for the characters.
If the character received is one of the number characters, the number character will be printed out.
The else statement takes care of any character that is not a number character.

Amazon.com

Getting String Input


The previous sketch was used to get and process a single character at a time. It will be more useful if we
could get a whole string at a time, then we could get a name as input, or a number that is more than one
digit long.

Finding the End of a String


A string is a series of characters. To be able to read a string from the serial port in the Arduino, we will
need to know when the string ends. One way to do this is to insert a newline character at the end of the
string. A newline character is a non-printable ASCII character that is called "line feed" in the ASCII control
code table.
The linefeed character has a value of 10 decimal but can be written as an escape code in an Arduino
sketch as: '\n'.
The following sketch is a modified version of the previous sketch. In addition to checking whether a
number or non-number is received, it also checks whether the newline character is received.
When the sketch is run and a character is sent from the Serial Monitor window, a setting at the bottom of
the Serial Monitor window must be changed so that a newline character is appended to the character sent
as shown in the image below the sketch.
void setup() {
Serial.begin(9600);
}

char rx_byte = 0;

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character

// check if a number was received


if ((rx_byte >= '0') && (rx_byte <= '9')) {
Serial.print("Number received: ");
Serial.println(rx_byte);
}
else if (rx_byte == '\n') {
Serial.println("Newline");
}
else {
Serial.println("Not a number.");
}
} // end: if (Serial.available() > 0)
}
Before running the sketch, make sure that the Arduino Serial Monitor window is set to "Newline" as shown
in this image.

Setting the Newline Character in the Serial Monitor Window

When "Newline" is set in the Serial Monitor window, whatever is typed into the "send" field of the Serial
Monitor window, will be followed by a newline character.
An else if is used to test if a newline character has been received as shown in this line of code.
else if (rx_byte == '\n') {
This code checks for the newline character which is represented by '\n' and prints "Newline" to the Serial
Monitor window if found.

Reading a String
The sketch below reads a string into the Arduino and uses the newline character to determine when the
string ends.
void setup() {
Serial.begin(9600);
Serial.println("Enter your name.");
}

char rx_byte = 0;
String rx_str = "";

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character

if (rx_byte != '\n') {
// a character of the string was received
rx_str += rx_byte;
}
else {
// end of string
Serial.print("Welcome ");
Serial.println(rx_str);
rx_str = ""; // clear the string for reuse
Serial.println("");
Serial.println("Enter your name.");
}
} // end: if (Serial.available() > 0)
}

Each individual character of the string is obtained in the same way as the previous sketches and stored in
the rx_byte variable.
If the character is not equal to the newline character, then it is added to the String object rx_str.
if (rx_byte != '\n') {
// a character of the string was received
rx_str += rx_byte;
}
The line of code rx_str += rx_byte; is the same as:
rx_str = rx_str + rx_byte;

It simply puts each character onto the end of the string to build up the string from received characters.
After the string has been assembled, the newline character will be received which will then trigger
the elsestatement and the received string is printed out to the Serial Monitor window as part of a welcome
message.

Getting a Number
When a number is received from the Serial Monitor window, it is a string of number characters and must
be converted into a number that can be stored in a number variable such as an integer or int.
The following sketch checks to see that the received characters are number characters and then converts
the number to an integer.
void setup() {
Serial.begin(9600);
Serial.println("Enter a number to multiply by 2.");
}

char rx_byte = 0;
String rx_str = "";
boolean not_number = false;
int result;

void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character

if ((rx_byte >= '0') && (rx_byte <= '9')) {


rx_str += rx_byte;
}
else if (rx_byte == '\n') {
// end of string
if (not_number) {
Serial.println("Not a number");
}
else {
// multiply the number by 2
result = rx_str.toInt() * 2;
// print the result
Serial.print(rx_str);
Serial.print(" x 2 = ");
Serial.print(result);
Serial.println("");
Serial.println("Enter a number to multiply by 2.");
}
not_number = false; // reset flag
rx_str = ""; // clear the string for reuse
}
else {
// non-number character received
not_number = true; // flag a non-number
}
} // end: if (Serial.available() > 0)
}

Building the String


A string is built up of received characters as done in the previous sketch. If any character received is not a
character number, the variable not_number is set to true to "flag" that a non-number character was
received.
Using a Boolean Flag
The not_number variable is of type boolean which can only have a value of true or false. In the sketch,
this variable is used as a flag which is checked later to see if any non-number characters were received.
After receiving the full string, which occurs when the newline character is received, the not_number flag
is checked and a message is displayed if any character received was not a number.
Processing the String
If all the received characters were numbers, the string is converted to an integer using rx_str.toInt(),
multiplied by 2 and the result stored in the result variable. The result of the calculation in then printed to
the Serial Monitor Window.
Sketch Limitations
There are some limitations with this sketch. We cannot get a result when a negative number is sent to the
Arduino because the minus sign will trigger the not_number flag. The size of the number that can be
multiplied is also limited by the size of a positive integer on the Arduino.

You might also like