0% found this document useful (0 votes)
11 views30 pages

Module 2 Programming For The Arduino

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views30 pages

Module 2 Programming For The Arduino

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module 2

PROGRAMMING FOR THE


ARDUINO

Learning Outcomes
At the end of the topic, students are expected to:
• know how to install and familiarize the Arduino IDE software;
• know and understand the programming language used in Arduino IDE; and
• learn how to code C Language in Arduino IDE and understating Sketch.
The Arduino functions as an embedded system, carefully designed with the
essential hardware components needed for optimal performance. However, this
efficiency doesn't imply weakness; unnecessary components, like a PCI bus that remains
unused, would needlessly occupy space, consume energy, and escalate the device's
overall cost. Arduinos, known for their lightweight and cost-effectiveness, excel as
embedded systems. Similar to all embedded systems, the programming process takes
place on a host computer, not directly on the Arduino itself.
Programming an embedded system, and indeed any type of system, involves the
skill of crafting human-readable text that can be translated into binary code,
comprehensible to a processor. This task necessitates specific tools. The text authored by
humans is referred to as source code, often presented in a textual format that a basic
text editor can handle. Many developers opt for an Integrated Development Environment
(IDE), an enhanced text editor equipped with developer-centric add-ons. These additions

1
encompass features such as text auto-completion and debugging, and they often provide
tools to manage diverse source files containing the source code. While some projects
may involve only a single file, extensive undertakings can encompass numerous files,
potentially numbering in the hundreds or thousands. Once the source code is written, a
compiler is employed to convert it into one or more binary files. These binary files are
subsequently uploaded onto the Arduino and executed by the microcontroller.
Arduino has curated a comprehensive set of tools, enabling you to dive directly
into your projects. Contrasting this with other embedded systems, where you might have
to make choices about an IDE, install a compiler, and sometimes even a flasher, which
can consume valuable time during the setup process. This is not the scenario with
Arduino; it offers an all-inclusive package that streamlines the process, encompassing
everything from crafting your programs to flashing the final binary file.
An Arduino program is referred to as a "sketch." The term "sketch" can
encompass various meanings, such as a concise literary composition or a brief musical
creation. Whichever interpretation you favor, an Arduino sketch resonates as an artistic
endeavor. You, as the artist, gather and harmonize components to fashion your
masterpiece. Jeremy Blum, an engineer from Google X and the author of "Exploring
Arduino" (Wiley, 2013), aptly remarked, "I believe that creative engineering is
indistinguishable from fine artwork."
Think of the Arduino as your canvas, embarking on a journey to craft something
remarkable through the fusion of sketches and electronics. Your imagination is the sole
boundary to your creative exploration.
Installing Your Environment
The initial step entails installing the Arduino IDE, which is a comprehensive
software application coded in Java. Java is compatible with various operating systems,
and the IDE can be accessed on Windows, Mac OS X, and Linux platforms. You can
acquire the Arduino IDE without any cost by visiting the official Arduino website at
[Link]
On this webpage, you will likely encounter multiple choices. The most recent
stable version is consistently presented first. Subsequently, any accessible beta versions

2
will be listed. Beta versions are experimental iterations that might lack the refinement of
a finalized version but introduce additional functionalities. The decision to use a beta
version rests with you. In some cases, beta versions might support a wider range of
hardware, leaving you with little choice if you're using the latest Arduino boards.
The website also provides details about nightly builds and specialized builds for
specific hardware. Nightly builds are installers generated nightly, containing the latest
updates but occasionally may have some bugs. Specific builds are tailored for particular
boards. As of the time of writing, there is an IDE available for the Intel Galileo, an
Arduino-compatible board developed and produced by Intel, which employs a distinct
compiler.
Downloading the Software
Let's dive into the task at hand! Your first step is to acquire the software by
locating and downloading the most up-to-date version. Take a look at Figure 2-1 to get an
idea of how the Arduino website appears on my development computer.

Figure 2-1: The Arduino download page

3
For Windows users, there's a choice between utilizing an installer or an archive.
Opting for the installer involves downloading it, double-clicking the downloaded file, and
following the provided instructions. If you need more detailed guidance on installation,
you can refer to the Arduino website's installation guide at:
[Link]
On the other hand, Mac OS X and Linux users need to obtain an archive. Simply
extract the contents of the archive using your usual tool and then double-click the
Arduino icon found within the newly formed directory. Everything necessary is contained
within this folder.
If you're operating on a system not mentioned here, or if you're intrigued by the
source code, there's also an option to acquire a source code bundle. This would allow
you to compile the source code independently.
Certain Linux distributions may include the Arduino IDE directly, while others
might necessitate external repositories. For specific information, you can explore your
distribution's forums or consult Arduino's Playground website, a community-edited wiki,
accessible at: [Link]
Running the Software
After successfully downloading and installing the software, proceed to launch the
application. If the process has been carried out correctly, you should be greeted with a
window resembling the depiction in Figure 2-2.

4
Figure 2-2: Default sketch
Welcome to the Arduino IDE, the platform where your sketches come to life. Your
creative canvas resides within the main window – the sketch editor – where your code
takes shape. Below, you'll find the status window, delivering valuable updates on
compilation, uploads, or any lurking code errors. Nestled in the lower right corner of the
interface, you'll discover the device information panel. Here, the device you're working
with and its connected serial port are illuminated.
Behold the sketch editor, a realm beyond mere text editing. Text springs to life
with color and formatting, reflecting the essence of your code. Greyed-out comments,
vibrant data types – a visual symphony that makes reading and writing source code a
seamless endeavor.
Fast-forward to my knowledge cutoff in September 2021, and launching the
Arduino IDE becomes a breeze. Following the installation steps detailed in the previous
response equips your computer with this invaluable tool. Once armed with the Arduino
IDE, a simple sequence awaits to set it in motion:
Windows:
• Open the "Start" menu and search for "Arduino IDE."
• Click on the Arduino IDE icon to launch the application.
macOS:
• Open the "Applications" folder.

5
• Locate the Arduino IDE application.
• Double-click on the Arduino IDE icon to launch the application.
Linux:
• Open the "Applications" menu and navigate to the "Programming" or "Development"
category.
• Look for the Arduino IDE icon and click on it to start the application.
Upon opening the Arduino IDE, you'll be greeted by the primary development
environment. Within this space, a text editor awaits your Arduino sketches (programs),
accompanied by an array of menus and toolbars. These elements facilitate seamless
interaction with both the software and your interconnected Arduino board.
Here are some of the main components of the Arduino IDE:
Toolbar: The toolbar contains buttons for common actions like verifying (compiling) your
code and uploading it to the Arduino board.
Sketch Area: This is the text editor area where you write your Arduino code.
Status Bar: The status bar displays information about the current status of your sketch,
such as the selected board and serial port.
Serial Monitor: To open the serial monitor, click on "Tools" in the menu and select "Serial
Monitor." The serial monitor allows you to communicate with your Arduino board via the
serial port, which is useful for debugging and sending/receiving data.
Embark on your journey of crafting Arduino sketches by initiating new projects,
accessing pre-existing ones, coding your masterpiece, and effortlessly uploading it to
your linked Arduino board through the "Upload" button. Your creative exploration is
further enriched by an array of example sketches thoughtfully included within the
Arduino IDE. Delve into the realm of libraries and functions that facilitate seamless
interaction with an array of sensors, actuators, and assorted components.
Keep in mind, should any obstacles arise or inquiries emerge regarding your
utilization of the Arduino IDE, the official Arduino website and its vibrant community
forums stand as invaluable troves of knowledge. These resources provide comprehensive
documentation, insightful tutorials, and dedicated support to ensure your journey
remains smooth and your queries are promptly addressed.
Choosing Your Own IDE

6
While the Arduino IDE offers a robust platform, certain individuals might prefer
utilizing their personal IDE due to personal inclination or familiarity with a different
setting. The Arduino community has dedicated substantial efforts towards adapting the
tools for alternative software, and a comprehensive compilation of these options is
accessible on the Arduino Playground.
In addition to the Arduino IDE, a plethora of alternative environments are
available, including but not limited to Eclipse, CodeBlocks, Kdevelop, and the command
line. While this book primarily centers around the Arduino IDE, it's worthwhile to explore
these alternative IDEs. For further insights, you can refer to the link:
[Link]
First Program
Let's take the plunge! Arduinos come preloaded with a sketch named Blink,
serving as the default. This sketch orchestrates the pulsating rhythm of the on-board LED,
linked to pin 13, a fixture on the majority of Arduino boards. With a swift connection of a
USB cable between your computer and Arduino, a mere handful of seconds shall pass
before the LED initiates its twinkling dance – a reassuring sign of successful execution.
Arduinos embody a practical approach to accomplishment, and what better way to
underscore their simplicity than by running your inaugural program? Your initial sketch
shall resemble the example depicted in Listing 2-1:
Listing 2-1: Your first sketch
/*
Blink
Turns on an LED on for one second, then off for one
second, repeat
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the
level)

7
delay(200); // wait for 0.2 seconds
digitalWrite(led, LOW); // turn the LED off by making the
LOW
delay(200); // wait for 0.2 seconds
}
If the source code appears confusing at the moment, don't worry – a detailed
explanation will follow shortly. Experienced C developers might have a few queries, and
those will also be addressed later on.
The preceding code snippet represents a complete program. You can either input
it manually or directly utilize the Arduino IDE. This code snippet serves as an illustrative
example within the Arduino IDE. To access it, navigate to File ➪ Examples ➪ [Link] ➪
Blink. Upon doing so, a new window will appear, displaying the code. This sketch contains
comments and text sections where users can outline their intentions, indicated by // at
the line's commencement. Take a quick overview and attempt to comprehend the
program's functionality.
Once you feel prepared, it's time to upload your initial program! Uploading
involves transferring the binary code to the Arduino board. Ensure your Arduino board is
connected to your development computer via USB. For this instance, opt for an Arduino
Uno or Arduino Mega. This code is compatible with all Arduino models, so feel free to use
the one you possess. To upload the program, a series of straightforward steps must be
taken. Initially, inform the IDE about the connected board. Proceed to the menu; Tools ➪
Board, and pick your board type. A variety of board options are available. Choose the
entry corresponding to your specific board. In this demonstration, I'm using an Arduino
Mega Uno, as depicted in Figure 2-3.

8
Figure 2-3: Arduino IDE with the Arduino Mega 2560 selected
Subsequently, it is essential for the IDE to be informed about the computer-to-
board connection. Through the Tools ➪ Serial Port menu, you have the option to
designate the appropriate linkage. If you are utilizing a Windows computer, the board will
be recognized as a COM port. In the case of a Mac, the Arduino connection will initiate
with "/dev/[Link]." In my instance, I am employing a Linux system as my
development machine, and here the Arduino is affixed to /dev/ttyACM0. It's worth noting
that certain systems could display a variety of serial ports. Figure 2-4 provides a visual
representation of my port selection process.

9
Figure 2-4: Arduino IDE with the Arduino Uno serial port selected
That concludes the configuration process. This setup is a one-time requirement;
the Arduino IDE retains your preferences and stores them for future use. Adjustments
will be necessary if you switch boards or connect the board to a different USB port.
Moving forward, you have the option to validate the source code, if desired.
During the verification phase, the source code is effectively compiled, with the compiler
issuing warnings if any issues arise. In case of an error, the IDE displays a message at the
bottom of the screen, indicating the line number and the underlying cause of the
problem. For the present example, the compiler should not raise any complaints and will
successfully compile your application.
To initiate compilation, you can either click on the Verify button (depicted as a
check mark) located in the upper left corner of the IDE or navigate to the Sketch ➪
Verify/Compile menu. Alternatively, you can use the keyboard shortcut: Ctrl+R.

10
Lastly, there remains one final step: you must transfer the program onto your
Arduino board. Simply click the Upload button situated adjacent to the Verify button, or
access the File ➪ Upload menu option. Again, a keyboard shortcut is available: Ctrl+U, as
shown in Figure 2-5. Prior to uploading, the source code is re-verified as part of the
upload process.

Figure 2-5: Successful upload


The Arduino IDE currently seeks to establish a connection with the Arduino board
in order to transfer the program into the flash memory of the microcontroller. You
should anticipate a message appearing at the bottom, indicating "Done Uploading." At
this point, direct your attention to the Arduino board. Adjacent to the USB connector,
there will be a small LED that is in the process of blinking. This is the same LED that was
used as a verification during the initial stages of this chapter. However, this time, it
should be blinking at a rate of two to three times per second. You have successfully
achieved your first Arduino program upload, and I congratulate you for that!
Now, let's delve into the significance of having the program written into flash
memory. Similar to a computer program, it has been stored in the nonvolatile memory,

11
resulting in it being executed every time the Arduino is powered on. You can verify this
right now by disconnecting your Arduino from the USB port, waiting for a brief interval,
and then reconnecting it. This action will power the Arduino through the USB port, and
after a short pause, the LED will commence its flashing pattern, indicating that your
program is actively running.
However, it's important to note that the Arduino's execution of your program
involves more than just running it. Arduinos encompass a component referred to as a
bootloader, which is a small program executed each time the device initiates. This aspect
exemplifies one of the strengths of the Arduino system. The bootloader is consistently
accessible, allowing the programmer to reflash a program when needed. Even if an
unintentional program crash occurs, the possibility of reflashing the Arduino remains
viable, as long as the bootloader remains intact.
Should you require additional program space, the option to remove the
bootloader and position your own application at the onset of the processor's instruction
sequence is available. This approach carries the benefit of liberating the space previously
occupied by the bootloader, which can then be employed for your custom application.
It's important to acknowledge that the bootloader is relatively small, with a size of
around 2 kilobytes. Should you decide to eliminate the bootloader, reprogramming your
Arduino will still be possible; however, specialized equipment will be necessary to achieve
this.
Understanding Your First Sketch
With your sketch functioning effectively and the outcomes observed, it is now
opportune to delve deeper into the source code. This will be presented incrementally,
taking you through each step. The initial segment provides intriguing insights:
/*
Blink
Turns on an LED on for one second, then off for one second
repeatedly
This example code is in the public domain.
*/
Any content enclosed between the markers /* and */ is recognized as a
comment, constituting a segment of the source code that the compiler disregards. Any
content contained within these boundaries will be overlooked, making it an ideal space

12
to include human-readable text describing the program's actions or purposes. It's
customary to initiate a source code file with a comment that elucidates the function of
the application. By examining these concise lines, you can already gain insight into the
program's intended functionality.
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
Once again, this clarifies the forthcoming process through the utilization of
comments. Much like the /* and */ markers, when the compiler encounters the //
marker, it disregards any content beyond that marker, but only for the specific line in
question. On the initial line, the compiler encounters a comment marker and dismisses
the accompanying text. It then endeavors to interpret the second line but once more
encounters a comment, leading to its dismissal. Upon reaching the third line, there's an
absence of a comment, rendering it an authentic line of code.
The line commences with the keyword "int," signifying "integer." This marks the
declaration of a variable, signaling the compiler to allocate memory space for a named
container capable of altering its contents. As the variable is defined as an integer, it has
the capacity to store whole numbers within the range of -32,768 to 32,767. The variable
is denoted as "led," and the compiler assigns the value 13 to it. Finally, the line concludes
with a semicolon. In the realm of C programming, a semicolon denotes the conclusion of
an instruction.
Now for the next part:
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}
The first line is a comment. It explains what the next portion of the code will do.
Moving forward, the subsequent line presents an intriguing aspect. The term
"void" designates an empty data type. The second word, "setup," serves as the
declaration for a function. Given the presence of parentheses and curly brackets, it's
evident that this isn't a variable, but rather a function. Functions are segments of code
that can be invoked within a program, eliminating the need to replicate identical code
multiple times. Instead, you can compose the code just once and have the program

13
invoke this function as necessary. This approach also aids in segregating code for distinct
requirements.
Within the parentheses, you would enumerate any parameters pertinent to the
function – these are variables that can be passed to the function. Since setup() lacks any
content within its parentheses, no parameters are involved. Consequently, the function
doesn't require any data to execute. Moreover, due to its "void" declaration, the function
won't yield any data upon execution. Once invoked, the function fulfills its task and
concludes without returning any data. However, the question remains: What precisely
does this function entail?
Everything enclosed within the curly brackets constitutes part of the function; in
this instance, it's a solitary line of code. Upon invoking the setup function, it executes a
single instruction, pinMode(). This directive isn't preceded by a data type, indicating that
it isn't a variable declaration, nor is it a function declaration. Because of its presence
within parentheses, it functions as a bona fide function, and unlike "setup," it
necessitates two parameters: "led" and "OUTPUT." While a comprehensive list of
standard functions will be provided in Chapter 4, for now, consider pinMode() as an
illustration. This function communicates to the microcontroller the intended purpose of a
specific pin. Prior to utilizing a pin, the microcontroller must comprehend its designated
usage; in this scenario, the pin is designated for output. As such, the microcontroller can
manipulate the output of a pin to be either HIGH or LOW, without attempting to
ascertain the pin's status. The particular pin, referred to as "led," was previously defined
in the code and corresponds to pin number 13.
Now for the final section of code.
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH voltage
level)
delay(200); // wait for a second
digitalWrite(led, LOW); // turn the LED off, LOWvoltage
delay(200); // wait for a second
}
Once more, the code initiates with a comment, providing an overview of the
upcoming segment's functionality. The ensuing code segment encompasses the

14
declaration of a function known as 'loop()', which operates independently without
requiring any input parameters.
Within the 'loop()' function, there is an occurrence of the 'digitalWrite()' function.
As inferred from its name, this function undertakes writing actions in a digital format to a
pin. It establishes the pin's state as either a logical 1 (HIGH) or a logical 0 (LOW). Upon
the initial invocation of this function within the current sketch, it designates the pin as a
logical 1.
Subsequently, the code employs the 'delay()' function with a parameter of 1000.
This function instructs the microcontroller to pause for a specified duration, measured in
milliseconds, before proceeding to the next instruction. In this context, it prompts the
microcontroller to pause for 1 second before progressing. In essence, the program
activates a pin and then pauses for 1 second. Analogously, the subsequent part of the
code executes a 'digitalWrite()' operation, this time configuring the pin to a logical 0
(LOW), followed by another 1-second pause.
For those acquainted with C programming, a distinction might be observed –
Arduino code lacks a 'main()' function. In conventional C programming, 'main()' serves as
the entry point, invoked at program initiation. However, this paradigm does not apply to
embedded systems, where the Arduino framework mandates the presence of 'setup()'
and 'loop()' functions. These functions are obligatory components of any sketch, even
though they can remain empty, although this is seldom the case.
The 'setup()' function is invoked at the commencement of a sketch and serves to
initialize variables, pin modes, and other components pertinent to the sketch. Adhering
to best practices, segregating initialization code from operational code enhances clarity
and augments program robustness. Though it is feasible to configure a pin immediately
prior to executing an action, it is advisable to ensure comprehensive setup before
initiating the program. By inspecting the 'setup()' function, you can promptly verify pin
configurations, obviating the need to sift through extensive lines of operational code. In
the example provided, 'setup()' featured a command to modify the pin's status,
designating it as an output.
As its name implies, the 'loop()' function perpetually iterates, persisting as long as
power is sustained by the Arduino. In the given instance, 'loop()' sets a pin's output to

15
HIGH, pauses for 1 second, switches the pin's output to LOW, and then pauses for
another second. Subsequently, the function recommences. This underscores the
rationale behind refraining from configuring within the 'loop()' function; the same code
sequence reiterates continuously. Introducing configuration within the 'loop()' could lead
to variable overwrites and potential slowdowns due to pin configuration alterations.
These two essential functions – 'setup()' and 'loop()' – constitute fundamental
components of any sketch, with the flexibility to include additional custom functions as
needed.
Programming Basics
As mentioned earlier, programming involves crafting code that is easily readable
by humans yet can be translated into a format comprehensible to computers. The
challenge lies in the fact that, contrary to popular belief, computers lack any inherent
intelligence. They rely on explicit instructions and must be provided with precise
guidance. Consequently, source code must adhere to a specific and meticulous structure.
Variables and Data Types
In your sketches, the majority of the time, you will find the need to store data and
carry out various calculations. Whether it involves tallying button presses, recording
analog pin voltages, or conducting intricate mathematical computations using vectors,
data manipulation and storage are essential. This data gets stored within a variable,
which represents a memory location that can be altered as needed. By defining a
variable, you prompt the compiler to allocate a specific memory size based on the data
type.
Diverse forms of data exist, and it's crucial to initially specify the precise kind of
data you intend to store to the compiler. If you designate a variable to hold integers, it
cannot be used to store floating-point values or even text strings. The various data types
are presented in Table 2-1.
Table 2-1: Different Data Types
Data Type Contents
void No data type
boolean True or false

16
One character, stored as an ASCII number (‘A’,
char
‘B’, ‘C’...)
unsigned char Decimal numbers, from 0 to 255
byte Decimal numbers, from 0 to 255
Decimal numbers, from –32,768 to 32,767
int (Arduino Due, from –2,147,483,648 to
2,147,483,647)
Decimal numbers, from 0 to 65,535
unsigned int
(Arduino Due, from 0 to 4,294,967,295)
word Decimal numbers, from 0 to 65,535
Decimal numbers, from –2,147,483,648 to
long
2,147,483,647
unsigned long Decimal numbers, from 0 to 4,294,967,295
short Decimal numbers, –32,768 to 32,767
Floating point numbers, from –3.4028235 x 1038
float
3.4028235 x 1038
double Floating point numbers
string An array of char
String Advanced arrays of char
array A collection of variable

Notably, the Arduino Due distinguishes itself as a relatively recent device


employing a 32-bit microcontroller, setting it apart from the 8-bit AVR present in other
Arduino boards. Consequently, certain data types exhibit differences compared to those
on other Arduino models. Specifically, integers are represented using 32 bits, allowing
them to accommodate significantly larger numerical values. Furthermore, the double
data type occupies 8 bytes on the Arduino Due, while it occupies 4 bytes on other
Arduino variants. As a result, a double variable exhibits greater precision when used on
an Arduino Due.
When embarking upon the declaration of a variable, it is imperative to first specify
the desired data type, followed by the variable name. Optionally, you have the option to
assign a value using the equals sign. The declaration is then concluded with a semicolon.
The ensuing examples demonstrate valid declarations:

17
long data;
char usertext;
int pin_number = 42;
You have the flexibility to choose nearly any variable name you prefer, but it's
advisable to avoid overly ambiguous names. In the preceding example, the name
"usertext" provides a hint that the variable stores textual information from an external
source. On the other hand, "pin_number" conveys that this variable pertains to the
identification of a pin used for input or output actions. However, the term "data" is
excessively broad; its definition could encompass text, numbers, or other types of
information. As your sketch progresses, you might eventually find yourself questioning
the contents of this variable, potentially leading to confusion and even unintended
consequences if you mistake it for another variable.
Data types have an impact not only on variables but also on functions. This
concept is further elaborated upon in the subsequent "Functions" section.
Control Structures
The strength of microprocessors and microcontrollers lies in their capacity to
handle and manipulate data. They adhere to instructions and possess the capability to
perform conditional operations based on data. For instance, consider whether a variable
holds a value equal to or exceeding 42. If the condition is met, a specific segment of code
is executed; otherwise, an alternative portion is executed. These directives are structured
as conditional statements such as "if," "for," and "while."
if Statement
The if statement is the simplest of branching statements and is used to detect if
an expression is equal to a result. It is used as follows:
if (expression)
{
statement;
}
Multiple instructions can be used inside an if statement, by placing multiple
instructions inside curly brackets:
if (expression)
{
statement;
another_statement;
}

18
An "if ... else" statement provides the ability to carry out two distinct sets of
instructions. You can envision this as performing a certain action if a condition is met, and
alternatively, executing a different action if the condition is not fulfilled.
if (expression)
{
do_this;
}
else
{
do_that;
}
It is also possible to mix several ifs using else:
if (expression)
{
do_this;
}
else if (expression)
{
do_that;
}
The expression is employed to verify the accuracy of a statement. For instance,
you can examine whether a variable holds an identical value, a value that's lower, or a
value that's higher than a specified reference. Additionally, you can identify various other
value types. For instance, you can ascertain whether a boolean value holds "true" or
"false."
int myval = 42;
if (myval == 42){
run_this; // myval equals 42; this function will be
executed
}else{
run_that; //This one will not
}
if (myval < 50){
run_another_function; //This will be run, since 42 is less
than 50
}
Take note that in this instance, the variable "myval" is assigned the value 42 using
a lone equal sign (=), while the value is assessed using a double equals sign (==). Within
the realm of C programming, a solitary equal sign consistently assigns a value to a
variable (or attempts to do so). On the other hand, two equal signs signify an evaluation.
When constructing "if" structures, exercise caution, as a lone equal sign can inadvertently
overwrite a variable's value, potentially yielding unexpected outcomes.

19
switch Case
The if statement offers simplicity and effectiveness when used in scenarios
requiring the evaluation of a variable against one or perhaps two values. However, what
if the requirement involves checking against multiple variables? Consider the scenario of
a robot tasked with gauging the proximity of an obstacle. In such a case, an if statement
could be employed; for instance, if the obstacle's distance measures less than 3 inches,
the motors should halt. Yet, certain situations are more intricate. Envision an Arduino-
connected keypad adorned with stickers outlining user instructions. When button one is
pressed, the lights are activated; button two prompts the blinds to open, and button
three triggers music playback, and so forth. The utilization of if statements in this context
could quickly become overwhelming and compromise readability.
if (button == 1){
turn_on_lights();
}
if (button == 2){
if (blinds_up == false){
raise_blinds();
blinds_up = true;
}
}
if (button == 3)

A more refined approach to express this concept is by utilizing the switch/case
statement. Similar to the if statement, the switch/case mechanism directs the program's
progression by enabling distinct segments to be executed based on a specific condition.
The switch statement evaluates a variable's value and triggers varying case statements
corresponding to that value.
switch(button)
{
case 1:
turn_on_lights();
break;
case 2:
if (blinds_up == false)
{
raise_blinds();
blinds_up = true;
}
break;
case 3:

20
Take note of the break directive, usually placed at the conclusion of each case,
instructing the compiler to halt the execution of instructions. Absent the break
statement, the Arduino would persist in executing case instructions, even when an
alternative case is appropriate. Interestingly, this characteristic can be leveraged
strategically. Envision a scenario where pressing buttons 4, 6, and 8 yields the same
outcome. In such a scenario, you can employ the following approach:
switch(button)
{
case 4:
case 6:
case 8:
//code to be run
break;
}
while Loop
The while loop stands as the fundamental looping structure in C. It iterates
through a designated set of code while a specified condition remains met. As the
condition holds true, the while loop persistently executes the identical code, reassessing
the condition's validity upon each loop's conclusion.
while (button == false)
{
button = check_status(pin4);
}
In this instance, the function "check_status" operates continuously until it yields a
true outcome. Upon achieving this, the "button" variable transitions to a true state,
leading to the termination of the while loop. This conclusion could manifest swiftly within
mere milliseconds, or alternatively, the system might endure an indefinite waiting period.
for Loop
When there arises a need for a specific segment of code to iterate a precise
number of instances, the for loop proves indispensable. It bears semblance to the while
loop but exhibits a distinct syntax. The for loop effectively monitors and manages the
count of its iterations.
for (expression1; expression2; expression3)
{
instructions;
instructions;
}

21
While this might appear intricate, there's no need for concern; the concept is
straightforward. It encompasses three expressions:
■ expression1 is the initializer; it will initialize a variable.
■ expression2 is the conditional expression; as long as this condition is true, the
loop keeps on executing.
■ expression3 is the modifier; when a loop is completed, this action is performed.
For example:
for (int i = 0; i < 10; i++)
{
myfunc(i);
}
In this illustration, a variable named "i" is established. It initiates at zero, and with
each invocation of the "myfunc" function, "i" is incremented by one. Ultimately, when "i"
reaches a value of 10, the loop concludes, preventing any further execution of "myfunc."
This approach spares you from the need to manually list each command individually, as
depicted here:
myfunc(0);
myfunc(1);

myfunc(8);
myfunc(9);
Frequently, the name "i" finds application as a transient variable within "for()"
loops, serving as an abbreviation for "index."
Functions
A function encompasses a segment of code that can be invoked, optionally with
parameters, and can yield data as a result. When faced with an extensive roster of
repetitive statements within code, or when you find yourself needing to call a segment of
code multiple times, creating a function can prove advantageous.
In the context of the main program, while it is in operation, it initiates a function
call named "addTwo()" with two arguments: 12 and 30. This function is executed,
producing data as output. Following this, the program resumes its prior point of
execution.
Every function necessitates a data type, even if it doesn't yield any data upon
completion. If data isn't intended to be returned, the "void" data type must be employed.
The function's content is enclosed within curly braces. In the case of the aforementioned

22
"addTwo()" function, it returns an "int" data type, a designation evident from its initial
declaration.
Functions in Arduino are blocks of code that perform specific tasks and can be
reused throughout your program. They allow you to break down complex tasks into
smaller, more manageable pieces of code, improving readability, reusability, and
maintainability of your Arduino sketches.

Figure 2-6: Anatomy of a C Function


Here's a brief overview of how functions work in Arduino:
Function Declaration: To declare a function, you specify its return type (if any),
the function name, and any parameters it accepts. For example:
int add(int a, int b) {
return a + b;
}
The next example where an entire sketch is defined. It would then look like this:
void setup(){
[Link](9600);
}

void loop() {
int i = 2;
int j = 3;
int k;

k = myMultiplyFunction(i, j); // k now contains 6


[Link](k);
delay(500);
}

int myMultiplyFunction(int x, int y){


int result;
result = x * y;

23
return result;
}
Another example This will read a sensor five times with analogRead() and
calculate the average of five readings. It then scales the data to 8 bits (0-255), and inverts
it, returning the inverted result. The function implementation is listed below:
int ReadSens_and_Condition(){
int i;
int sval = 0;

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


sval = sval + analogRead(0); // sensor on analog pin 0
}

sval = sval / 5; // average


sval = sval / 4; // scale to 8 bits (0 - 255)
sval = 255 - sval; // invert output
return sval;
}
Function Call: To use a function, you call it by its name and pass any required
arguments. For example:
int result = add(5, 3); // Calls the 'add' function with
arguments 5 and 3
In the second example a "call" to the simple multiply function, we pass it
parameters of the datatype that it is expecting:
void loop(){
int i = 2;
int j = 3;
int k;

k = myMultiplyFunction(i, j); // k now contains 6


}
In the third example the call of our function will be implemented by simply
assigning a variable to it.
int sens;

sens = ReadSens_and_Condition();
Return Statement: Functions can return values using the return statement. The
return type should match the type specified in the function declaration. If a function
doesn't return a value, you can use void as the return type.
void printHello() {
[Link]("Hello, world!");
}

24
Library Functions: The Arduino environment comes with a standard library that
provides a variety of functions for common tasks. For instance, digitalRead(),
digitalWrite(), analogRead(), and analogWrite() are functions used to interact with digital
and analog pins. Similarly, there are functions to control timing, communication, and
other aspects of your Arduino board.
Creating Your Own Functions: You can create your own functions to encapsulate
specific tasks. This can make your code more modular and easier to manage. For
instance:
void blinkLED(int pin, int times) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH);
delay(500);
digitalWrite(pin, LOW);
delay(500);
}
}
Function Scope: Functions have their own scope, which means variables declared
inside a function are only accessible within that function. If you need to use a variable in
multiple functions, you might need to declare it as a global variable.
Function Overloading: Arduino supports function overloading, which means you
can have multiple functions with the same name but different parameter lists. The
appropriate function is called based on the arguments you provide.

Segmenting code into functions allows a programmer to create modular pieces of


code that perform a defined task and then return to the area of code from which the
function was "called". The typical case for creating a function is when one needs to
perform the same action multiple times in a program. They allow you to divide your code
into logical sections and promote the reuse of code for different tasks.
For programmers accustomed to using BASIC, functions in Arduino provide (and
extend) the utility of using subroutines (GOSUB in BASIC).
Standardizing code fragments into functions has several advantages:
• Functions help the programmer stay organized. Often this helps to
conceptualize the program.

25
• Functions codify one action in one place so that the function only has to be
thought out and debugged once.
• This also reduces chances for errors in modification, if the code needs to be
changed.
Functions make the whole sketch smaller and more compact because sections of
code are reused many times. They make it easier to reuse code in other programs by
making it more modular, and as a nice side effect, using functions also often makes the
code more readable. There are two required functions in an Arduino sketch, setup() and
loop(). Other functions must be created outside the brackets of those two functions.
Libraries
The Arduino programming environment is equipped with a standard library that
integrates functions into every sketch. However, due to Arduino's embedded system
nature, this standard library focuses on fundamental components. It inherently handles
core mathematical operations and simplifies pin configuration for digital or analog
input/output purposes. Yet, more advanced capabilities like writing data to an SD card,
establishing WiFi connections, or utilizing a TFT screen are not part of the core
functionality of standard Arduino boards. Although these specialized features can be
utilized when present, they require a custom library to be added to the sketch.
Neglecting this would result in the incorporation of additional functionality that could
potentially consume valuable memory space on a resource-limited device, which would
be counterproductive.
By introducing a library to your sketch, you expand its capabilities and gain access
to new functions as a programmer. For instance, upon importing the EEPROM library,
you gain the ability to interact with the internal EEPROM using two additional functions:
read() and write(). Similar to other programming platforms, the Arduino environment can
be extended through the integration of libraries. These libraries provide supplementary
functionality for use within sketches, such as working with hardware or manipulating
data. To incorporate a library into a sketch, simply choose it from the "Sketch" menu and
then select "Import Library."

26
While the IDE comes preloaded with a variety of libraries, you also have the
option to download or create your own. For detailed instructions on library installation,
refer to the provided guidelines.
Communication (1317)
Data Processing (357)
Data Storage (161)
Device Control (1054)
Display (515)
Other (505)
Sensors (1235)
Signal Input/Output (468)
Timing (231)
Uncategorized (227)
Official Arduino Libraries
Robotics
Libraries for controlling servo and stepper motors.
• Servo - for controlling servo motors.
• Stepper - for controlling stepper motors.
Communication
Libraries for using the SPI, I2C and UART protocols.
• SPI - for communicating with devices using the Serial Peripheral Interface (SPI)
Bus.
• Wire - Two Wire Interface (TWI/I2C) for sending and receiving data over a net
of devices or sensors.
• SoftwareSerial - for serial communication on any digital pins.
Connectivity
Libraries to access radio modules on different IoT boards (Wi-Fi, Bluetooth®, LoRa®, GSM,
NB-IoT, Sigfox).
• ArduinoIoTCloud - This library allows to connect to the Arduino IoT Cloud
service.

27
• ArduinoBLE - library to use the Bluetooth® Low Energy on a selection of
boards.
• Ethernet - for connecting to the Internet via Ethernet.
• GSM - for connecting to a GSM/GRPS network with the GSM shield.
• MKRWAN - library for MKR WAN 1300/1310, for connecting to LoRaWAN®
networks.
• MKRGSM - library for MKR GSM 1400, for connecting to GSM/GPRS networks.
• MKRNB - library for MKR NB 1500, for connecting to NB-IoT / Cat M1
networks.
• SigFox - library for MKR FOX 1200, for connecting to the Sigfox network.
• WiFi - library for the WiFi shield, for Internet connections via Wi-Fi.
• WiFi101 - library for the MKR 1000 WiFi and WiFi101 shield, for Internet
connections via Wi-Fi.
• WiFiNINA - library for boards with a Wi-Fi NINA module, for Internet
connections via Wi-Fi.
Nano Family Libraries
Libraries designed for embedded sensors on various Nano boards.
• ArduinoAPDS9960 - library to use the gesture sensor APDS9960; it senses
gesture, color, ambience illumination and proximity.
• Arduino_LSM6DS3 - library to use the LSM6DS3 6 axis IMU available on the
Arduino Nano 33 IoT and the Arduino UNO WiFi Rev. 2.
• Arduino_LSM9DS1 - library to use the LSM9DS1 9 axis IMU available on the
Arduino Nano 33 BLE and the Arduino Nano 33 BLE Sense.
• Arduino_LSM6DSOX - library to use LSM6DSOX 6 axis IMU available on the
Arduino Nano RP2040 Connect.
• ArduinoLPS22HB - library to use the barometer and temperature sensor
LPS22; it is an ultra-compact sensor which functions as a digital output
barometer.
• ArduinoHTS221 - library to use the HTS221 relative humidity & temperature
sensor.

28
• PDM - library to use the digital microphone MP34DT05 (Nano BLE Sense and
Nano RP2040 Connect).
Memory
Libraries for memory management and data storage.
• EEPROM - reading and writing to "permanent" storage.
• SD - for reading and writing SD cards.
Display
Libraries for controlling different displays.
• LiquidCrystal - for controlling liquid crystal displays (LCDs).
• TFT - for drawing text, images, and shapes on the Arduino TFT screen.
MKR Family Libraries
Libraries listed below are specifically designed to work with Arduino MKR Family products.
• Scheduler - manage multiple non-blocking tasks (also works with the Arduino
Due).
• RTCZero - Real Time Clock to schedule events.
• ArduinoMKRGPS - library to be used with the Arduino MKR GPS Shield.
• ArduinoMKRRGB - library to be used with the Arduino MKR RGB Shield.
• ArduinoGraphics - library with graphic primitives, works also with the Arduino
MKR RGB Shield.
• ArduinoRS485 - library that implements RS485 on the Arduino MKR RS485
shield.
• ArduinoMKRENV - library to read all MKR ENV Shield sensors.
• ArduinoMKRTHERM - library to read the sensors connected to the Arduino
MKR THERM Shield.
• MKRIMU - library to read the acceleration, gyroscope, magnetic field and
euler angles from the IMU on your MKR IMU shield
• ArduinoMotorCarrier - library for controlling the MKR / Nano Motor Carriers.
• Arduino_MKRIoTCarrier - library for controlling the MKR IoT Carrier
Audio
Libraries for audio sampling and playback.

29
• AudioFrequencyMeter - library to sample an audio signal and get its frequency
back.
• AudioZero - library to play audio files from a SD card.
• ArduinoSound - simple way to play and analyze audio data.
• Audio - allows playing audio files from an SD card. For Arduino DUE only.
• I2S - library for using the I2S protocol on SAMD21 (included in SAMD
platform).
USB
Libraries for using your Arduino as either a USB host or device.
• USBHost - communicate with USB peripherals like mice and keyboards.
• Keyboard - send keystrokes to an attached computer.
• Mouse - control cursor movement on a connected computer.
Other
• Firmata - for communicating with applications on the computer using a
standard serial protocol.
Retired Libraries
A list of archived libraries for retired products.
• CurieBLE - interact with smartphones and tablets with Bluetooth® Low Energy.
• CurieIMU - manage the on-board accelerometer and gyro.
• CurieTimerOne - allows to use Timer functions.
• CurieTime - allows to control and use the internal RTC (Real Time Clock).
• Esplora - this library enable you to easily access to various sensors and
actuators mounted on the Esplora board.
• Robot - this library enables easy access to the functions of the Arduino Robot.
• Bridge - enables communication between the Linux processor and the
microcontroller on the Yún.
• Ciao - aims to simplify interaction between microcontroller and Linino OS
allowing a variety of connections with most common protocols.

30

You might also like