Arduino Software 2

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

1

Arduino software.

The hardware part of Arduino comprises Arduino boards, input and


output devices (including digital and analog pins, and sensors and
actuators), shields, breadboards, jumper wires, and so on. These
components can be combined together to create dynamic and
interactive projects. The Arduino development and design process
comprises both hardware and software. So knowing how they work
together is important for building the right foundation for your
journey.

The software is made up of the development tools used to write,


debug, compile, and upload code to Arduino boards. Most 0f the
software tools can be found in the Arduino IDE (Integrated
Development Environment).

How to Install and Set Up the Arduino IDE


You can use the Arduino IDE to program Arduino boards. That is, you
write the code in the IDE, then upload it to the board.

In this section, you’ll learn how to set up the IDE, and create your first
Arduino program (also called an Arduino sketch).

You can download the latest version of the Arduino IDE on


the Arduino software download page. You can download the IDE for
different operating systems — Windows, MacOS, and Linux.
The installation process is similar for the operating systems listed
above. Here’s how to install it on a Windows machine:
2

Step #1 – Download the Arduino IDE


The first step is to download the IDE from the Arduino software
download page. You should see a section of the page similar to the
image below:

On the right side of the image above are different download


options for specific operating systems. Make sure you download the
option that suits your operating system.

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.

Step #2 – Unzip the Downloaded File


Go on and unzip the downloaded file. This gives you access to all the
resources needed to run the Arduino IDE.
3

After unzipping the file, you should see files like these:

Image showing the files you should see

To launch the Arduino IDE, click on the file that says “Arduino IDE”.

Step #3 – Overview of the Arduino IDE


Now that you’ve downloaded and installed the Arduino IDE, the next
part is to get familiar with the development environment. In the next
section, you’ll learn how to upload code to an Arduino Uno board
using the 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

Screenshot showing these options (File, Edit, Sketch, Tools, Help)

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.

The “Help” option provides resources for troubleshooting,


information on IDE updates, guides on “getting started”, 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.

What Is an Arduino Sketch?


We mentioned the term “sketch” a couple of times in the last
section, but what is it? A sketch is a program written with the
7

Arduino programming language. It’s another way of referring to a


code file written for Arduino projects.

The Arduino programming language is built upon the C/C++ language


so they both share similar syntax and structure. You may come across
resources that refer to Arduino code as “embedded C” or “embedded
C++”.

How to Upload Code to an Arduino Board


To upload code to an Arduino board, you'll need both hardware and
software. The hardware is the board which is the Uno board in our
case, and the software is the Arduino sketch in the IDE.

Here are the steps:

Step #1 – Connect the Arduino Board


Connect the Arduino board to your computer using the USB cable.
Without this step, you can't go further.

Step #2 – Create a Sketch


Now it's time to launch the IDE and write some code.

Here's a code example that makes an LED blink:

int ledPin = 13;

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
digitalWrite(ledPin, HIGH);
delay(1000);
8

digitalWrite(ledPin, LOW);
delay(1000);
}

Don't worry if you don't understand the code — we'll cover


everything as we go further.

Step #3 – Select the Board and Port


You can select the board to upload your code to from the IDE. Here's
an image showing what that looks like:
9

Step #4 – Verify the Code


You can use the verify button to compile the code and check for
errors. If errors exist, you'll get an error message to show you the
possible cause.

Image showing the verify button

Step #5 – Upload the Code


You can upload the code using the upload button (the button after
the verify button).
10

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.

Basics of Arduino Programming


Before we dive into creating our own sketches and tinkering, you
have to understand the logic that make these boards work as
expected. To do that, you’ll have to know how to code using the
Arduino programming language.

As discussed in the last chapter, the Arduino language is built upon


C/C++. You’ll begin this chapter by learning the basics of
programming. This will prepare you for every other chapter that
involves writing code.

I’ve created this chapter with beginners in mind. If you’ve never


written code before then this can serve as a starting point for you.
This doesn’t mean you’ll learn how to code in C or C++. You’ll be
learning how to write Arduino code which shares similar syntax with
those languages.

At the end of this chapter, you should be able to understand and


write Arduino code.

Variables and Data Types in Arduino


Variables and data types are used in most programming languages to
store and manipulate data. You can think of variables as containers or
storage units. Data types, like the name implies, are the type of data
stored in variables.
11

In Arduino programming, you must specify the data type of a variable


before using it. That is:

dataType variableName = variableValue


There are different types of data types in Arduino, and we’ll discuss
each one along with code examples.

int Data Type in Arduino


The int data type is used to store integer values. The Uno board has a
16-bit integer capacity so it can store values that fall within the range
of -32,768 to 32,767.

int redLED = 6;

In the code above, we created an integer variable called redLED with a


value of 6.
The int data type can also store negative integers:
int redLED = -6;
long Data Type in Arduino
The long data type is similar to int but has a wider range of integer
values. It has a 32-bit integer limit which falls within the range of -
2,147,483,648 to 2,147,483,647.
long largeNumber = 6000;
float Data Type in Arduino
The float data type can be used to store numbers with decimals. Float
variables can store values up to 3.4028235E+38 and values as low as -
3.4028235E+38.
float num = 10.5;
Although the float data type is mainly used for decimal numbers, it
can also accept whole numbers (integers without decimals). But it'll
always return a float value. So if you store 10 in a float, it'll return
10.00.
12

String Data Type in Arduino


You can use the String data type to store and manipulate text. You'll
work with strings occasionally to display information in the form of
text when building projects.
Here's a code example:

String greeting = "Hello World!";


The value of strings are nested within double quotation marks as can
be seen in the code above.

Note that when declaring a string, the "S" should always be in


uppercase.

char Data Type in Arduino


The char data type stores single characters.

Here's an example:

char alphabet = 'A';


This is different from the String data type that can store multiple
characters.
There are two main differences between char and String:
 char uses single quotes ('A') while string uses double quotes
("Arduino").
 char stores single characters while string stores multiple characters.
char can also accept integer values equivalent to the ASCII value of
letters:
char charValue = 65;
In the code above, we initialized a char variable with the value of 65.
When printed to the serial monitor (we'll talk about the serial
monitor in Chapter 6: How to use the Serial Monitor in Arduino), A
will be returned.
A is returned because 65 has an ASCII character of A.
13

bool and boolean Data Types in Arduino


You can use both bool and boolean to store/denote boolean values of
either true or false.
bool roomIsCold = false;
Boolean values are mostly used with logical and comparison
operators, and conditional statements (you'll learn about these later
in this chapter) to manipulate and control different outcomes in an
Arduino program.

byte Data Type in Arduino


The byte data type has an 8-bit unsigned integer limit that ranges
from 0 to 255. Unsigned means that it can't store negative values.
byte sensorValue = 200;
The byte data type isn't the only data type that can be unsigned. You
can also use the unsigned int, unsigned long, and unsigned char data types
which all have their respective positive integer ranges.
Operators in Arduino
Operators are symbols or characters that can be used to perform
certain operations on operands. An operand is simply any value(s) an
operator acts on.

There are different categories of operators in Arduino like:

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

// we use addition operator to add a and b below


int c = a + b;

Serial.print(c);
// 15
Subtraction(-) Operator

The subtraction operator subtracts the value of one operand from


another operand. It is denoted by the - symbol:
int a = 5;
int b = 10;

// we use subtraction operator to subtract b from a below


int c = b - a;

Serial.print(c);
// 5
Multiplication (*) Operator

You can use the multiplication operator (*) to multiply two operands:
int a = 5;
int b = 10;

// we use multiplication operator to multiply a by b below


int c = a * b;

Serial.print(c);
// 50
Division(/) Operator

The division operator divides one operand by another:

int a = 5;
int b = 10;

// we use division operator to divide b by a below


15

int c = b / a;

Serial.print(c);
// 2
Modulus (%) Operator

The modulus operator returns the remainder of a division between


two operands:

int a = 5;
int b = 10;

// we use division operator to divide b by a below


int c = b % a;

Serial.print(c);
// 0
Increment (++) Operator

The increment operator increases the value of a variable by 1:

int num = 5;
num++;

Serial.print(num);
// 6
Decrement (--) Operator

The decrement operator decreases the value of a variable by 1:

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.

The assignment (=) operator is used for assigning and updating


variables. The = operator should not be confused for "equal to" —
they aren't the same. We'll talk about the equal to (==) operator in
the Comparison Operators section.
Here's an example that shows how to use the assignment operator:

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

Compound assignment operators let you combine arithmetic


operators and the = operator. This method provides a shorter way of
writing code. Here is an example:
int x = 5;
x += 5;

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

So compound operators combine two operators and let you do the


same thing in a shorter way. There's nothing wrong with either
method.

Here are other compound operator examples:

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.

Here are the comparison operators you'll come across occasionally:


Equal To (==) Operator

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

Logical AND (&&) Operator


The logical AND (&&) operator returns 1 if both statements are true.
int x = 10;

Serial.print((x > 5) && (x > 3));


// returns 1
The expression above — (x > 5) && (x > 3) — returns 1 because both
statements are true. That is, x > 3 and x > 3. If either or both of those
statements were false, then we'd have a return value of 0.
Logical OR (||) Operator

The logical OR (||) operator returns 1 if one of both statements is


true.
int x = 10;

Serial.print((x > 5) && (x > 15));


// returns 1
The code above returns 1 although one of the statements is false.
This is because the || operator returns 1 if either or both statements
are true.
Logical NOT (!) Operator

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;

Serial.print(!(x > 5));


// returns 0
The code above returns 0, but why? x > 5 is true so the expected result
is 1.
We got 0 because the ! operator reversed the return value of the
operand from 0 to 1.
21

Conditional Statements in Arduino


You can use conditional statements to make decisions or execute
code based on specific conditions. You can combine conditional
statements and logic (like operators in the last section) to control
how code is executed.

Let's take a look at some conditional statements and how to use


them:

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!");
}

// You have to rewrite the exam


In the code above, the condition given is false. So the code for
the else statement will be executed because the score variable is not
greater than 50.
Remember: the code for the else statement only runs when the
condition is false. If the condition is true then the code for
the if statement will be executed.
else if Statement
You can use the else if statement to define multiple conditions to be
checked. Here's the syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2){
// code to be executed if condition2 is true
} else {
// code to be executed if condition1 and condition2 are false
}
In the syntax above, there are two conditions (you can create more
than two conditions). If condition1 is true, then code in the curly bracket
for condition1 will be executed.
If condition1 is false, then condition2 will be evaluated. If condition2 is true,
its block of code will be executed.
If both condition1 and condition2 are false, the else statement's code will
be executed.
int score = 80;
23

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!");
}

// You passed the exam!


switch-case Statement
In the last section, we saw how to create multiple conditions
using else if statements. Your code might become hard to read if you
have many conditions. We can clean it up and make the code more
readable using switch statements.
Here's what the syntax looks like:

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 expression is compared to the value of each case.


 When a case matches the expression, the code for that case is executed.
24

 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:

for (initialization; condition; increment/decrement) {


// code to be executed
}
There are three important keywords in the syntax above:

 initialization denotes an initial variable (usually an integer) which


specifies the starting point of the loop.
 condition is used to control the number of times the loop is expected
to run for. The loop stops when the condition is false.
 increment/decrement increases/decreases the value of the initial
variable after every iteration.
Here's an example to help you understand the keywords:

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


Serial.println(i);
}
26

// 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.

int ages[4] = {2, 4, 6, 8};

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

In the last section, we discussed some built-in functions in Arduino


that can be used to carry out a variety of tasks related to Arduino
hardware and software components. All we did was write the
function name and pass in parameters where necessary and we got
the desired outcome.

For instance, the digitalWrite() function writes values to digital pins


using two parameters (the pin number and the value to be sent to
the pin). Under the hood, some code logic handles that operation.
Let's assume that the logic required to send values to digital pins was
up to a hundred lines of code. Without functions, you'll have to write
those hundred lines every time you wanted to send values to digital
pins.

Functions prevent you from having to reinvent the wheel. They also
help you break your code down into smaller, more readable and
manageable parts.

Just like how built-in functions can be reused to perform a particular


task repeatedly, you can also create your own functions for specific
functionalities, and that's exactly what you'll learn in this chapter.

How to Declare Functions in Arduino


There are four main parts of a function in Arduino:

 The type of data the function returns.


 The name of the function.
 The function parameter(s) which is optional.
 The body of the function.
Here's what that looks like:
31

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!

How to Declare a Function with the void Type


In the last chapter, we discussed the void Setup() and void
loop() functions. They are two built-in functions that you'll use in every
Arduino sketch. These functions are defined using the void keyword
because they return nothing
Here's what the syntax looks like for functions that use the void type:
void functionName(optionalParameters) {
// code logic
}
32

In the syntax above, functionName denotes the name of the function.


We can use that name to call the function in order to execute the
code defined in the function.
optionalParameters are used to pass external data to the function while
the code logic that runs when the function is called is written
between the curly brackets.
Here's an example:

// 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

Using an integer will raise an error because the function expects a


string.

How to Declare a Function with a Return Data Type


In this section, I'll use the int data type to show you how functions
declared without the void type are used. The logic here is the same
with other functions that use the return statement.
// function declaration
int addNums(int a, int b) {

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

What You Should Know About the return Statement


In the last two sections, we saw how to use functions in two different
ways — functions that use the return statement and functions that
don't use it.
But what if you used the return statement in a void function? Would
that break the code? The answer is no. I'll explain why.
The main use of the return keyword is to return a value from the
function, and then terminate the function. Consider the example
below:
int addNums(int a, int b) {

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

// This part will be ignored


Serial.println("Hello World");
}
The function above takes in two parameters — a and b — and returns
their sum. You'll notice that we printed "Hello World" after
the return statement. The part of the code that comes after
the return statement will not be executed because the function
terminates/stops its operation once it sees a return statement.
So you should always remember that anything that comes after
the return statement will be ignored.
You can use the return statement in void functions but it is a
convention not to. We simply use the void keyword to define
functions that have no use for the return statement.
Commonly Used Built-in Functions in Arduino Sketch
In this section, we’ll discuss some of the commonly used built-in
functions you’ll come across when writing or reading Arduino code.
We'll make use of them in most of the upcoming sections.
35

We'll begin with the two main parts of an Arduino sketch —


the setup() and loop() functions.
setup() and loop() Functions in Arduino
You can use the setup() function to configure analog and digital pins,
initialize variables, and do other setup functionalities.
The setup() function is executed once — when the board is powered
on or reset.
The loop() function runs continuously. This part of the sketch is where
you write all the code logic. You can use the loop() function to give the
Arduino board instructions on different components and sensors.
void setup() {
// put your setup code here, to run once:

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.

Serial Functions in Arduino


Serial communication enables an Arduino board to communicate
with the computer and other devices using the built-in serial monitor.
Here are some of the commonly used functions:
Serial.begin()
The Serial.begin() function initializes serial communication. It is the first
function you use when working with the serial monitor. The function
takes in a baud rate as its parameter.
37

In this case, baud rate represents the rate or speed of data transfer in
serial communication.

Here's the syntax:

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy