Arduino
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).
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 }).
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.
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.
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.
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
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.
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.
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 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.
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;
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.
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.
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 = 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);
void loop() {
}
void loop() {
}
The output of the above sketch is shown here.
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);
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);
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.
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.
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
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.
Serial.begin(9600);
void loop() {
}
How the for Loop Works
The image below shows the parts of the for loop.
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
void loop() {
}
This sketch works exactly the same as the previous sketch and outputs the numbers 0 to 9.
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.
Serial.begin(9600);
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;
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.
void loop() {
char rx_byte;
void loop() {
char rx_byte;
// "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.
void loop() {
char rx_byte;
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.
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.
void loop() {
char rx_byte;
char first_char = 0;
void loop() {
char rx_byte;
void loop() {
char rx_byte;
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.
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.
void setup() {
Serial.begin(9600);
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
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.
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.
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.
void loop() {
}
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;
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() {
}
return result;
}
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.
void loop() {
}
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);
// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial.println(my_array[i]);
}
}
void loop() {
}
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
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.
Serial.begin(9600);
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'
Serial.begin(9600);
void loop() {
}
Serial.begin(9600);
void loop() {
}
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.
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);
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.
char rx_byte = 0;
void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character
Amazon.com
char rx_byte = 0;
void loop() {
if (Serial.available() > 0) { // is a character available?
rx_byte = Serial.read(); // get the character
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