0% found this document useful (0 votes)
82 views85 pages

Claudia Alves, Arduino Reference - Syntax, Concepts, and Example (2021)

This document provides an overview of the Arduino programming environment and coding concepts. It discusses the Arduino programming language, which is based on C/C++. The Arduino IDE is introduced as the integrated development environment for writing Arduino code sketches. Various data types, constants, variables, control structures, functions, and libraries are described. The document also mentions Proteus simulation software and using matrices and loops to control LEDs. Overall, the document serves as an introduction for learning the basics of Arduino programming.

Uploaded by

NickOl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
82 views85 pages

Claudia Alves, Arduino Reference - Syntax, Concepts, and Example (2021)

This document provides an overview of the Arduino programming environment and coding concepts. It discusses the Arduino programming language, which is based on C/C++. The Arduino IDE is introduced as the integrated development environment for writing Arduino code sketches. Various data types, constants, variables, control structures, functions, and libraries are described. The document also mentions Proteus simulation software and using matrices and loops to control LEDs. Overall, the document serves as an introduction for learning the basics of Arduino programming.

Uploaded by

NickOl
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

Arduino Reference

syntax, Concepts, Arduino & Proteus , and Examples

2020

2nd Edition

By Claudia Alves

mEmlnc.com

"Programming isn't about what you know; it's about what you can figure out.” - Chris Pine

This book will help you to develop working source code for the Arduino microcontroller. In these pages, we will primarily
concern ourselves with the software aspect of physical computing—designing code to work with physical objects that exhibit
behavior or interactivity through software. Starting with the basic context of the Arduino platform to getting up and running
with our first code, we will discuss the structure and syntax of Arduino’s C-based programming language, looking at
variables, control structures, arrays, and memory. This book will then go into many of the functions unique to Arduino
development for controlling digital and analog input and output, timing, randomness, writing functions, and using many of
the Arduino libraries for working with different kinds of hardware and communication protocols. Arduino, like Processing
before it, adopted the idea of a code sketchbook. We will carry on this metaphor as we talk about the process of sketching in
code as an intuitive method for quickly testing out new ideas in code. Most of this book is written around this idea of
developing programming skills through sketching. We will also provide some suggestions for new projects and hardware,
new languages to try out, and ways to contribute back to the community. This book intentionally does not dwell too long on
electronics theory, circuit design, hacking, or other specifically hardware-based practices, although we’ll revisit the hardware
1
side of things in our last chapter to provide a small foundation for physical computing. This book in many ways picks up
where the Arduino Programming Notebook left off, with even more in-depth discussions about the Arduino environment;
simple, no-frills code samples; and clear, easy-to-read schematics and illustrations.The Notebook, a little PDF booklet, was
my first experience writing about the Arduino and was never meant to be more than a brief guide for my students when I first
introduced a class of 15 college art and design majors to the Arduino in 2007. Best laid plans and all, this little booklet has
now been translated into Spanish, Russian, and Dutch (that I know of), is hosted in so many different places that it is
impossible to keep track of, and it’s been used in workshops and classes around the world. I haven't updated the Notebook
over the last few years, and in all honesty I am not entirely sure what to do with it now, so hopefully this new book will fill a
void and find a similar, widespread adoption that the little booklet has enjoyed all these years.

Lcd.print("John Bach Translation");

Introduction

Arduino Coding Environment and basic tools

What language is Arduino?

Arduino IDE

Chapter One

Transactions in Arduino language

Arithmetic transactions in Arduino

Budget transactions in Arduino

Boolean transactions in Arduino

Index access transactions in Arduino

Binary number coefficients in Arduino

Compound transactions in Arduino

Chapter II

Data types

The String object in the Arduino

General structure

Returned values

Minions

Transactions

Arrays in Arduino
2
Create an array

Access to the matrix

Type bool in Arduino

byte in Arduino

Type char in Arduino

Type double in Arduino

Type float in Arduino

General structure

Type int in Arduino

Strings In Arduino

General structure

Termination character null

Long strings wrapping

Matrices of text strings

Type word in Arduino

The keyword void in Arduino

Chapter III

Constants and variables

Decimal system (base 10)

Binary System (Basis 2)

Notes and warnings

Constants in Arduino

Variable Scope & Qualifiers

The keyword const in Arduino

The field of variables in Arduino

The static keyword in Arduino

Examples

Keyword volatile in Arduino

Volatile or long volatile integers?

Chapter IV

Control structures

Keyword break in Arduino

Continue keyword in Arduino

Loop do ... while iterative in Arduino

Keyword else in Arduino

Goto keyword in arduino

Expression if conditional in Arduino

Notes and warnings

Keyword return in Arduino

Examples

Expression switch ... case in Arduino

Transactions

While iterative episode in Arduino

Chapter V

Functions

The digitalRead () function in the Arduino

digitalRead (pin)

The digitalWrite () function in the Arduino

The pinMode () function in the Arduino

Time functions in Arduino

The delay () function in the Arduino

Arduino delayMicroseconds () function

Arduino micros () function

Arduino millis () function

Mathematical Functions in Arduino

Handling and verifying typefaces in Arduino

3
Arduino conversion functions

Provincial control functions in Arduino

Chapter VI

Additional tools

The keyword programm in Arduino

Examples

Notes and warnings

Chapter VII Proteus 162

Chapter VIII Matrices and loops for and condition if to control LEDs 174

4
Introduction

Since the launch of the Arduino open-source platform, the brand has established themselves at the center of an expansive
open-source community. The Arduino ecosystem is comprised of a diverse combination of hardware and software. The
versatility of Arduino and its simple interface makes it a leading choice for a wide range of users around the world from
hobbyists, designers, and artists to product prototypes.

The Arduino board is connected to a computer via USB, where it connects with the Arduino development environment (IDE).
The user writes the Arduino code in the IDE, then uploads it to the microcontroller which executes the code, interacting with
inputs and outputs such as sensors, motors, and lights.

Both beginners and experts have access to a wealth of free resources and materials to support them. Users can look up
information on how to set up their board or even how to code on Arduino. The open source behind Arduino has made it
particularly friendly to new and experienced users. There are thousands of Arduino code examples available online. In this
book, We will explain all the basic principles that a novice programmer needs to enter the genius world, Arduino

5
Arduino Coding Environment and basic tools

What language is Arduino?


Arduino code is written in C++ with an addition of special methods and functions, which we’ll mention later
on. C++ is a human-readable programming language. When you create a ‘sketch’ (the name given to Arduino
code files), it is processed and compiled to machine language.

Arduino IDE
The Arduino Integrated Development Environment (IDE) is the main text editing program used for Arduino
programming. It is where you’ll be typing up your code before uploading it to the board you want to program.
Arduino code is referred to as sketches.

Arduino is an open source platform used to build electronic projects (ranging from simple projects such as thermometers to
complex projects such as robots, 3D printers, and IoT applications). The main goal of creating the Arduino platform is to
provide a user-friendly platform to help people without prior knowledge of electronics and programming. The Arduino
platform consists of two main sections: the hardware section and the software section. The hardware section consists of an
Arduino board and related electronic components and other hardware components, while the software section consists of the
Arduino Development Environment (Arduino IDE), which represents the host environment for writing the code in the
Arduino language and uploading it to the Arduino boards to control the hardware section.

Arduino is just a set of C / C ++ functions, which are mainly derived from C and C ++ and the Wiring and Processing
frameworks and are open source. The Arduino language is used to program Arduino boards of various types. Arduino is
distinct from the C-derived language, being an object-oriented language, containing many classes and objects such as String
and Stream. In addition, Arduino is rich in a lot of libraries that provide more functionality such as working with any piece or
additional electronic element, modifying data, etc. Arduino is not only required to be used with the Arduino IDE but can also
be used with third-party development environments such as Eclipse.

6
Chapter One
Transactions in Arduino language

7
Arithmetic transactions in Arduino

Arithmetic Operators perform the four basic arithmetic operations (addition, subtraction, multiplication and division) in
addition to other operations such as calculating the remainder of division and assigning values to variables.

Modulus%
Calculates the rest by dividing two numbers by each other.

Laboratories *
Calculates the product of multiplying two numbers together.

OPERATION +
Calculates the result of adding two numbers together.

-
Calculates the result of subtracting two numbers from one another.

Labs /
Calculates the result of dividing two numbers by one.

Parameter =
The attribution coefficient tells the controller to evaluate the expression or value on the right side of the coefficient = whatever
and store it in the variable on the left side of that coefficient.

8
Budget transactions in Arduino

Comparison Operators perform a balancing process, as it is called, between two values, two variables, a variable and a given
value, and then return a logical value that represents the state of one operator (greater, smaller, equal, etc.) relative to the
other.

Parameter! =
Balance two values or two variables and return the true value if they are not equal.

Parameter <
Balance two values or two variables and return the true value if the coefficient on the left side is completely smaller than the
coefficient on the right side.

Parameter <=
Balances two or two values and returns true if the coefficient on the left side is smaller than or equal to the coefficient on the
right side.

Parameter ==
Balance two or two variables and returns true if the coefficient on the left side is equal to the coefficient on the right side.

Parameter>
Balance two values or two variables and return the true value if the coefficient on the left side is exactly larger than the
coefficient on the right side.

Parameter> =
Balance two or two values and returns true if the coefficient on the left side is greater than or equal to the coefficient on the
right side.

9
Boolean transactions in Arduino

Boolean Operators perform Boolean operators (AND operation, OR operation, or NOT operation) on values or logical
expressions and return the resulting Boolean value.

!
The logical reflects the value or logical expression that precedes it by applying the NOT logical operation to it;

&&
Applies the AND logical operation to two logical values or expressions and returns the resulting logical value

||
Applies the logical OR operation to two logical values or expressions and returns the resulting logical value

10
Index access transactions in Arduino

Pointer Access Operators (Pointer Access Operators) are transactions that are used with cursors to provide cursor access to
and references to variable memory addresses, and variables to access values contained in memory addresses referenced by
cursors.

&

It is used to provide a reference to the referencing memory address of a variable. A reference is an important feature used
with pointers.

It is used to provide access to a value stored in a specific memory address (Dereferencing) of an indicator. Access to data
stored in memory addresses is an important feature used with pointers.

11
Binary number coefficients in Arduino

Bitwise Operators performs all logical operations and offsets on number bits and binary values and returns the resulting
value.

&

In C ++, the AND operation is performed on each of the two corresponding bits of the given numbers independently and
gives the resulting numerical value.

>>

The bits to its left to the left displace a specified number of digits equal to the value to the right.

<<

The bits to the left of it to the right displace a specified number of digits equal to the value on the right.

In C ++, the XOR operation is performed on each of the two corresponding bits of the given numbers independently and
gives the resulting numerical value.

In C ++, the OR operates on each of the two corresponding bits of the two given numbers independently and gives the
resulting numerical value.

In C ++, the NOT operation is performed on each of the given bits independently - unlike the & & coefficient | - and gives the
resulting numerical value.

12
Compound transactions in Arduino

Compound Operators are frequently used to write codes in Arduino to zero, fine-tune and invert certain bits in binary values
and other important processes that greatly simplify and simplify code writing.

Parameter = &

Usually used with a constant variable to zero a specific bit value (ie make a value of 0 or LOW).

Modulus = *

It is a shorthand for multiplying the current value of one variable by a constant or another variable and then storing the result
in the same variable.

OPERATION ++

Increases the value of the variable used by 1.

Parameter = +

A shorthand is the process of combining the current value of a variable with a constant or another variable and then storing
the result in the same variable.

Decreases the value of the variable used by 1.

Modulus = -

A shorthand for a constant or another variable is subtracted from the current value of a variable and the result is stored in the
variable itself.

Modulus = /

A shorthand is a process of dividing the current value of one variable by a constant or another variable and then storing the
result in the same variable.

Modulus = ^

Usually used with a constant variable to invert (reverse) a specific bit value.

Parameter = |

It is usually used with a variable of constant to set a specific bit value (set to 1 or HIGH).

13
14
Chapter II
Data types

15
The String object in the Arduino

The String () function creates a copy of the String class. There are several ways to create text strings of different types of data:
call the String () function with:

Static text string of characters within double quotation marks (i.e. an array of characters), or

A single constant character within single quotation marks, or


Another copy of the String object, or
Integer constant or long constant number, or

A fixed integer or long fixed number using a specified base, or


Integer or long variable number, or
Integer or long number variable using a specified base, or

A decimal or a double decimal number using specified decimal places.

If you call the String () function with a number, it creates a text string containing a representation of that number's numbers
via ASCII characters. The default basis used in this case is 10. The following example would be given:

String thisString = String (13);

Text string "13". A different basis can be used such as:

String thisString = String (13, HEX);

You will give the text string "D" which is the hexadecimal representation of the decimal value of 13. If you prefer binary, try
this example:

String thisString = String (13, BIN);

Which will give the text string "1101" which is the binary representation of the decimal value of 13.

General structure

String (val)

String (val, base)


String (val, decimalPlaces)
Transactions

val
The variable or value to be formatted as a text string. The allowed data type are: text string, typeface, byte, integer, pointless
integer, long pointless number, decimal number, and multiplier decimal.

base
Optional coefficient determines the basis of the numerical system in which the numerical value will be formatted. The default
value is: DEC.

decimalPlaces
Restricts the number of decimal places (numbers after the comma) to the decimal or multiple of the decimal.

Returned values
A copy of the String class containing the value val is returned.

16
Examples

All of the following are valid examples of using the String () function:
String stringOne = "Hello String"; // Use a fixed text string
String stringOne = String ('a'); // Converts a fixed typeface to a text string

String stringTwo = String ("This is a string"); // String Converts a static text string to an object of type
String stringOne = String (stringTwo + "with more"); // Combine two text strings together
String stringOne = String (13); // Use a constant integer

String stringOne = String (analogRead (0), DEC); // Using an integer specifying the basis used
String stringOne = String (45, HEX); // "Use integer with base set to" hex
String stringOne = String (255, BIN); // "Use an integer with the baseline set to" binary

String stringOne = String (millis (), DEC); // Use a long number and specify the basis used
String stringOne = String (5.698, 3); // Use a decimal number and specify the number of decimal places

Minions
charAt ()

The function fetches a character with a specific index from the text string that is called with it.

compareTo ()

The function balances two text strings and determines which is greater than the other or if they are equal.

concat ()

The function adds the parameter passed to it to the text string that is called with it.

c_str ()

The function converts the content of the text string with which it is called to the ideal text string style in C (the text string
ending in null).

endsWith ()

The function verifies whether the text string called with it ends with the same characters that were passed to it.

equals ()
The function verifies if the text string you are calling is equal to the text string you passed to.

equalsIgnoreCase ()
The function verifies if the string you are calling is equal to the string you passed to, not taking into account the case.

getBytes ()
The function fetches a specified number of bytes of the text string that is called with it and places it in a specific repository.

indexOf ()
The child index returns the first appearance of a particular character or text string within the text string that is called with it.

lastIndexOf ()
The child index returns the last appearance of a particular character or text string within the text string that was called with it.

17
length ()

The function returns the number of characters of the string that is called with it.

remove ()

The function deletes a specified number of characters of the text string with which it is called.

replace ()

The child substitutes a typeface or substring where a specific typeface or substring exists in the string that is called with it.

reserve ()

The slave reserves part of the memory and allocates it to manipulate and modify the text string that is called with it.

setCharAt ()
The function assigns the value of a character that is positioned in the text string with which it is called.

startsWith ()
The function verifies whether the text string called with it begins with the same characters that were passed to it.

substring ()
The child fetches a specific part of the text string that is called with it.

toCharArray ()
The function converts the whole or part of the text string that is called with it into a string of characters.

toInt ()

The function converts the text string with which it is called into an integer.

toFloat ()
The function converts the text string with which it is called to a decimal.

toLowerCase ()

The function converts all the characters of the text string with which it is called into lower-case letters.

toUpperCase ()
The function converts all the characters of the text string with which it is called to upper-case.

trim ()
The function removes all white spaces from the beginning and end of the text string called with it.

Transactions
[]
The operator provides access to and returns a specific character of the string used.

+
The operator combines (merges) two text strings together into one new text string and then returns them.

18
=+
The operand adds any type of data to the end of a particular text string.

==
The coefficient verifies that two text strings are equal to each other.

<
The operand checks if the text string to the left is exactly larger than the text string to the right.

=<
The operand checks if the text string to the left is greater than or equal to the text string to the right.

>
The operand checks if the text string on the left is smaller than the text string on the right.

=>
The operand checks if the text string to the left is less than or equal to the text string to the right.

=!
The parameter checks if the text string on the left is different from the text string to the right.

19
Arrays in Arduino

An array is a set of variables placed in a single container that can be accessed by their index number. Matrices in C, on which
Ardonyo is based, can be a bit complicated, but using them in the simplest form is easy.

Create an array

There are several ways to create an array:

int myInts [6];


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

int mySensVals [6] = {2, 4, -8, 3, 2};


char message [6] = "hello";

You can declare an array without initializing it and placing values in it as in myInts. An array can be declared without
explicitly specifying its size, such as myInts; in this case, the bank will count the elements and give the matrix an appropriate
size.
However, you can configure an array and specify its size as in the case of the mySensVals array. Note that when declaring an
array of characters, you need to increase the size of the array to the size required to accommodate only one additional
element, the null, which is located at the end of the characters; see, for example, the size of the message array in the previous
example and the number of characters stored in it.

Access to the matrix

The indexing of elements in the array begins with a value of 0; the index of element 2 in the mySensVals matrix - in the
previous example - is 0, the index of element 4 (second element) is 1, and so on. This also means that the index of the last
element of a 10-element array is 9, not 10! Here's an example:

int myArray [10] = {9,3,2,4,3,2,7,8,9,11};


// The value 11 contains the myArray [9] element
// It works outside the array and has myArray [10]

// Returns a random value from memory

For this reason, you should be careful not to make this error when accessing any element of an array. Accessing an element
that falls after the last element (indexed greater than the size of the array with a value of 1), or generally outside the array,
leads to reading from a portion of memory that is intended for other purposes. Reading this part does not return valid values
or data. Conversely, writing on a piece of memory outside the reserved portion of an array, when assigning a value to one of
its elements, is bad and more dangerous than reading that part, as it can lead to disastrous and unexpected results such as
program crashes and downtime. This error may be difficult to track and refine.

The C language expense does not verify access to arrays defined in the program, although an access exceeds the limits of one,
unlike BASIC or JAVA, to verify this.

Assign a value to an array element

Any value can be assigned to an array element by using the attribution operator = and the index of the element in question
Assign the value to it as follows:

mySensVals [0] = 10;

Bring value from the matrix

20
The value of any array element can be fetched by the index of that element as follows:

x = mySensVals [4];

Arrays and loops

Arrays are frequently used within loops to modify or fetch the values of their elements. The loop counter is used as the index
of each element of the array. For example, to print all array elements on a serial interface, you can use something similar to
the following example:

int i;
for (i = 0; i <5, i = i + 1) {
Serial.println (myPins [i]);

21
Type bool in Arduino

The declared bool variable stores one of the following two logical values: true, or false, by reserving only one byte of
memory.

General structure

bool var = val;


Var represents the name of the variable to declare, and val is the value to assign to this variable, which is either true or false.
Examples

The following example illustrates how to use the bool type to make the light attached to the leg 5 flash each time the cutter
connected to the leg 13 is pressed:
int LEDpin = 5; // LED light connected to leg 5
int switchPin = 13; // An instantaneous cutter connected to the 13th leg, and the other leg connected to the ground

bool running = false;

void setup ()

pinMode (LEDpin, OUTPUT);

pinMode (switchPin, INPUT);

digitalWrite (switchPin, HIGH); // Activating the internal lifting resistance

void loop ()

if (digitalRead (switchPin) == LOW)

{// Was the cutter pressed? Patches resistance keeps voltage always high

delay (100); // Delay in order to neglect the cutter bounce

running =! running; // Switch the value of the variable

digitalWrite (LEDpin, running); // Indicating the state of the variable through light

22
byte in Arduino

Byte stores an unsigned 8-bit number, i.e. from 0 to 255.

General structure

byte var_name;
byte var_name = Number; // 0 - 255

Examples
Example of defining a byte variable:

byte myNumber = 125;


byte result = myNuber / 5;

Note that the numbers after the comma in the second case will be neglected if the division (or any calculation) result in a
decimal.

23
Type char in Arduino

The char type reserves one byte of memory and stores a typeface value. Characters are written in single quotes like 'A' (for
several characters [[[Arduino / string | text string]]], use an even quotation mark like 'ABC').

Numbers are stored in the bytes reserved for the char type representing the value of the corresponding character. These
numbers are referred to as coding, and the coding used here is ASCII coding. Go to the ASCII Documentation Documentation
to see all the characters and the corresponding numerical value for each. This means that it is possible to perform some
calculations on the characters in which the ASCII value is used (such as carrying out the operation A '+ 1' which will give the
value 66 corresponding to the letter 'B', since the numerical value of the letter 'A' in the ASCII symbol is 65). Take a look at
the Serial.println () function documentation for more information on how to switch characters and their numerical value.

Char is a type with a signal; this means that the numerical values it can take ranges between 128 and 127. If you want one
byte without a signal to store data in it, use the type byte.

General structure

cahr var = 'character';


char var = Number;

Var represents the name of the variable to declare, and the character represents the character to be attributed to that variable.
The corresponding character number can be used in ASCII encoding instead of the same character.

Examples

Example of defining a type char:

char myChar = 'A';


char myChar = 65; // Both represent the same typeface

24
Type double in Arduino

Double is a decimal number with double precision. On Arduino and other ATMEGA-based boards, this type reserves only 4
bytes (32 bits) of memory. This means that the double type in these panels exhibits the behavior of the float type itself without
any difference and without any increase in accuracy.

In Due panels, the size of the double type is 8 bytes (64 bits), which is twice the float.

General structure

double var;
double var = val;

Var represents the name of the variable to declare, and val represents the decimal value to assign to this variable.

Examples
An example of defining a double variable:

double myNumber = 12.123456789;


double result = myNumber / 2;

Notes and warnings


Users who bring codes that contain double type variables from other sources must try and test the code to ensure that the
desired precision does not differ due to the different boards that will be implemented on it (especially boards that rely on
ATmega controllers).

25
Type float in Arduino

The type float is used with decimal numbers, which are fractional numbers that are used as a decimal separator. Decimal
numbers are often used to approximate similar continuous values because they have greater accuracy than integers. Decimal
numbers can be large with the number 38.028235E + 38 and small with the number 38-4282835E +. The float type reserves
four bytes (32 bits) of memory to store a float.

Float decimal numbers have a small precision of 6-7 decimal places after the comma. In Arduino Uno and other ATMEGA
control boards, there is no higher resolution than this by using double (double float), as the size of this type is exactly the
same as float. In Due panels, the double type provides double precision.

Doing mathematical operations on decimal numbers is much slower than performing the same operations on integers, so
decimal numbers should be avoided if the timing is critical for some functions and the iterative function is required to repeat
the operations at the fastest speed and the shortest possible time. Programmers usually avoid performing arithmetic operations
on decimal numbers and convert and manipulate these operations to perform on integers only in order to increase the speed of
the program.

If your program performs mathematical operations on decimal numbers, then you must add to all the fixed numbers used in
these operations decimal places after the comma if they do not have them (such as 12.0); if you do not (i.e. you use the
number 12 only), then these numbers will be treated as Integers. See the decimal point fixed number page for more
information.

General structure

float var;
float var = val;

Var represents the name of the variable to declare, and val represents the decimal value to assign to this variable.

Examples
An example of defining a float variable and performing a calculation on it:

float myfloat;
float sensorCalbrate = 1.117;

int x;
int y;
float z;

x = 1;
y = x / 2; // the value 0, because it cannot store the decimal parts y will contain the variable

z = (float) x / 2.0; // (the value 0.5) pay attention to the number 2.0 and do not use 2 only z will contain the variable

26
Type int in Arduino

Whole numbers are the primary data type used to store numbers.

On Arduino Uno boards (and ATMega based boards), the int type reserves a 16-bit (2-byte) size of memory in which numbers
between 32768- (the smallest value equal to 15 ^ 2) can be stored and 32767 (the largest and equal value 1 - 15 ^ 2). In
Arduino boards and SAMD-based boards (such as MKR1000 and Zero), the type reserves a 32-bit (4-byte) amount of
memory to store numbers from 2,147,483,648- (31 ^ 2-) to 2,147,483,647 (1-31) ^ 2).

This type stores negative numbers with a technique called "Two's complement". The most important upper bit (MSB)
determines whether a number is negative or positive, and it is often called a “sign bit”. When its value is 1, the value of all
remaining bits is reversed and added 1.

Arduino has the task of dealing with negative numbers, so the calculations are performed on them transparently and in the
expected way. However, there may be some complexity in dealing with the displacement coefficient <<.

General structure

int var = val;

Var represents the name of the variable to declare, and val represents the correct numerical value to be assigned to that
variable.

Examples

The following example will create a variable called countUp and assign an initial value to it; this variable will be used as an
ascending counter, as its value will be increased during the loop and will appear on the serial communication interface:

int countUp = 0; // Declare a variable with integers

void setup () {

Serial.begin (9600); // Configure and start the serial port

void loop () {

countUp ++; // countUp Add the value 1 to the variable

Serial.println (countUp); // Print the value of the current variable on the serial port

delay (1000);

Notes and warnings

If the signal variables exceed the maximum or minimum value of the type in which they are defined, then they will have
reached an "overflow" state, and their value cannot be predicted at that time. Consequently, care must be taken to make a
variable reach the condition of rash (unless this is desirable). One of the indicators of the variable's arrival to the state of rash
is the transfer of the variable from its maximum value to its minimum value or vice versa. Note that we said "one of the
indicators" and not the only evidence that a rash occurred, so be careful. If you define a variable and do not intend to use it to
store a negative value in it, then the unsigned int of this type, which is an unsigned int, should be used to reduce the
possibility of reaching the overflow.

27
28
Strings In Arduino

Strings can be represented in two ways. Either the text strings are used as one of the data types in Arduino which became part
of the kernel starting in version 0019, or a text string can be created from an array of characters with the null character in the
end; the second method will be explained on this page, as the first method is explained in detail in documentation The string
object provides many functions and tools for manipulating text strings but at the expense of memory.

General structure
All of the following examples are valid strings for declarations:

char Str1 [15];


char Str2 [8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};

char Str3 [8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\ 0'};
char Str4 [] = "arduino";
char Str5 [8] = "arduino";

char Str6 [15] = "arduino";

There are several possibilities available for declaring strings:

Declaring a matrix without formatting as in Matrix Str1.


Declaring a matrix of characters (increasing the size to accommodate an additional character), and the compiler will
automatically add the required null as the Str2.
This case is just like the previous case except for explicitly adding null to the array like Str3.

Configure the array with a fixed text string given in quotation marks; when decoding the code the array will choose an
appropriate size for the array that fits the fixed text string with a null terminator. Look at the Str4 matrix for this case.
Initializes the array and explicitly specifies it, such as Str5.
Configure the matrix with an oversize option to provide future text string capability; see Str6 for example.

Termination character null


Generally, strings terminate with null (ASCII 0). This allows functions (such as the Serial.print () function) to know the end
of a text string when it is read or fetched from memory. If the terminate character is not present, the function will complete
reading or fetching successive bytes in memory that may not be part of the text string itself.

This means that any text string must have additional space for an extra character in addition to the content that you want to
store in the string. This is the reason why Str2 and Str5 need a size of 8, even though the phrase “arduino” is only 7, because
in the last available position the typeface will be added null automatically. For Str4, its size will be set to 8 characters
automatically, taking the termination character into account. In matrix Str3, we added the null null of the expression ('0 \')
manually.

Note that it is possible that there is a text string that does not have a terminate character (such as setting Str2 to 7 instead of
8). This will malfunction in most of the functions dealing with strings, so you should avoid doing this inadvertently. If you
notice that the behavior of the program has become somewhat strange (especially when dealing with characters and not with
strings), then the termination character is likely to be the cause of the problem.

Single and double quotation marks


Strings are always defined inside double quotation marks like "ABC", and characters are always defined inside single quotes
like 'A'.

Long strings wrapping


Long strings can wrap and move to the following line as:
char myString [] = "This is the first line"

"And this second line"


" And so on";

29
Matrices of text strings
It is often appropriate when dealing with a large amount of text, such as working on a project with an LCD screen, creating an
array of text strings. Since the strings are matrices themselves, in this case we will use a two-dimensional matrix.

In the following example, the presence of the parameter * after defining the type of data that is char as "* char" indicates that
the matrix to be declared is an array of pointers. Really, all arrays are pointers, so using this parameter * in this way is
important to create an array of arrays. The indicators in C are a little complicated and not understood by many novice
programmers, but it is enough to understand the indicators only superficially to deal with them in our case.

Examples

An example of defining an array by using a parameter * and printing the contents of this array on the serial interface:
char * myStrings [] = {"This is string 1", "This is string 2", "This is string 3",

"This is string 4", "This is string 5", "This is string 6"};

void setup () {

Serial.begin (9600);

void loop () {

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

Serial.println (myStrings [i]);

delay (500);

30
Type word in Arduino

Word type variables store a non-signal number of 16 bits (2 bytes), with a value ranging from 0 to 65,535 max. This type is
similar to the unsigned int type.

General structure

word var = val;

Var represents the name of the variable to declare, and val represents the value to be attributed to that variable.

Examples

Example of defining a variable of type word and assigning a value to it:

word w = 10000;

31
The keyword void in Arduino

The keyword void is used with functions defined by the programmer in the code to indicate that this function is not expected
to return any data to whoever called it after its execution. Based on this definition, the return keyword is not assumed to be
used within the function declared with the keyword void.

General structure

void function ()

{
// The code block that the code will execute
}

Examples

The following code explains how to use void with the setup () function and loop () to indicate that they will not return
anything after their implementation is complete:
// But "loop" and "setup" will not be executed for all tasks within the two functions

// Neither of them returns any data back to the higher program that called them

void setup ()

// ...

void loop ()

// ...

32
Chapter III
Constants and variables

Fixed integers in Arduino

Fixed integers are numbers used directly in the code such as 123. By default, these numbers are treated as integers but can be
converted to other types of numbers using a modifiers such as U or L.

Integers are treated as integers based on the number 10 always (ie represented by decimal by default). However, other
formulas can be used to write numbers, since the basis of the number will vary.

33
Decimal system (base 10)
This system is the common counting system among humans that they always use in calculations. Numbers written in the code
that are not preceded by any coordinator (prefix determining the number formula) are considered as numbers written in
decimal (base 10).

n = 101; // ((1 * 10 ^ 2) + (0 * 10 ^ 1) + 1) == 101

34
Binary System (Basis 2)
The values in this system are represented by numbers 0 and 1 only.

n = B101; // ((1 * 2 ^ 2) + (0 * 2 ^ 1) + 1 * 2 ^ 0) == 5 in decimal


The binary formula is only valid for byte (8-bit) values; between 0 (B0) and 255 (B11111111). If you want to use the binary
formula with larger values - such as with integers (16 bits) - you can do this by performing a simple two-step process as
follows:

myInt = (B11001100 * 256) + B10101010; // is the upper byte value B11001100

Eight (Basis 8)

The numbers used to represent the values in this system are from 0 to 7. The values to be written and represented in this
system begin with the coordinator 0 (zero).
n = 0101; // ((1 * 8 ^ 2) + (0 * 8 ^ 1) + 1) == 65 in decimal
A logical error that is difficult to find in the code is likely to result from an unintentional zero constant; this leads the
interpreter to interpret this constant as a value of eight during code discharge.

Hexadecimal system (base 16)

The numbers and characters used to represent the values in this system are 0 to 9 and A to F. In fact, the decimal value of the
letter A is 10, the letter B is 11, and so on until the letter F is 15. The values to be represented and written in the hexadecimal
system With prefix 0x. Note that the letters A-F can be used in uppercase or lower case (a-f).
n = 0x101; // ((1 * 16 ^ 2) + (0 * 16 ^ 1) + 1) == 257 in decimal

35
Notes and warnings

The U and L switches

By default, a constant integer is treated as a type of integer that has a limited size that is insufficient in some cases. To change
this type to another type of data, you can use one of the U or L switches as follows:

'u' or 'U': This switch is used at the end of the numerical constant to convert it to an unsigned type such as 33u.
'l' or 'L': This switch is used at the end of the numerical constant to convert it to a 'long number' type such as 100000L.

'ul' or 'UL': The two switches are used together at the end of the numerical constant to convert it to a 'long number without
signal' type such as 32767ul.

36
Constants in Arduino

Constants are predefined expressions in the Arduino language. Used to make it easier for programmers to work as they write
code, as well as to make the code more readable. Constants are grouped by function.

Defining logical levels (logical constants)

In Arduino, there are two constants used to represent truth and falsity: true and false.

The constant is false

The logical false value is an error value and is defined as numerically zero (0).

The constant is true

A true Boolean is a true value and is defined as one (1) numerically. In fact, true represents a wider range of numeric values
than just 1. Any non-zero value is logically referred to as true. Accordingly, values 1, 2, and 200 all logically indicate true.

Be aware that true and false are lowercase, unlike other constants such as HIGH, LOW, INPUT, etc.

Definition of the state of the legs (voltage level)


When reading or writing the value of digital legs, we find that we are dealing with two values that are not third; one of the
digital legs can be taken or set to HIGH or LOW.

Hard HIGH
The meaning of the fixed HIGH value, when dealing with the legs of the Arduino board, varies depending on the position of
the man; that is, the man is an INPUT or an OUTPUT. If the man is set to a man who has entered by passing the INPUT value
to the pinMode () function and is read using the digitalRead () function, the ATmega controller will report the HIGH value if:

The voltage applied to the leg is greater than 3.0V on panels with a voltage of 5V, or
The voltage applied to the leg is greater than 2.0V in 3.3V panels.

The man can also be set to an input man by passing the INPUT constant to the pinMode () function and then typing the HIGH
value on it using the digitalWrite () function. This will activate the internal lifting resistance associated with that man.
Activating this resistance will raise the man's effort to HIGH unless it is reduced to LOW by connecting it to an external
circuit. This is very similar to what the INPUT_PULLUP constant does when passed to the pinMode () function, which we
will address later.

When a man is set to an output man by passing the OUTPUT constant to the pinMode () function, and then typing the HIGH
value on it using the digitalWrite () function, that man's effort will be:

5 volts in 5V, or
3.3V in 3.3V panels.

When a man is in this state, then a current can be drawn to light a LED light, for example by connecting one of its poles to it
and connecting the other pole with resistance on the sequence to the ground pole.

Hard LOW

The meaning of the fixed LOW value also varies depending on the position of the man; If the man is set to an input man by
passing the INPUT value to the pinMode () function and is read using the digitalRead () function, the ATmega controller will
report the LOW value if:

The voltage applied to the leg is smaller than 1.5V in panels with a voltage of 5V, or

The voltage applied to the leg is smaller than approximately 1.0V in 3.3V panels.
When a man's position is set to an output man by passing the OUTPUT constant to the pinMode () function, and then typing
the LOW value on it using the digitalWrite () function, that man's voltage is 0 volts (in both 5V and 3.3V panels). When the
man is in this situation, a current can be discharged, such as one light pole connected to it and the other pole with resistance
on the sequence with a 5V + (or 3.3V +) pole to light it.

37
Definition of legs position (input or output)

Digital legs can be used as input legs or output legs by using one of the INPUT, INPUT_PULLUP, or OUTPUT constants
with the pinMode () function. When a man is so prepared, her electrical behavior is completely changed internally.

Hard INPUT

The legs of the Arduino board set as input legs using the INPUT constant with the pinMode () function are said to be in high-
impedance state. The legs set to the INPUT legs make the burdens on the circuit you are examining very small, equivalent to
a 100-ohm sequence resistance in front of the man. This makes the legs very useful in reading sensor values.

If one of the legs is set as an input man and used to read a switch, the man's condition will be “floating” when the cutter is
open; this will produce unexpected results. To ensure that the leg condition is read correctly when the cutter is open, use an
external pull-up or pull-down resistance with this leg. The goal of connecting the resistance to this man is to adjust its effort to
a known state when the cutter is open. A resistance of 10 k ‫ أوم‬is usually used, which is small enough to prevent the input leg
from floating, and large enough to not pull a large amount of current when the cutter is closed. See this tutorial for more
information.

If an external pull-down resistor is used, the input leg voltage will be low when the cutter is opened, and HIGH when the
cutter is closed.

If an external pull-up resistor is used, the input leg voltage will be HIGH when the cutter is opened, and LOW when the cutter
is closed.

The INPUT_PULLUP constant


The ATmega controller in the Arduino board has internal lifting resistance connected to each leg of the input and output legs
that can be controlled. If you prefer to use this resistance instead of adding an external lifting resistance, you can do so by
passing the INPUT_PULLUP constant to the pinMode () function when configuring the leg. Check out this tutorial, which
contains a practical example of what we have mentioned.

WARNING: Legs set as input legs using INPUT or INPUT_PULLUP can be damaged or destroyed if they are connected with
voltage below ground voltage (negative voltage) or greater than positive voltage (5V or 3.3V).

Hard OUTPUT
It is said that the legs of the Arduino board set as the output legs by using the OUTPUT constant with the pinMode () function
are in a high-impedance state. This means that they can provide enough current to other devices and circuits connected to
them. Any man with ATmega legs can give or discharge other devices and circuits up to 40 mA. Exceeding this value of
current damages the controller, so resistors or similar electronic elements must be used to determine current when connecting
electronic parts that require large amounts of current such as motors.

WARNING: Legs set as output legs using OUTPUT can be damaged or vandalized if connected with ground voltage or
positive voltage of the current source directly used.

Define embedded elements in the panel


Fixed LED_BUILTIN
Most Arduino boards have LED light integrated into the board and connected to one leg with resistance on the sequence. The
constant LED_BUILTIN represents the number of the man connected to this panel light. This man is the 13th man in most
Arduino paintings that have a built-in light on them.

38
Variable Scope & Qualifiers

The keyword const in Arduino

The keyword const is an abbreviation of the word constant, which is constrained by the variables that are used with it. This
means that a variable can be used as a representative of variables of the same type, except for the inability to change the value
that was assigned to it when it was created. You will encounter an error from the banker if you try to assign a value to a
variable with which the keyword const is used.

Constants defined using the const keyword comply with variable scoping rules that set the rest of the variables. Taking the
risks of define # into consideration, this makes the keyword const the best way to define constants, and preferably use them
instead of define #.

General structure

const dataType var = val;

The dataType represents the type of variable to be defined, var the name of the variable, and val the value to be assigned to
this constant variable. Note that once val is assigned to a variable, it can no longer be changed, and the variable will be read-
only.
Examples

Use the word const to define the constant π used in mathematical operations:
const float pi = 3.14;

float x;

// ....

x = pi * 2; // Constants are frequently used in mathematical operations

pi = 7; // This will generate an error, as a constant variable cannot be overwritten

Notes and warnings


Expression define # or keyword const?
You can use either the keyword const or the #define to create numeric or text constants. For arrays, you only need to use const
with them. In general, the use of the keyword const is preferable to the use of the define # expression.

The field of variables in Arduino

Variables in the C language, from which Arduino is derived, have a property called scope that determines the scope of use of
those variables and who can access them. This is different from recent versions of languages such as BASIC where the
variable is always global.

General variables can be seen by all functions in the program. On the other hand, local variables are only visible in the
function within which they are defined and not available to other functions. In the IDE environment, any variable declared
outside a function (such as setup (), loop (), etc.) is a global variable.

When a program becomes larger and more complex, local variables are more useful than general ones to ensure that only one
function reaches the variables defined within them. This prevents errors from one function from modifying variables that
another function inadvertently uses.

39
It is useful to declare variables and assign them value within iterative loops such as for. This prevents anything outside the
loop from accessing and modifying this variable.

Examples
int gPWMval; // Any function can see and access this variable

void setup ()
{

// ...
}

void loop ()
{
int i; // loop is only visible within the variable "i" loop
float f; // Only the loop is also visible within the variable "f" loop
// ...

for (int j = 0; j <100; j ++) {


// only for available within the variable j
}

The static keyword in Arduino

The static keyword is used when creating visual variables for only one function in order to preserve its content after the
execution of that invoked function and until the next call to it, unlike the local variables that are created and destroyed each
time the function is called.

The static variables declared within the function will be created and initialized with the static keyword only the first time that
function is called.

General structure

static dataType var = val;

The dataType represents the type of variable to be defined, var the name of the variable, and val the value to be assigned to
this static variable. Be aware that once the var variable is created when the function is first called, it will not be destroyed
when the function is executed and the value stored within it will be preserved until the next call to the function.

40
Examples

The following program generates random steps that are limited to a specific domain and also limits the size of the steps
through the stepsize variable passed to the randomWalk () function:
/ * RandomWalk
* Paul Badger 2007

* RandomWalk wanders up and down randomly between two


* Endpoints. The maximum move in one loop is governed by
* the parameter "stepsize".

* A static variable is moved up and down a random amount.


* This technique is also known as "pink noise" and "drunken walk".

#define randomWalkLowRange -20


#define randomWalkHighRange 20
int stepsize;

int thisTime;
int total;

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

void loop ()
{// randomWalk test function
stepsize = 5;
thisTime = randomWalk (stepsize);
Serial.println (thisTime);
delay (10);

int randomWalk (int moveSize) {


static int place; // is defined as static so it stores values randomWalk is a variable that stores a value in the function
// Between function calls with this variable remaining local and only accessed by this function

place = place + (random (-moveSize, moveSize + 1));

if (place <randomWalkLowRange) {// Check the upper and lower limits


place = randomWalkLowRange + (randomWalkLowRange - place); // Reverses the number in the opposite
direction to the positive direction

}
else if (place> randomWalkHighRange) {

41
place = randomWalkHighRange - (place - randomWalkHighRange); // Reverses the number in the opposite
direction to the negative direction
}

return place;
}

Keyword volatile in Arduino

The keyword volatile is categorized under 'variable qualifier', and is usually used before the variable type when it is defined to
modify the way the banker and the subsequent program treat this variable.

The key word volatile, when used to define a variable, is a directive for the banker itself. The banker is a program that
converts the C / C ++ code into an executable code that the hardware understands; this code contains actual commands for the
controller on the Arduino board telling him what to do.

What the volatile keyword does with the variable is to direct the banker to load the variable from RAM and not from the flash
memory records where all program variables are stored. In some cases, the value stored in the recorders for a variable may be
inaccurate.

The variable must be defined with the keyword volatile whenever its value can be changed by anything beyond the control of
the code fragment within which this variable appears (such as simultaneously executing a string). In Arduino, the only place
where this is likely to happen is the district-related code fragments called the ISR programs.

Volatile or long volatile integers?

If you use the word volatile with a variable that is larger than one byte (2 bytes as an integer, 4 bytes as a long number, etc.),
the controller will not be able to read it in one step because the controller architecture is often 8 bits (make sure the
architecture is Control panel). This means that while the first eight bits of the variable are read in a part of the code (such as
the loop), the interrupt may have already changed the other eight bits (if the variable size is 16 bits). This will get a random
value for the variable.

The solution to this problem is to disable interrupts while reading variable values, so that the values of the variable bits do
not change as they are read. There are several ways to do this:

Use the noInterrupts () function to disable interrupts, or


The use of the block ATOMIC_BLOCK, where atomic operations are single operations performed by the controller (MCU)
and represents the smallest possible unit.

Examples

Switch the state of the connected foot with LED light when an interrupt occurs on foot 2:

int pin = 13;


volatile byte state = LOW;

void setup ()
{
pinMode (pin, OUTPUT);
attachInterrupt (digitalPinToInterrupt (2), blink, CHANGE);
}
42
void loop ()
{
digitalWrite (pin, state);
}

void blink ()
{

state =! state;
}

43
Chapter IV
Control structures

44
Keyword break in Arduino

The break keyword is used to get out of loops for, while, or do ... while iterative, bypassing the next code and the specified
loop conditions and exiting them. Also used to exit the programmatic switch ... case expression.

General structure

break;

Examples

In the following code, the controller exits the for loop when the measured sensor value exceeds a certain threshold:

for (x = 0; x <255; x ++)


{
analogWrite (PWMpin, x);

sens = analogRead (sensorPin);


if (sens> threshold) {// Ensure that the measured value does not exceed the threshold
x = 0;

break;
}
delay (50);

45
Continue keyword in Arduino

The continue key passes the next code in the iteration loop (such as for, while, or do ... while iterations) to check the
conditional expression of that loop and then the loop loop is resumed normally. Making this statement is similar to making a
jump in the loop to skip execution when a certain condition is met.

General structure

continue;

Examples
In the following code, the value 0 to 255 will be written on the foot PWMpin with skipping the values in the range 41 to 119:

for (x = 0; x <= 255; x ++)


{
if (x> 40 && x <120) {// Causes a jump in values

continue;
}

analogWrite (PWMpin, x);


delay (50);
}

46
Loop do ... while iterative in Arduino

The iterative do ... while loop works the same as the while loop except that the condition is checked at the end of the loop, not
at the beginning. This means that the loop will be executed at least once.

General structure

do

{
// The code block to be executed
} while (condition);

A condition is a logical expression and will be evaluated as either true or false.

Examples

An example of using the do ... while loop to read a value from a sensor and waiting for it to reach a certain limit:
do
{

delay (50); // Wait for the sensor value to stabilize


x = readSensors (); // Read the value of the sensor

} while (x <100);

47
Keyword else in Arduino

The conditional if ... else expression allows more control over the sequence of validating several specific conditions when
executing the code rather than verifying a single condition when using the if expression. The else statement (if any) will be
executed if the condition given in the if statement is not met. You can also use the else statement with the if statement as else
if to add another condition to verify, so that several consecutive checks can be performed at the same time.

If there are several conditions to be verified, it will be met from the first condition and then from the next condition if it
returns false and so on until one of the conditions is met (ie returns true). When the condition is met, the associated block will
be executed and the program will skip the entire if / else structure to the next line. If no condition is met, the default else
block will be executed if it eventually occurs.

Note that the else if block may be used with or without the else block at the end and vice versa. The number of times the use
of the else if block in any conditional expression is unlimited.

General structure

If (Condition 1)

// Do the thing a

else if (Condition 2)

// Do the thing b

else

// Do the thing c

Examples

The following code is part of the temperature sensing system code:

if (temperature> = 70)

// Danger! Stop the system

else if (temperature> = 60 && temperature <70)

// Warning! You must send signals to alert the user

else

// Safety! Complete the normal tasks

Episode for iterative in Arduino

The for loop is used to duplicate a specific block of code a specified number of times. In this loop, a counter is usually used to
track the number of times the code is duplicated and interrupted when a specified number is reached. The for loop can be used
with any iteration, and is frequently used with arrays to perform a particular operation on elements that may be normal data or
specific legs.

General structure

48
for (step; condition; initial configuration) {
// code block to be replicated;

Initialization is performed only once at the start of loop execution. The condition is checked every time the loop is repeated; if
true, the block that falls within the loop will be executed, then the step will be executed and the condition will be re-checked.
When the condition is not met (that is, the value becomes false), the loop stops working.

Examples

The following code is part of the temperature sensing system code:

int PWMpin = 10; // LED light connected to sequence with 10 ohm impedance of 10 foot

void setup ()
{
// This example does not require any configuration
}

void loop ()
{
for (int i = 0; i <= 255; i ++) {
analogWrite (PWMpin, i);
delay (10);
}
}

Notes and warnings

The for loop in C is more flexible than for loops in some languages such as BASIC. One or all of the three main elements can
be removed from the loop, keeping the semicolon intact. In addition, the initialization, condition, and step expressions can be
any valid C language expressions with unrelated variables, and can use any of the data types in C, including decimals. Using
these unusual types of expressions with the for loop provides a solution to some rare software problems.

For example, using the multiplication in the expression step will generate a logarithmic progression such as:
for (int x = 2; x <100; x = x * 1.5) {
println (x);
}

This code will generate the following steps:

2,3,4,6,9,13,19,28,42,63,94

Another example of lighting up and gradually turning off LED light with just one ring:
void loop ()

int x = 1;

for (int i = 0; i> -1; i = i + x) {

analogWrite (PWMpin, i);

49
if (i == 255) x = -1; // Switch the direction of the step when the peak is reached

delay (10);

50
Goto keyword in arduino

The keyword goto moves the program to a specific position within the code.

goto label; // Send the program to execute the code block


// label found at the label

Examples

Example of using goto:

for (byte r = 0; r <255; r ++) {


for (byte g = 255; g> 0, g -) {
for (byte b = 0; b <255; b ++) {

if (analogRead (0)> 250) {goto bailout;}


// Something can be added here
}

}
}

bailout:

Notes and warnings

The goto statement is no longer used in C, and in some C programming textbooks it is stated that the goto statement is no
longer necessary but can be used to simplify some programs. The reason why programmers are reluctant to use the goto
statement is that when they are overlooked, a program with an unknown execution path will be created, making it almost
impossible to track and correct errors.

On the other hand, there are situations where the use of the word goto is useful and greatly simplifies the code. One of these
cases is a fork loop fragmentation or a conditional if block at certain conditions.

51
Expression if conditional in Arduino

The conditional if expression verifies a given condition and executes the code block written within it if it is true (ie its value is
true).

General structure

if (condition)
{

// The block of code to execute when the condition is met


}

A condition is a logical expression whose value is either true or false.

Examples

An example of using the conditional if expression in multiple formats:

if (x> 120) digitalWrite (LEDpin, HIGH);

if (x> 120)

digitalWrite (LEDpin, HIGH);

if (x> 120) {digitalWrite (LEDpin, HIGH); }

if (x> 120) {

digitalWrite (LEDpin1, HIGH);

digitalWrite (LEDpin2, HIGH);

Notes and warnings

The given terms may require the use of one of the following parameters.

Budget transactions

x == y (y is equal to x)

x! = y (y is not equal to x)
x <y (y is exactly smaller than x)
x> y (y is exactly greater than x)

x <= y (y is smaller or equal to x)


x> = y (y is greater than or equal to x)

Be careful not to use only one equal sign (e.g. if (x = 10)). Equals (such as if (x == 10)), which in this case is a equilibrium
coefficient and checks if the value of the variable x is equal to or not. The value of the last expression will be true if the value
of the variable x is 10, while the value of the previous reference expression is always true.
The explanation of how C evaluates the expression if (x = 10) with true is always that C assigns the value 10 to the variable x
(remember that a single equal sign is an attribution operator and has been used in error). The conditional if expression then
evaluates the value 10 - which becomes the value of the variable x - as always true because the logical evaluation of any non-
zero number is always true. Consequently, the conditional if (x = 10) expression will be assessed as verified and the result will
be contrary to the expectations expected at that time. In addition, the variable x will be set to 10, which is also not desirable
52
53
Keyword return in Arduino

The return keyword intersects the execution of any function and returns a value from the function to the one who called it if
specified.

General structure

return;

return value; // value In this format, the value will be returned

The returned value can be any type of variable or constants to be returned to the one who called the function.

Examples

The following example demonstrates how to create a function to balance the measured value of a sensor with a specific
threshold:

int checkSensor () {

if (analogRead (0)> 400) {

return 1;

else {

return 0;

The following example shows how to use the return keyword to examine a portion of the code without resorting to the
comment method:

void loop () {

// This part of the code is checked

return;

// The part here which will not be implemented

// The error is probably within it

54
Expression switch ... case in Arduino

The switch ... case, as in if, verifies a specified value in a way that allows the programmer to specify several codes, one of
which is executed based on that value. In more detail, the switch ... case balances the value of a variable with the values
specified within it; when the value of that variable matches one of the values or expressions within it, the block associated
with that value or expression will be executed.

The break keyword is usually used at the end of each state of the switch ... case to exit it after matching the state and
executing the associated block. If the key break is not used in that case, the switch ... case will continue to examine the
conditions and execute the associated blocks until the break is reached or at the end.

General structure

switch (var) {

case label1:

// The first code that will be executed when the first case is matched

break;

case label2:

// The second code will be executed when the second case is matched

break;

default:

// The default code that will be executed when no case matches

// This case is optional

Transactions

var
The variable to balance its value with multiple values (states). Allowed data types are: Integer, typeface.

lable1
The first constant that will be balanced with var. Allowed data types are: Integer, typeface.

lable2
The second constant that will be balanced with var. Allowed data types are: Integer, typeface.

Examples

An example of using the switch ... case expression to balance a variable value and execute a code as appropriate:
switch (var) {

case 1:

// Value 1 var Do something when it equals

break;

case 2:

// Value 2 var Do something when it equals

break;

default:

// with any of the previous values var do something if it doesn't match

break;

55
While iterative episode in Arduino

The loop repeats while executing the code block within it continuously and infinitely as long as the value of the logical condition in parentheses is true (see the general
evidence); once the value of the logical condition becomes false, the loop stops and exits. Any change in the value of the condition must occur otherwise the loop will
never come out, so the value of the variable that is checked within the logical condition must be increased or decreased, or an external condition such as checking a
sensitive value or the like must be used.

General structure

while (condition) {

// block to be duplicated

Transactions

condition

A logical expression whose value is either true or false.

Examples

An example of using the while expression to repeat the execution of a code a certain number of times:

var = 0;

while (var <200) {

// The code written here will be repeated 200 times

var ++;

56
Chapter V
Functions

Digital foot control functions in Arduino

57
The digitalRead () function in the Arduino

The digitalRead () function reads the value of a numeric foot that is either HIGH or LOW.

General structure

58
digitalRead (pin)

Transactions
pin
A number indicating the digital man whose value is to be read.

Returned values
Returns the HIGH or LOW value representing the numeric pin foot value.

Examples
Set the value of foot 13 to the same value of foot 7 defined as input foot:

int ledPin = 13; // There is a LED light connected to the 13 foot digital
int inPin = 7; // Push button connected to 7 digital foot

int val = 0; // Changer to store the read value

void setup ()

{
pinMode (ledPin, OUTPUT); // 13 digital foot set as the output foot
pinMode (inPin, INPUT); // Set the 7 foot digital as the entered foot

void loop ()

{
val = digitalRead (inPin); // Read the income blood
digitalWrite (ledPin, val); // Adjust the light status to the value of the button

Notes and warnings

If you don't connect the foot with anything, the digitalRead () function can return either HIGH or LOW (this may change
randomly).
Similar input feet can also be used as digital feet, then referred to as A0, A1, etc.

59
The digitalWrite () function in the Arduino

The digitalWrite () function writes either the HIGH value or the LOW value on a specific numeric leg.

If the man is configured as an output (ie, OUTPUT) via the pinMode () function, that man's voltage is set to the corresponding
value: 5V (or 3.3V in 3.3V panels) for HIGH, or 0V (ground) for LOW.

If the man is configured as an INPUT, it will activate (with HIGH) or disable (with LOW) the digitalWrite (internal pullup
resistor) function associated with that input man. It is recommended that you use the INPUT_PULLUP value with the
pinMode () function to directly activate the internal lifting resistance. See the "Digital Legs Tutorial" for more information.

If you do not configure a man to OUTPUT via the pinMode () function and connect a LED light with it, the LED light may
appear dim when calling digitalWrite (HIGH) with this guy. Without explicitly configuring the man via the pinMode ()
function, digitalWrite () will activate the internal lifting resistance that will regulate the large current flowing then.

General structure

digitalWrite (pin, value)

Transactions
pin

A number indicating the numeric man on which to write the value.

value

The HIGH or LOW value to be written to the pin man.

Returned values

Nothing is returned.

Examples

Set the digital 13 man mode to the output man and then invert its value from HIGH to LOW and vice versa every one second:

void setup ()
{

pinMode (13, OUTPUT); // 13 digital man set it as a man came out


}

void loop ()
{
digitalWrite (13, HIGH); // HIGH Adjust the value of 13 digital man to

delay (1000); // Waiting for one second to pass


digitalWrite (13, LOW); // LOW Adjust the value of the 13 digital man to
delay (1000); // Waiting for one second to pass
}

60
Notes and warnings
Similar input legs can also be used as digital legs, then referred to as A0, A1, etc.

61
The pinMode () function in the Arduino

The pinMode () function prepares a specific leg to perform either an input or output behavior. See the "Digital Legs Tutorial"
for more information about leg functions.

Starting with the Arduino version 1.0.1, it became possible to activate the internal lifting resistance by using the mode
INPUT_PULLUP. In addition, the INPUT mode automatically disables internal lifting resistors.

General structure
pinMode (pin, mode)

Transactions
pin
A number indicating the digital man to be configured to mode.

mode
The mode that determines the pin's behavior is either INPUT, OUTPUT, or INPUT_PULLUP. A full explanation of the
behavior and functions of digital legs can be found on this page.

Returned values
Nothing is returned.

Examples
Set the digital 13 man mode to the output man and then invert its value from HIGH to LOW and vice versa every one second:

void setup ()
{
pinMode (13, OUTPUT); // 13 digital man set it as a man came out

void loop ()

{
digitalWrite (13, HIGH); // HIGH Adjust the value of 13 digital man to
delay (1000); // Waiting for one second to pass

digitalWrite (13, LOW); // LOW Adjust the value of the 13 digital man to
delay (1000); // Waiting for one second to pass
}

Notes and warnings


Similar input legs can also be used as digital legs, then referred to as A0, A1, etc.

62
Time functions in Arduino

The functions in this section deal with times and times, for example, to create time delays with a certain value that some tasks
require, or to perform a specific process when a specific time period has passed since the board started.

The delay () function in the Arduino

The delay () function pauses program execution for a specified period of time (in milliseconds).

General structure

delay (ms)

Transactions

ms

An unsigned long number represents the time in milliseconds during which the program is paused.

Reminder: There are 1,000 milliseconds per second.

Returned values

Nothing is returned.

Examples

Use the delay () function to pause the program from working for one second before reversing the output case connected to
LED light:
int ledPin = 13; // LED light connected to the man 13

void setup ()
{
pinMode (ledPin, OUTPUT); // As a man led out ledPin initialize the man

void loop ()

{
digitalWrite (ledPin, HIGH); // turning the light on
delay (1000); // Wait for one second

digitalWrite (ledPin, LOW); // Turn off the light


delay (1000); // Wait for one second
}

Notes and warnings

Although it is very easy to create a flashing LED light with the delay () function and many codes use this function to create
time delays required by some tasks - such as using them to avoid the problem of button bounce when pressed (button
debouncing) - but using the delay () function In the code is accompanied by a lot of disadvantages. During the execution of
the delay process when calling the function, the sensors' values will not be read, the calculations will not be performed, and
the condition of any man will not be modified or controlled ... etc., so calling this function will interrupt the rest of the tasks
and operations and stop them for a period of time. Instead, look at the millis () function and the example below to handle time
63
delays and control timing effectively. Experienced and knowledgeable programmers usually avoid using the delay () function
to delay events and control their timing when the delay period exceeds a few tens of milliseconds unless the written code is
very simple.

Some things continue to work during Atmega's delay () control, such as interrupts, as this does not disrupt it. The RX
receiver's serial communication is also recorded, the PWM values (written using analogWrite ()) and the leg condition are
preserved, and the interrupts continue to work as desired.

Arduino delayMicroseconds () function

The delayMicroseconds () function pauses program execution for a specified period of time (in seconds). Currently, the
largest value giving an accurate time delay is 16383. This value can change in future Arduino versions. The delay () function
should be used instead of this function for time delays longer than a few thousand microseconds.

General structure

delayMicroseconds (us)

Transactions
us
An unsigned int integer represents the time in the microsecond to which the program is paused.

Reminder: There are 1,000 microseconds per millisecond, and 1,000,000 microseconds every 1 second.

Returned values
Nothing is returned.

Examples
The following code prepares the 8th man to act as an outgoing man. The man then transmits a series of pulses of
approximately 100 microseconds in length. You should focus on the word "almost" because the time is absolutely inaccurate
and this is due to the loss of some time in the implementation of other commands and instructions in the code:

int outPin = 8; // Label Man 8

void setup ()

64
pinMode (outPin, OUTPUT); // As a man came out outPin create the man

void loop ()

digitalWrite (outPin, HIGH); // Make the man's condition high

delayMicroseconds (50); // Pause for 50 microseconds

digitalWrite (outPin, LOW); // Make the man's condition low

delayMicroseconds (50); // Pause for 50 microseconds

Notes and warnings

This function works with absolute accuracy in the range between 3 microseconds and above. The delayMicroseconds ()
function cannot be guaranteed to work accurately for time delays smaller than that value.

Starting with version 0018, the delayMicroseconds () function no longer disables interrupts.

Arduino micros () function

The micros () function returns the Arduino board runtime of the current program in microseconds.

The value calculated by this function will reach the state of rash (i.e. it will return to zero) after about 70 minutes have passed.
On Arduino 16MHz boards (such as Duemilanove, and Nano), the accuracy of this function is 4 microseconds (that is, the
value that the function returns is always a multiple of 4). On Arduino boards running at 8 MHz (such as LilyPad), the
accuracy of this function is 8 microseconds.

General structure
time = micros ()
Returned values
Returns an unsigned long number representing the startup time of the current program's Arduino board to the moment the
micros () function is called.

Examples
Use the micros () function to find out how long the Arduino board started:
unsigned long time;

void setup () {

Serial.begin (9600);
}
void loop () {
Serial.print ("Time:");

time = micros ();

Serial.println (time); // Print the duration of the program since it started working
delay (1000); // Wait for one second not to send a huge amount of data
}

Notes and warnings

65
Remember: there are 1,000 microseconds in every one millisecond, and there are 1,000,000 microseconds in every single
second.

Arduino millis () function

The millis () function returns the Arduino board runtime for the current program in milliseconds.

The value that this function calculates will reach the overflow state (i.e., it will return to zero) after approximately 50 days.

General structure
time = millis ()
Returned values
An unsigned long number representing the start time of the current program's Arduino board is returned to the moment the
millis () function is called in milliseconds.

Examples
Use the millis () function to find out since when the Arduino board started working:
unsigned long time;

void setup () {
Serial.begin (9600);
}
void loop () {
Serial.print ("Time:");
time = millis ();

Serial.println (time); // Print the duration of the program since it started working
delay (1000); // Wait for one second not to send a huge amount of data
}

Notes and warnings

Please note that the type of value returned by the millis () function is an unsigned long number, so logical errors may occur if
the programmer tries to perform math operations with smaller types of numbers, such as int. Even calculations with a signed
long number can result in errors because its maximum capacity is half that of the corresponding non-reference number.

66
67
Mathematical Functions in Arduino

Mathematical functions generally deal with numbers, as they perform various mathematical operations on them, such as
calculating an absolute value, number root, sine, or random number generation.

() Abs
The abs () function calculates the absolute value of the number passed to it.

Constrain ()
The constrain () function limits a number within a specified field.

() Cos
The cos () function calculates the angle passed to it.

() Map
The map () function repositiones a number from the domain in which it is to another domain.

() Max
The max () function returns the largest value passed to it.

() Min
Min () returns the smallest value passed to it.

() Pow
The pow () function calculates the value yx, that is, raises the base y to the power x of the two values that are passed to it.

Random ()
The random () function generates and returns a pseudo-random number.

() Randomseed
The randomSeed () function creates the seed that the pseudo-random numbers generator uses in the generation process.

() Sin
The sin () function calculates the sine of the angle passed to.

() Sq
The sq () function calculates the number of squared (multiplied by the number itself) and returns it.

Sqrt ()
The sqrt () function calculates the square root of the number passed to it.

() Tan

The tan () function calculates the tangent of the angle passed to.

68
Handling and verifying typefaces in Arduino

These functions generally work with characters, verifying that a particular character belongs to a particular set of characters.

isAlpha ()

The isAlpha () function checks if the passed character is an alphabetical character.

isAlphaNumeric ()

The isAlphaNumeric () function checks if the character passed to it is an alphabetical character or a number.

isAscii ()

The isAscii () function checks if the character passed to it is one of the Ascii characters.

isControl ()

The isControl () function checks if the passed character is a control character.

isDigit ()

The isDigit () function checks if the passed character is a number.

isGraph ()

The isGraph () function checks to see if the typeface passed to it is printable and contains some visible content (the blank is
printable but does not have visual content).

isHexadecimalDigit ()

IsHexadecimalDigit () verifies if the character passed is a hexadecimal digit (hexadecimal digit); that is, it is between A-F or
9-0.

isLowerCase ()

The isLowerCase () function checks if the character passed to it is passed a lower case alphabetical character.

isPrintable ()

IsPrintable () checks to see if the passed character is printable (i.e. one of the characters that produces any output even if it is
blank).

isPunct ()

The isPunct () function checks if the typeface passed to it is a punctuation mark (i.e. is the typeface comma, semicolon,
exclamation mark, etc.)?

isSpace ()

The isSpace () function checks if the character passed to it is a space.

isUpperCase ()

The isUpperCase () function checks if the character passed to it is a lower case alphabetical character.

isWhitespace ()
The isWhitespace () function checks if the character passed to it is a white space.

69
Arduino conversion functions

Conversion functions convert between different types of data in Arduino.

byte ()

The byte () function converts the value passed to it byte type.

char ()
The char () function converts the passed value to the char type.

float ()

The float () function converts the value passed to it (float).

int ()

The int () function converts the passed value to the integer type.

long ()

The long () function converts the value passed to the type “long”.

word ()

The word () function converts the passed value to the word type.

70
Provincial control functions in Arduino

The functions in this section control the districts in Arduino, activating or disabling a specific interruption on a leg, or
activating or disabling all interrupts.

Attachinterrupt ()

The attachInterrupt () function activates a specific external interrupt on one of the legs in the arduino board.

() Detachinterrupt

The detachInterrupt () function disables a specific external interruption associated with one of the legs of the Arduino board.

() Interrupts

The interrupts () function deactivates interrupts after stopping it by calling the nointerrupts () function.

() Nointerrupts

The noInterrupts () function disables all interrupts in the Arduino board.

71
Chapter VI
Additional tools

72
The keyword programm in Arduino

The keyword PROGMEM is used with variables when its data is to be stored in program memory (flash memory) rather than
in SRAM. For more information about the types of memory available in Arduino, see this page.

The keyword PROGMEM is categorized under 'variable qualifier' and should be used only with the data types defined in the
pgmspace.h library. This word tells the banker to place the variable data that you used with it in flash instead of in SRAM
where it should be stored in the normal state.

The PROGMEM keyword is part of the library pgmspace.h. This disc is automatically included in recent versions of the
Arduino IDE. However, if you are using a version earlier than 1.0 (2011), the library must be manually included at the
beginning of your code using include #:

#include <avr / pgmspace.h>

General structure

const dataType variableName [] PROGMEM = {data0, data1, data3…};

DataType represents any type of data, and variableName is the name of the array of data to be stored in flash memory. Be
aware that since the key word PROGMEM is constrained to a variable, there is no rule that requires it to be in a specific place
while declaring a variable; However, some tests have suggested that PROGMEM, in different versions of Arduino (which
uses the Gulf banker), may work in a specific location only when declaring a variable. The second example is tried in the
examples section in the Arduino 13 version; the example might work better in earlier versions if PROGMEM is placed after
the variable name.

const dataType variableName [] PROGMEM = {};

const PROGMEM dataType variableName [] = {};


const dataType PROGMEM variableName [] = {};

Since it is possible to use the keyword PROGMEM with one variable, it is better to use it with an array (or any similar
structure in C to store data, whether mentioned in this documentation or not) to contain the data to be stored in flash memory
if this data is large.
Using PROGMEM requires a two-step procedure. After storing the data in the flash memory (the first step), special functions
(functions) defined in the pgmspace.h library must be used in order to read this data from the program's memory and put it in
the SRAM, so we can take advantage of this data and use it.

Examples

The following code shows how to write data to flash memory and then read it again:
// Memorize some integerless numbers
const PROGMEM uint16_t charSet [] = {65000, 32796, 16843, 10, 11234};

// Save some characters

73
const char signMessage [] PROGMEM = {"I AM PREDATOR, UNSEEN COMBATANT. CREATED BY THE UNITED
STATES DEPART"};

unsigned int displayInt;


int k; // counter variable
char myChar;

void setup () {

Serial.begin (9600);
while (! Serial); // Waiting for serial port connection

// Type here anything you want to configure and execute it once


// Re-read whole numbers
for (k = 0; k <5; k ++)
{
displayInt = pgm_read_word_near (charSet + k);
Serial.println (displayInt);
}
Serial.println ();

// Re-read the characters


for (k = 0; k <strlen_P (signMessage); k ++)
{
myChar = pgm_read_byte_near (signMessage + k);
Serial.print (myChar);
}

Serial.println ();
}

void loop () {
// Write here your program to execute it frequently

}
When working with a large amount of text, such as having a project on the LCD, it is a good idea to create and configure an
array of text strings to store them. Since text strings themselves are arrays, a 2D matrix must be used. The following example
illustrates the idea of placing large data in program memory:
/*

PROGMEM string demo


How to store a table of strings in program memory (flash),
and retrieve them.

Information summarized from:


http://www.nongnu.org/avr-libc/user-manual/pgmspace.html

Setting up a table (array) of strings in program memory is slightly complicated, but

74
here is a good template to follow.

Setting up the strings is a two-step process. First define the strings.


*/

#include <avr / pgmspace.h>


const char string_0 [] PROGMEM = "String 0"; // is the string to store. Others to suit your "String 0" series
const char string_1 [] PROGMEM = "String 1";

const char string_2 [] PROGMEM = "String 2";


const char string_3 [] PROGMEM = "String 3";
const char string_4 [] PROGMEM = "String 4";

const char string_5 [] PROGMEM = "String 5";

// Then create a table that points to these strings

const char * const string_table [] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

char buffer [30]; // Make sure that this matrix is large enough to accommodate the largest text string

void setup ()
{
Serial.begin (9600);
while (! Serial); // Wait for the serial port to connect
Serial.println ("OK");
}

void loop ()
{
/ * Requires the use of a strings table in memory
Use special functions to retrieve data

A text string from the strcpy_P program memory copies the function
(In our case buffer is the variable memory)
Big enough RAM Make sure that the portion is reserved in memory
To recover data from program memory
*/

for (int i = 0; i <6, i ++)


{
strcpy_P (buffer, (char *) pgm_read_word (& (string_table [i]))); // Necessary casts and dereferencing, just copy.

Serial.println (buffer);
delay (500);
}
}

75
Notes and warnings
Please note that the variables must be either general variables or static local variables (defined using the keyword static) in
order to use the word PROGMEM with it.

The following example will not work when placed into a variable:

const char long_str [] PROGMEM = "Hi, I would like to tell you a bit about myself. \ n";

While the following declaration will work for a variable if it is defined locally within a function:

const static char long_str [] PROGMEM = "Hi, I would like to tell you a bit about myself. \ n"

Extended call F ()

When something like:

Serial.print ("Write something on the Serial Monitor");

The text string to be printed normally stored in RAM. If your code prints a lot of scripts on the serial port, it will fill memory.
If you have flash space, you can easily invest it by storing these texts in it by using the following formula:

Serial.print (F ("Write something on the Serial Monitor that is stored in FLASH"));

Chapter VII
Proteus

In this chapter, we will carry out the first experiment, which is lighting and extinguishing the LED repeatedly. To ensure that
all concepts and steps are linked to each other, we will explain all the steps starting from how to create a project on Proteus to
extracting a Hex file that will be used to program Arduino in addition to running the experiment and observing the results.
Also, the step-by-step explanation will be covered.

Circle design on proteas

1. Open Proteus 8 and choose new project.

2. Type the project name and filing location, then click Next.
76
3. Choose Create schematic from templates, then choose template (default).
. Choose do not create pcb as shown then choose Next.

5. Although there is a platform on Proteus to write and implement Arduino codes, I prefer to use the main Arduino program,
so choose the option specified in the following way.

6. This is the project summary, we will create only schematic. After pressing Finish we will be ready to place the devices and
connect them together.

7. We will choose three devices, namely

Arduino UNO
220 ohm resistance
RED LED

The following steps explain how to choose the UNO and place it on the list of devices that will be used in the design. In the
same way, choose RED LED and 220ohm resistance.

9. The following example shows how to place the Arduino on the schematic space. In the same way, follow the following
steps and put the resistance and the LED.

10. After placing all the devices on the asmatic and connecting the ends, we will have the following shape.

. What is missing now until the circle is complete? There is no doubt that it is the Ground. To choose the Ground, follow the
steps illustrated below. Thus, we have completed the connection settings for the circuit on the protein program.

Note:

Arduino board does not need to be connected to the power or even ground, because Proteus does this process implicitly for
you.

Writing the code on the Arduino program

1. Open the Arduino program, open a new project, write the following code, then save the project with the name
E1_LED_Blinking

const int LED_Pin = 13;

void setup () {

// put your setup code here, to run once:

77
pinMode (LED_Pin, OUTPUT);

void loop () {

// put your main code here, to run repeatedly:

digitalWrite (LED_Pin, HIGH);

delay (1000);

digitalWrite (LED_Pin, LOW);

delay (1000);

Code explanation:

The code begins by announcing the variables that are used within more than one scope of the program. The "Scope" is the
term enclosed in parentheses of type {}. So we started by announcing the LED_Pin variable which was used inside the setup
and loop. The const command is used to ensure the value of the variable is not changed again, and since the LED_Pin variable
retains the value of the port number, it must not be changed again. We note that the value 13 has been assigned to the
LED_Pin variable, because we have connected the LED to port number 13. Inside the setup, the port type (port) will be
defined if it is output or input via the PinMode function. Inside the loop, the code that is repeated continuously will be written
non-stop. The code inside the loop starts with the line (digitalWrite (LED_Pin, HIGH), which means output 5 volts to the port
called LED_Pin, after that we notice the delay (1000) line, which means that the code will remain the same for a period of 1
second, then we notice the presence of the line (digitalWrite) LED_Pin, LOW through which 5 volts will be prevented from
passing to port 13 and to ensure the continuity of the LED stops lighting for a period of 1 second had to put (delay) 1000 at
the end of the loop also. If through the code inside the loop it will light LED for one second and it will turn off for one second
and so it will continue without stopping.

2. Make a verification of the code by pressing the button shown in the figure to make sure that the code does not contain any
errors.

3. If the code is correct, you will see a message similar to the following message under the Arduino program.

4. After making sure that the code is free from any errors, go to the sketch menu and choose Export compiled Binary. This is
to extract the hex file. Which is used to program the microcontrollers.

. Going to the folder in which the project was saved, you will find a .hx file. With the same name as the project.

6. Return to the circle in Proteus, press Arduino to add the script file as shown in the following steps.

7. Turn on the circuit and notice how the LED lights up and then turns off repeatedly.

8. Try to change the delay time to 500 instead of 1000, perform steps 2 through 7, and note the difference.

Debate

Suppose you write the code in the following image and ignore the delay delay after the digitalWrite (LED_Pin, LOW). What
do you expect to happen in this case?

const int LED_Pin = 13;

78
void setup () {
// put your setup code here, to run once:
pinMode (LED_Pin, OUTPUT);
}

void loop () {
// put your main code here, to run repeatedly:
digitalWrite (LED_Pin, HIGH);

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

So let us do the implementation process, we will start from the loop and then we will put 5 volts on the port called LED_Pin
which is originally port number 13. Then we will go to the second line to implement it and we find delay by 1000 and since
the delay function deals with the values in milliseconds then this This means that the delay will continue for a period of 1
second, and this delay will remain on the last state the micro was on, so the LED will be lit for a period of 1 second, that is,
until the delay command ends. Now we are going to execute the third line which contains the command (digitalWrite
(LED_Pin, LOW) in which the LED will be turned off. Well the LED has turned off now but then what? Focus on me well
here we are inside the loop function and therefore the code will start executing again from the first A line inside the loop in
which the command that will output 5 volts to the LED and it will illuminate again! Here lies the problem where the last line
will be executed and immediately after it the first line will be executed and on it the eye will not be able to notice that the
LED has gone out because the implementation of the code is calculated in microseconds for that The delay had to be put after
the command that required the LED to be turned off.

Chapter VIII

Matrices and loops for and condition if to control LEDs

In this lesson we will control four LED lights, each lamp will be controlled by push button. What we will learn here is how to
put the ports connected with the LEDs in one variable is an Array, and the same for the switches will also be placed in one
array. In this way the code will be shorthand and more professional. The lesson also discusses how to use the for loops to
access the elements of an array and the values saved in them. Also, it will explain how to execute an order based on the
fulfillment of a specific condition.

79
Circle design on Proteus

Open Proteus and design the circle as shown in the following figure

Explanation of the circuit

Four push buttons were connected with the Arduino ports from port number 1 to port number 4, the ports were set to internally contain a pull-up resistance so there
would be no need to connect resistors or voltage sources with the push buttons and therefore it will work through the inverse logic When a specific button is pressed,
that port will read the logic LOW, and when a button is not pressed, that port will read the logic HIGH and this is what should be considered in the code (you can
review Lesson Six, there is a complete experiment to understand this method). For LEDs, they are connected to ports 9 through 12 via a resistance of 220 ohms used to
reduce current. In the code we will make each button illuminate only one LED.

Writing the code on the Arduino program

Write the following code on the Arduino program then extract the Hex file and program the Arduino as described in Lesson 4.

int pushButtons [4] = {1,2,3,4};

int ledPins [4] = {9,10,11,12};

void setup () {

// put your setup code here, to run once:

for (int i = 0; i <4; i ++)

pinMode (pushButtons [i], INPUT);

pinMode (ledPins [i], OUTPUT);

digitalWrite (pushButtons [i], HIGH); // activate pullup resistor

void loop () {

// put your main code here, to run repeatedly:

for (int i = 0; i <4; i ++)

int val = digitalRead (pushButtons [i]);

if (val == 0)

digitalWrite (ledPins [i], HIGH);

else

digitalWrite (ledPins [i], LOW);

Code explanation

The code begins with defining global variables that will work within the setup and loop fields. We defined two matrices of the integer type, each matrix consists of four
elements. In the first matrix, which is called pushButtons, the port numbers connected with the pushButtons are assigned, and they are ports 1 through 4. Likewise, for
the second matrix, which is called ledPins, the port numbers connected to the LEDs were placed inside The array, which is ports 9 through 12. We have to note that
after the name of the array, the number of elements of the array is enclosed in parentheses such as [4].

int pushButtons [4] = {1,2,3,4};

int ledPins [4] = {9,10,11,12};

As for the code inside the setup area, as we previously learned, it is often used to set the position of ports so that they are either in the input or output state. But before
explaining the code in the setup field, we will first discuss some of the basic concepts related to matrices.

The numbering of the elements inside the matrices begins with the number 0, for example the first element in the ledPins array is [0] ledPins which contains the value 9
and from this we conclude that the second element in the array is element number 1 and so on. So [0] ledPins is a variable that contains the value 9, and if we call it at
any time, it means that we called the value inside of it which is 9 unless it is changed. Since port number 9 is connected to an LED, it must be set to function as an
output port, the following code explains this step:

80
pinMode (ledPins [0], OUTPUT);

Notice that the number 0 is inside the ledPins matrix, which indicates element zero, which has a value of 9. Now we want to set all ports from 9 through 12 in order to
work as output ports because they are connected with LEDs. We can do this through the following code inside the setup function.

void setup () {

pinMode (ledPins [0], OUTPUT);

pinMode (ledPins [1], OUTPUT);

pinMode (ledPins [2], OUTPUT);

pinMode (ledPins [3], OUTPUT);

In the above code we have called the pinMode function on each line to set the ports to work either in the case of the output or the input, the input (Arguments) that will
be passed to the function is the port number and the state that must work on it (input / output), and since we deal with the connected ports With LEDs, the status will
always be the output. As for port numbers, they were previously defined inside the ledPins array, so on each line the name of the array along with the element number
will be placed inside the pinMode function. This code is true one hundred percent, but it lacks professionalism and explains that its writer is a little weak with
programming, but why? Imagine if the number of ports inside the array is 10, this means that we will write 10 lines to define the port type to act as the output port. But
what is the professional way? It is best to use iterative loops to shrink the code and make it more professional and flexible. We will be using the for loop as shown in the
following code.

for (int i = 0; i <4; i ++)

pinMode (ledPins [i], OUTPUT);

In the above code, we used the for loop and inside the definition of for, we defined the variable i, which is of the integer type, and we assigned the initial value to it 0
because the first element in the array starts with zero. Now let's implement for loop together. In the first cycle, the value of i will be equal to 0. This value will be
compensated inside the code inside the for loop field, so the code will be as follows (pinMode (ledPins [0], OUTPUT), after executing all the code inside the field of for
loop The for will implement the partial code that will affect the value of i and in this code is ++ i, which means that the variable i will become its value equal to one,
now the for will test the condition i <4 and certainly the condition will be met because the value of i now is one and it is actually less Of 4. And since the condition is
met, we can now execute what is inside the for loop, and this time do not forget that the value of i has become one, so the variable will be compensated To enter pin to
become the pinMode (ledPins [1], OUTPUT code, and by executing port number ten, it will be set in the output state. the work.

In the same way, we can set the matrix of the input ports that extend from port number 1 to 4, and the code for them can be added to the for loop inside the tuning of the
output ports. It is very important to note that port numbers 1 through 4 are numbers inside the array while the array itself starts from element 0 and will end with
element 3 because it has four elements.

void setup () {

for (int i = 0; i <4; i ++)

pinMode (pushButtons [i], INPUT);

pinMode (ledPins [i], OUTPUT);

Finally, we will add a partial code that will make the input ports linked to the internal pull up resistance to the iterative loop where it will operate with the same
previous concept.

void setup () {

for (int i = 0; i <4; i ++)

pinMode (pushButtons [i], INPUT);

pinMode (ledPins [i], OUTPUT);

digitalWrite (pushButtons [i], HIGH); // activate pullup resistor

81
So far we have finished the code for setting the port mode, but what about the code inside the loop function? As you know, the code in the loop is the code responsible
for implementing the basic idea.

The code inside the loop function is a code that is executed continuously to infinity. When you reach the last line of the function, the function starts to work again
starting from the first line. It is worth noting here that the microcontroller on the Arduino Uno board is ATMEGA328P connected to a clock source operating at 16 MHz
and almost the microcontroller performs one operation per clock pulse, that is, we can say that the microcontroller can implement 16 million instructions per second! I
deliberately mentioned this information now because the code in the loop in this lesson depends on this feature and you will not be able to understand it until you feel
the speed with which the microcontroller works.

void loop () {

// put your main code here, to run repeatedly:

for (int i = 0; i <4; i ++)

int val = digitalRead (pushButtons [i]);

if (val == 0)

digitalWrite (ledPins [i], HIGH);

else

digitalWrite (ledPins [i], LOW);

The code starts with a for loop that runs from 0 to 3, you will start by placing the value 0 in the variable i and the code inside the loop will be executed. In the first line
inside the loop, we defined the variable val of the integer type, in which the value in port 1 will be read, i.e. [push button [0], if the push button is pressed, the
digitalRead function will read the value 0 and in the opposite case it will read the value 1 then this will be put The value in the variable val. Then the microcontroller
will implement the if else condition function and will test the condition if the val variable contains the value 0 or LOW then if the condition is met the value of HIGH
will be placed on the port associated with the variable [ledPins [0 and if the condition is not met the value LOW will be placed on the port associated with the variable [
ledPins [0 So we ran the first iterative loop in which the value of the variable i was equal to zero. The function will continue to work and each time you increase the
value of i by one and then execute the code with the new value of i until it becomes i equal to 3, the code is executed based on this value and then the value of i returns
again to 0.

Now suppose that you have implemented the code and loaded it into the Arduino and then pressed the button connected to port number 3 located in [pushbutton [2.
Actually, the code in the loop function will test all pushbuttons from [pushbutton [0 to reach [pushbutton] 3 but this will be done very quickly and each time when it
passes the test of the condition related to [pushbutton [2] which will light the LED connected to port number 11.

82
Table of Contents

Introduction 5
Arduino Coding Environment and basic tools 6
What language is Arduino? 6
Arduino IDE 6
Chapter One 7
Transactions in Arduino language 7
Arithmetic transactions in Arduino 8
Budget transactions in Arduino 9
Boolean transactions in Arduino 10
Index access transactions in Arduino 11
Binary number coefficients in Arduino 12
Compound transactions in Arduino 13
Chapter II 15
Data types 15
The String object in the Arduino 16
General structure 16
Returned values 16
Minions 17
Transactions 18
Arrays in Arduino 20
Create an array 20
Access to the matrix 20
Type bool in Arduino 22
byte in Arduino 23
Type char in Arduino 24
Type double in Arduino 25
Type float in Arduino 26
General structure 26
Type int in Arduino 27
Strings In Arduino 29
General structure 29
Termination character null 29
Long strings wrapping 29
Matrices of text strings 30
Type word in Arduino 31
The keyword void in Arduino 32
Chapter III 33
Constants and variables 33
Decimal system (base 10) 34
Binary System (Basis 2) 35
Notes and warnings 36
Constants in Arduino 37
Variable Scope & Qualifiers 39
The keyword const in Arduino 39
The field of variables in Arduino 39
The static keyword in Arduino 40
Examples 41
Keyword volatile in Arduino 42
Volatile or long volatile integers? 42
83
Chapter IV 44
Control structures 44
Keyword break in Arduino 45
Continue keyword in Arduino 46
Loop do ... while iterative in Arduino 47
Keyword else in Arduino 48
Goto keyword in arduino 51
Expression if conditional in Arduino 52
Notes and warnings 52
Keyword return in Arduino 54
Examples 54
Expression switch ... case in Arduino 55
Transactions 55
While iterative episode in Arduino 56
Chapter V 57
Functions 57
The digitalRead () function in the Arduino 58
digitalRead (pin) 59
The digitalWrite () function in the Arduino 60
The pinMode () function in the Arduino 62
Time functions in Arduino 63
The delay () function in the Arduino 63
Arduino delayMicroseconds () function 64
Arduino micros () function 65
Arduino millis () function 66
Mathematical Functions in Arduino 68
Handling and verifying typefaces in Arduino 69
Arduino conversion functions 70
Provincial control functions in Arduino 71
Chapter VI 72
Additional tools 72
The keyword programm in Arduino 73
Examples 73

84

You might also like