Arduino Software 2
Arduino Software 2
Arduino Software 2
Arduino software.
In this section, you’ll learn how to set up the IDE, and create your first
Arduino program (also called an Arduino sketch).
I'll use the ZIP file option for Windows. If you decide to download an
installer instead, then you can follow the installation steps after
clicking the installation file.
After unzipping the file, you should see files like these:
To launch the Arduino IDE, click on the file that says “Arduino IDE”.
Before that, let’s have a look at some options you’ll find in the
Arduino IDE. At the top left corner of the IDE are five options — File,
Edit, Sketch, Tools, Help:
4
he “File” option lets you do different things like creating a new sketch
(we’ll talk about sketches in the next section), opening an existing
sketch, Arduino practice examples for beginners, keyboard shortcuts,
save options, and so on.
The “Edit” option gives you access to text formatting options like
copy, paste, cut, comment/uncomment code, font size options, text
search options, and so on.
You can use the “Sketch” option to verify and compile code, upload
code to Arduino boards, optimize code, and add libraries.
5
You can use the “Tools” option to manage libraries, format code,
access the serial monitor and plotter, select an Arduino board and
port to upload code to, choose a processor, and so on.
Next, let’s look at some other parts and functionalities in the IDE that
you’ll find useful. The image below, from the Arduino
documentation, highlights them perfectly:
Verify/Upload: You can use these options to compile and upload
6
code to Arduino boards. You’ll get error messages if the code doesn't
compile as expected.
Select Board & Port: You can use this option to select a port and port
number to upload your code too. The current version of the Arduino
IDE automatically detects both boards and ports.
Sketchbook: This gives you access to all the sketches created in your
computer. You can also access sketches saved on Arduino Cloud
(mostly used for creating IoT projects).
Boards Manager: The Arduino IDE comes with support for different
boards. As you progress through your journey, you’ll make use of
different boards and some of them may not be supported by the IDE.
The board manager tab lets you install and manage packages
required to use these boards.
Library Manager: You can use libraries to extend certain
functionalities in code. Through the library manager, you can install
numerous libraries that’ll help simplify the development process for
you.
Debugger: This is used for real time testing and debugging of Arduino
programs.
Search: You can use the search tool to find specific keywords in your
code.
Open Serial Monitor: You can use the serial monitor to communicate
with Arduino boards, debug and test code, visualize data from your
boards, interact with user input, and so on. We’ll look at the serial
monitor in depth in a different chapter.
Open Serial Plotter: The serial plotter is mostly used for real-time
visualization of numerical data.
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
8
digitalWrite(ledPin, LOW);
delay(1000);
}
If there are no errors in your code, these steps will help upload code
to your board. If you've uploaded the code above, you should have
the built-in LED (it is connected to pin 13 by design) on the Uno board
blinking.
int redLED = 6;
Here's an example:
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations
like addition, subtraction, division, multiplication, and so on. Here are
some arithmetic operators you should know:
Addition(+) Operator
The addition operator, denoted by the + symbol, adds two operands
together:
int a = 5;
int b = 10;
14
Serial.print(c);
// 15
Subtraction(-) Operator
Serial.print(c);
// 5
Multiplication (*) Operator
You can use the multiplication operator (*) to multiply two operands:
int a = 5;
int b = 10;
Serial.print(c);
// 50
Division(/) Operator
int a = 5;
int b = 10;
int c = b / a;
Serial.print(c);
// 2
Modulus (%) Operator
int a = 5;
int b = 10;
Serial.print(c);
// 0
Increment (++) Operator
int num = 5;
num++;
Serial.print(num);
// 6
Decrement (--) Operator
int num = 5;
num--;
Serial.print(num);
// 4
16
Assignment Operators
Assignment operators are mainly used to assign values to variables.
You can also use them to update the value of variables.
int age = 1;
In the code above, we created a variable called age, and then assigned
a value of 1 to it using the = operator.
But this isn't the only way to assign or update the value of variables
when using the = operator. You can also use compound assignment
operators.
Compound Assignment Operators
Serial.print(x)
// 10
In the code above, we created an x variable and assigned a value of 5
to it. But on the second line, you'd see that we combined the
arithmetic addition (+) operator and the = operator to assign a new
value to x:
x += 5;
The line of code above is the same as this:
x = x + 5;
17
int a = 10;
a -= 5; // Equivalent to a = a - 5 (a becomes 5)
int b = 10;
b *= 5; // Equivalent to b = b * 5 (b becomes 50)
int c = 10;
c /= 5; // Equivalent to c = c / 5 (c becomes 2)
int d = 10;
d %= 5; // Equivalent to d = d % 3 (d becomes 0)
Comparison Operators
You can use comparison operators to compare two values/operands.
Comparison operators return either true (1) or false (0) depending on
the relationship between operands.
Comparison operators can help you make decisions based on their
return values. You'll see them a lot when we start building projects.
This operator compares the values of two variables. If the values are
the same, it returns true. If the values are not the same, it returns false.
Here's an example:
int x = 10;
int y = 5;
Serial.print(x == y)
18
// returns 0
The return value of x == y in the code above is 0 (false) because the two
variables are not the same. Remember that the == operator returns 1
(true) only when both variables have the same value.
Not Equal (!=) Operator
The not equal operator checks whether two values have different
values. It's does the opposite of the == operator. That means it'll
return 1 (true) if both values are not of the same value and 0 (false) if
both values are the same.
Here's an example:
int x = 10;
int y = 5;
Serial.print(x != y)
// returns 1
Greater Than (>) Operator
The greater than (>) operator checks if the operand on the left is
greater than the operand on the right. If the left operand is greater, it
returns 1. If the left operand is smaller, it returns 0.
int x = 10;
int y = 5;
Serial.print(x > y)
// returns 1
Less Than (<) Operator
The less than (<) operator checks if the operand on the left is less
than the operand on the left. If the left operand is smaller, it returns
1. If the left operand is greater, it returns 0.
int x = 10;
int y = 5;
Serial.print(x < y)
19
// returns 0
Greater Than or Equal To (>=) Operator
Just like the name, the >= operator checks if the operand on the left is
either greater than or equal to the operand on the right. It returns 1
if the left operand is greater than or equal to the right operand, and 0
if it isn't.
"Or" implies that either of the conditions can be used. If the left
operand is not greater than the right operand but is equal to the right
operand, you'll still get a value of 1.
int x = 10;
int y = 5;
Serial.print (x >= y)
// returns 1
Less Than or Equal To (<=) Operator
The <= operator checks if the left operand is either less than or equal
to the right operand. If the left operand is less than or equal to the
right operand, it returns 1, and returns 0 if the left operand is neither
less than nor equal to the right operand.
int x = 10;
int y = 5;
Serial.print(x <= y)
// returns 0
Logical Operators
Logical operators are used in most programming languages to
evaluate and determine the relationship between variables.
Here are the three logical operators you should know for Arduino
programming:
20
The NOT (!) operator negates or reverses the value of its operand. If
the operand statement is true, it returns false, and returns false if the
operand is true.
Here's an example:
int x = 10;
if Statement
The if statement is used to execute code if a condition is true. Here's
what the syntax looks like:
if (condition) {
// code to be executed if condition is true
}
In the syntax above, condition denotes a specified logic. If the condition
is true then the code in the curly brackets will be executed. Here's an
example:
int x = 5;
if (x < 10) {
Serial.print("x is less than 10");
}
// x is less than 10
In the code above, we gave a condition— x < 10 — and a block of code
within curly brackets that prints "x is less than 10". The code in the
curly brackets will only run if the condition is true.
This is the same as saying "if x is less than 10 then print 'x is less than
10' to the serial monitor". Since x is less than 10, the condition
evaluates as true and we get the message printed out.
But what if the condition is false? The code in the curly brackets won't
run, so we'll need a different type of logic to handle situations like
that. We can do this using the else statement.
22
else Statement
The else statement is used to execute code if a condition is false.
int score = 20;
if (score > 50 ) {
Serial.print("You passed the exam!");
} else {
Serial.print("You have to rewrite the exam!");
}
if (score > 50 ) {
Serial.print("You passed the exam!");
} else if (score < 50) {
Serial.print("You have to rewrite the exam!");
} else {
Serial.print("No records for your exam score found!");
}
switch (expression) {
case 1:
// Code to be executed if expression equals case 1
break;
case 2:
// Code to be executed if expression equals case 2
break;
case 3:
// Code to be executed if expression equals case 3
break;
default:
// Code to be executed if expression doesn't match any case
break;
}
Let's break the syntax down:
The break keyword stops the switch statement's iteration once a match
for the expression has been found.
The code for the default keyword is executed if none of the cases
match the expression.
Here's an example:
int day = 2;
switch (day) {
case 1:
Serial.print("Monday");
break;
case 2:
Serial.print("Tuesday");
break;
case 3:
Serial.print("Wednesday");
break;
case 4:
Serial.print("Thursday");
break;
case 5:
Serial.print("Friday");
break;
case 6:
Serial.print("Saturday");
break;
case 7:
Serial.print("Sunday");
break;
default:
Serial.print("Number out of range");
}
// Tuesday
25
The code above prints "Tuesday" because the expression which has a
value of 2 matches case 2.
Loops in Arduino
You can use loops to execute code repeatedly until a certain
condition is met. You can also use loops to iterate over a collection of
data and execute code on all elements of the collection.
There are different type of loops you can use in Arduino like the for
loop, while loop, and do-while loop. Let's take a look at their syntax along
with some practical examples:
for loop
You can use the for loop to iterate through a collection or execute code
until a certain condition is met. It is commonly used when you know
the number of times the loop is supposed to run.
Here's the syntax:
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
In the loop above, we created an initial variable called 1 with a value
of 0.
The condition stated i < 11 which implies that the loop will continue to
run as long as i is less than 11.
Using the increment operator i++, we increased the value of i by 1
every time the loop ran.
Lastly, we printed the value of i at every iteration. In the serial
monitor, you'll notice the numbers from 0 to 10 printed out. This is
because after the number 10, i is no longer less than 11 (the
condition given), so the loop terminates.
while loop
The while loop works just like the for loop — it executes code as long
as the given condition is true. But its often used when the number of
times the loop is supposed to run is unknown.
Here's the syntax:
while (condition) {
// Code to be executed
}
In the syntax above, the code will continue to run until
the condition becomes false.
while (i < 11) {
Serial.println(i);
27
i++;
}
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
do-while Loop
The do-while loop is just like the while loop, but it executes its code
block first before checking the validity of the condition given. That is,
at the beginning of the loop, the code in curly brackets will run first
even if the condition is false. After that, it starts checking if the
condition is true or false, just like a normal loop.
In summary, the code for a do-while loop will run at least once,
irrespective of the condition given. Here's an example:
do {
// code block to be executed
}
while (condition);
Here's the code example:
int i = 0;
do {
Serial.println(i);
i++;
} while ( i < 11);
28
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10
Arrays in Arduino
You can use arrays in Arduino to store multiple variables of the same
data type in a single variable. Each element stored in an array can be
accessed using its index number.
Array Declaration
Declaring an array simply means to create one. You can do that in
Arduino using the syntax below:
dataType arrayName[arraySize]
In the syntax above:
dataType represents the data types that'll be stored in the array. For
instance, if the data type is int, then only integers can be stored in the
array.
arrayName denotes the name of the array.
arraySize denotes the number of elements that can be stored in the
array.
Here's an array declaration code example:
int ages[4];
29
In the code above, we created an array called ages. The array can only
store four elements with an int data type.
Array Initialization
To initialize an array means to assign values to the array. In the last
section, we created an array called ages. Now, let's assign some
elements to it:
int ages[4] = {2, 4, 6, 8};
You can see from the example above that there are only four
elements in the array — 2, 4, 6, 8. Assigning a fifth element would
throw an error because we specified that the array can only have for
integer elements: int ages[4];.
You can access the elements of the array using their index number.
Indexes start at zero (0) – so the first element has an index of 0, the
second element has an index of 1, the third element has an index of
2, and so on.
Serial.print(ages[0]);
// 2
As can be seen above, we accessed the first element using the array
name and the index of the element in square brackets: ages[0].
You can also assign and reassign values to a particular element using
its index:
ages[0] = 10;
Note that you can declare and initialize an array at the same time. I
only divided them into separate sections to help you understand
what each term means.
Functions in Arduino
30
Functions prevent you from having to reinvent the wheel. They also
help you break your code down into smaller, more readable and
manageable parts.
dataType functionName(optionalParameters) {
// body of the function
}
So from the syntax above, dataType is the data type the function
returns. It can be int, String, and so on. A function that has
no return statement uses the void type as its data type.
The functionName is the name given to the function. The name is used
to call the function to execute the logic defined in the body of the
function. You'd see words like "call", "fire", and "invoke" associated
with functions. They all mean the same thing — to execute the
function's logic.
optionalParameters are variables that you define when creating a
function. They enable functions to accept external data which can be
used within the function body. Function parameters are defined
along with their data types. You'll understand this when we look at
some examples.
The body of the function is where all the logic goes to. What the
function does when it is invoked is written in the body.
Now that we've seen the different parts of a function, let's create
some functions!
// function declaration
void printName(String userName) {
Serial.println("Hello " + userName);
}
void setup() {
Serial.begin(9600);
}
void loop() {
printName("Ihechikara"); // function call
delay(1000);
}
In the code above, we created a function called printName which
accepts a string parameter called userName. The function's task is to
print "Hello " along with whatever the parameter value is.
In the void loop(), we called the function and passed a parameter to
it: printName("Ihechikara"). In the serial monitor, you'll see "Hello
Ihechikara" printed.
To call a function, all you have to do is write the name of the function
with parenthesis: printName(). Remember to pass in parameters when
required: printName("Ihechikara").
Using a parameter that has the wrong data type will result in an
error. For instance, we defined a string parameter in our example.
33
int result = a + b;
return result;
}
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(addNums(2, 10)); // function call
delay(1000);
}
In the code above, we declared a function with the int type: int
addNums(int a, int b) {...}. This implies that the function is expected to
return an integer value.
The function's logic adds the value of the two parameters (a and b)
and returns their sum. We used the return statement to return the
sum of the parameters.
We can now say that the task of the addNums function is to return the
sum of two given parameters. This can be seen when we used the
function in the void loop():
Serial.println(addNums(2, 10));
We called the function with two parameters and got their sum
printed out in the serial monitor.
34
int result = a + b;
Serial.println(result);
return result;
void loop() {
// put your main code here, to run repeatedly:
}
pinMode() Function in Arduino
The pinMode() function is used to configure pins as input or output
pins. It can also be used to configure a resistor to act as either a pull-
up or pull-down resistor. You'll understand more about this function
in the Sensors and Actuators chapter.
Syntax
pinMode(pin, mode)
pin denotes the pin number on an Arduino board.
mode denotes the configuration of the pin which can be INPUT,
OUTPUT, or INPUT_PULLUP.
digitalRead() Function in Arduino
You can use the digitalRead() function to read the state of digital pins. It
returns either 0 (LOW) or 1 (HIGH).
36
Syntax
digitalRead(pin)
In the code above, pin denotes the pin number on an Arduino board.
digitalWrite() Function in Arduino
The digitalWrite() function assigns or writes values (either HIGH or LOW)
to digital pins.
Syntax
digitalWrite(pin, value)
pin denotes the pin number on an Arduino board.
value denotes the value to be assigned to pin. Can be HIGH or LOW.
analogRead() Function in Arduino
The analogRead() function reads values from analog pins and returns
values that fall within the range of 0 and 1023.
Syntax
analogRead(pin)
In the code above, pin denotes the pin number on an Arduino board.
analogWrite() Function in Arduino
This function writes or assigns an analog value to a pin.
Syntax
analogWrite(pin, value)
pin denotes the pin number on an Arduino board.
value denotes the value to be assigned to pin. Range from 0 to 255.
In this case, baud rate represents the rate or speed of data transfer in
serial communication.
Serial.begin(baudRate)
Serial.print() and Serial.println()
You can use the print() and println() functions to print data to the serial
monitor.
print(val)
println(val)
In the code above, val denotes the value to be printed.
delay() Function in Arduino
You can use the delay() function to pause the Arduino program for a
specified amount of time. Here's what the syntax looks like:
delay(ms)
In the code above, ms denotes the specified time in milliseconds.