You are on page 1of 92

Beginners Guide to Arduino

The Perfect Step by Step Manual or


Handbook with Practical examples!

By
Ben C. Philips
TABLE OF CONTENTS
Introduction To Arduino
Arduino Arithmetic Operators
Arduino Loops
Arduino Functions
Time library in Arduino
Arduino Control Statements
Understanding Arrays in Arduino
How To Use Strings In Arduino
Arduino Project Sample
Conclusion
INTRODUCTION TO ARDUINO
A rduino is an open source prototyping platform built on easy-to-use
hardware and software. Arduino boards are able to read inputs - a light on a
sensor, a finger on a button, or a Twitter message - and turn it into an output
- activate the motor, turn on an LED, and post something online. You can
tell your board what to do by sending a set of instructions to the onboard
microcontroller. To do this, it uses the Arduino programming language
(based on Wiring), and the Arduino software (IDE), based on the
processing.
The Arduino board itself is a blue circuit board, the size of a credit card
(but also has other sized models). It contains two rows of connectors
("headers"), a power connector, and a USB connector. The mind board is
an Atmel microcontroller. It's like a very small, very low power
"computer". (It has only 32 KB of storage, 2 KB RAM, and the 8-bit
processor only runs at 16MHz.) However, for most applications, this is
more than enough. Processor pins attach to headers, and you can connect to
almost anything you can imagine. You just need to write some lines of code
to control it. The input / output (input / output) pins can be used as input
pins, for connecting buttons or knobs, temperature sensors, light sensors, or
even keyboards and mice, digital musical instruments ... or they can be used
as output pins, for connecting lamps, motors Disks, control the lights in
your home, connect to small screens or even connect to the internet, so you
can check your mail, post tweets ... through a USB connection, you can also
use it to control your computer, or use your computer to control In
Arduino.

T ypes O f A rduino B oards


Many different types of Arduinos are available, as shown in the table
below, and each has its own set of features. They differ with regard to
processing speed, memory, I / O and connection, but their basic functions
are the same.

Arduino Uno
Arduino Leonardo
Arduino Due
Arduino Yún
Arduino Tre
Arduino Micro
Arduino Robot
Arduino Esplora
Arduino Mega
Arduino Mini
LilyPad Arduino
Arduino Nano
Arduino Fio
Arduino Pro
Arduino Ethernet

SOFTWARE (IDE)
The software used for programming Arduino is called the Integrated
Development Environment (IDE). IDE is a Java application that works on
many different platforms, including PCs, Macs, and Linux systems. It was
developed for beginners who are not familiar with programming. Includes
a code editor, compiler, and uploader. Symbol libraries for use of
peripheral devices, such as serial ports and various types of displays, are
also included. Arduino programs are called "sketches" and are written in a
language very similar to C or C ++.

USB CABLE
Most Arduinos connect to a host computer via a USB cable. This
connection enables you to upload graphics to your Arduino as well as
provide power to the board.

PROGRAMMING
Programming Arduino is easy: you can use the IDE code editor to write
the program and then compile and load it with one click. The Arduino
software includes two main functions:
Setup ()
Loop ()
You can use the setup function () to configure the panel settings. This
function works only once when the board is powered on. The loop ()
function is executed after setup () has completed, and unlike the setup ()
function, it runs continuously.

PROGRAMMING FUNCTIONS
Here are some of the most used functions in Arduino programming:

pinMode - Sets the pin mode to either INPUT or OUTPUT.


analogRead- The analog voltage is read from the analog input
terminal.
analogWrite - Writes an analog voltage to an analog output
terminal.
digitalRead - reads the value of the digital input pin.
digitalWrite - sets the value of the digital output terminal to either
HIGH or LOW.
Serial.print - prints the data to the serial port as human-readable
ASCII text.

ARDUINO LIBRARIES
Arduino libraries are sets of functions that allow you to control devices.
Here are some of the most used libraries:

GPS library
LCD library
Servo library
SD library
Robot_control library
Robot_motor library
Ethernet library
Wi-Fi library
Stepper library
SPI library
EEPROM library
Software Serial library
GSM library

A rduino setup steps

First, install the IDE. You can download the IDE from the
Arduino website.
Install the program on your computer.
Now run the arduino IDE.exe file. It has the following layout:
Write your program using the code editor and upload it to the
Arduino. To do this, you need to connect the Arduino to your
computer using a USB cable.
In the IDE, select the type of Arduino you are using from Tools ->
Boards menu.
Now verify your code by clicking on the "hash" icon at the top of
the IDE window, then click the "right" arrow next to compile the
code and upload it to the Arduino.
Note: You may have to install drivers if your system does not detect the
Arduino.

A rduino shields

Arduino shields are a board that is attached to the Arduino to allow you to
connect peripherals, sensors, and actuators to the Arduino. Here are some
popular shields:

GSM Shield
Ethernet Shield
WiFi Shield
Motor Shield
Proto Shield
Joystick Shield
Bluetooth Shield
Xbee shield
COMPONENTS AND ACCESSORIES
Here is a list of all the components and accessories commonly used with
Arduino for project development:

Breadboard
USB cable
9V Battery
LEDs
Push Buttons
Capacitors
Voltage Regulators
Sensors (IR, temperature etc)
Jumper wires
Resistors
Potentiometer
Motors (DC, Servo, BLDC)
LCD
Hex keypad
Arduino shields

A rduino D ata T ypes


Arduino data types. They play an important role when it comes to
programming Arduino. An Arduino that is a computer is not very familiar
with data (it does not know or care about the way the data it receives has
been sent to it.)
Without data types, you cannot specify the number of bytes of memory
allocated to this variable, and the type of data that can be stored in the
variable which makes the variable's data type important.
A data type can be defined as a classification that describes the value a
variable carries and the operations we can perform on it. Unlike variables,
functions also have data types depending on the values ​they return.
Computers, including Arduino, tend to be very data neutral. The core of
the device is an arithmetic logical unit (ALU), which performs (to some
extent) simple operations on locations in memory: R1 + R2, R3 * R7, R4,
R5, etc. This represents data to the user, whether it is text, integer values,
floating values, or even part of program code.
All the context for these operations comes from the compiler, and the
context directives reach the compiler from the user. You, the programmer,
are telling the compiler that this value is an integer and that this value is a
floating point number. So the translator is left trying to figure out what I
mean when I say "add this integer to that floating point." Sometimes this is
easy, but sometimes it is not. And sometimes it sounds easy, but it turns out
it gives results you might not expect.
Data types are used to define the data types and functions associated with
data processing. It is used to announce functions and variables, which
define bit style and storage space. The types of data that we will be using in
the Arduino are listed below:

void Data Type


int Data Type
Char Data Type
Float Data Type
Double Data Type
Unsigned int Data Type
short Data Type
long Data Type
Unsigned long Data Type
byte data type
word data type

VOID DATA TYPE


The null data type defines the set of null values ​and is only used to define
functions. It is used as a return type for functions that do not return any
value.
Let's understand with an example in Arduino.
Consider the code below.
int a = 3 ;
void setup( )
{
. //
}
void loop ( )
{
.
.
}

INT DATA TYPE


Integer data types are integers like 5, -6, 10, -123, etc. They don't have
any fractional part. Valid data types are represented by int. It is the primary
data type for storing numbers.
The size of int is 2 bytes (16 bits).
Lower range: -32768 to 32767 or - (2 ^ 15) to ((2 ^ 15) -1)
On the ATmega and Arduino UNO boards, int data types store a 2-byte
value.
On boards like Arduino Zero, MKR1000 (SAMD boards), and Arduino
Due, the int data type stores a 4-byte or 32-bit value. The lowest range in
such a case would be - (2 ^ 31) to ((2 ^ 31) - 1) or -2,147,483,648 to
2,147,483,647.
Negative numbers are stored in the integral form of 2, with the sign bit or
the highest bit marked as a negative number.
The syntax is used as follows:
int var = val;
where,
var = variable
value = the value assigned to the variable
For example,
int a;
int b = 3 ;
Any variable or variable identifier becomes an integer and can only contain
integer values.
Let's understand with an example in Arduino. Consider the code below.
int Sum = 0 ;
void setup( )
{
Serial.begin(9600 );
}
void loop ( )
{
Sum++; // on every loop, it adds 1 to the Sum int
Serial.println ( Sum); // it prints the current state of the Sum variable
delay(1500 ); // delay of 1.5 seconds
}

CHAR DATA TYPE


Char data type can store any number of character sets. The identifier
declared because the char becomes a character variable. The letters are
written within a single quote.
The character type is often said to be an integer type. This is because
symbols, letters, etc., are represented in memory by the associated number
codes and are just integers.
The size of the character data type is at least 8 bits. We can use the byte
data type for the unsigned 8-bit or 1-byte char data type.
For example, the letter "A" has an ASCII value of 65.
If we specify, 'A' + 2, it will have an ASCII value of 67.
The formula is:
char var = val;
where,
var = variable
val = The value assigned to the variable.
Let's understand with an example.
Consider the below code.
char myvariable = ' B ' ;
char myvariable = 66 ; // both the value are equivalent
The ASCII table is shown below:

FLOAT DATA TYPE


The number containing the fractional part and the decimal part is
considered a floating point number. For example, 4.567 is a floating point
number. The number 13 is an integer, while 13.0 is a floating point
number. Due to their great accuracy, fractional numbers are used to
approximate adjacent and analog values.
Floating point numbers can also be written as an exponent. The numbers
can be as large as 3.4028235E + 38 and as small as -3.4028235E + 38. The
size of floating data types is 4 bytes or 32 bits.
The formula is:
float var = val;
where,
var = variable
val = The value assigned to the variable
Let's understand with an example.
Consider the below code.
int a ;
int b ;
float c ;
void setup ( )
{
Serial.begin (9600 );
}
void loop ( )
{
a=3;
b = a/2 ; // b is an integer. It cannot hold fractions. The output will be 1.
c = (float ) a / 2.0 ; // c now contains 1.5.
// Here, we have to use 2.0 instead of 2.
}
Note: We need to add a decimal comma to a number. Otherwise, it will be
considered an integer. For example, 14.0 is a floating number while 14 is
an integer.
Floating point numbers can also be converted to integers. For example,
float a = 3.6 ;
int b = a + 0.6 ; // output = 4

DOUBLE DATA TYPE


The double data type is also used to manipulate the decimal or floating
point numbers. It takes up twice the memory float. Stores floating point
numbers with greater accuracy and range. It stands for double precision
floating point numbers.
It plays 4 bytes in ATmega and UNO boards, while it plays 8 bytes in
Arduino Due.
The formula is:
double var = val;
where,
var = variable
val = The value assigned to the variable

UNSIGNED INT DATA TYPE


Unsigned int stores the value up to 2 bytes or 16 bits. It stores only
positive values. The range of unsigned data type ranges from 0 to 65,535 or
0 to ((2 ^ 16) - 1).
Arduino Due stores 4-bit or 32-bit unsigned data value.
The difference between the unsigned data type is the signature bit. The
int type in the Arduino is int. In a 16-bit number, 15 bits are interpreted
with a complement of 2, while a high bit is interpreted as a positive or
negative number. If the high bit is "1", it is considered a negative number.
The formula is:
unsigned int var = val;
where,
var = variable
val = The value assigned to the variable
For example,
unsigned int pinofLED = 8 ;

SHORT DATA TYPE


Short is an integer data type that stores 2 bytes or 16 bits of data.
The range of short data types ranges from -32768 to 32767 or - (2 ^ 15) to
((2 ^ 15) - 1). Arduino's ARM and ATmega usually store the data value of
2 bytes.
The formula is:
short var = val;
where,
var = variable
val = the value assigned to the variable
For example,
short pinofLED = 8 ;

LONG DATA TYPE


Long data types are extended size variables, which store 4 bytes (32 bits).
The size ranges from -2,147,483,648 to 2,147,483,647.
While using integers, L must follow at least one of the numbers, which
forces the number to be a long data type.
The formula is:
long var = val;
where,
var = variable
val = The value assigned to the variable
For example,
long speed = 186000L;

UNSIGNED LONG DATA TYPE


Long unsigned data types are also extended size variables, which store 4
bytes (32 bits). It does not store negative numbers like other unsigned data
types, making it range from 0 to 4294.967.295 or (2 ^ 32 - 1).
The formula is:
unsigned long var = val;
where,
var = variable
val = The value assigned to the variable
For example
unsigned long currenTtime;

BYTE
1 byte = 8 bits.
It is considered as an unsigned number, which stores values from 0 to 255.
The formula is:
byte var = val;
where,
var = variable
value = the value assigned to the variable
For example,
byte c = 20 ;

WORD
It is considered as an unsigned number of 16 bits or 2 bytes, which stores
values from 0 to 65535.
The formula is:
word var = val;
where,
var = variable
val = The value assigned to the variable
For example,
word c = 2000 ;
ARDUINO ARITHMETIC OPERATORS
B elow, five math factors are described and then all of them are put into a
diagram to show how they work on an Arduino.

ADDITION
To add numbers on the Arduino, we use the addition operator (+).
The example below shows how to add two numbers together.
int a = 2;
int b = 7;
int sum;
sum = a + b;
In the above code, three variables are defined. Both variables A and B are
assigned a value when defined.
The sums variable is defined, but not initialized, so it contains any random
number. We'll use this variable to store the result of calculating the
addition, so the random value in the sum will be overwritten when we place
the result of the addition (or the sum) in it.
After executing the statement shown below, the sum will contain the value
9, that is, the result of adding the variable a and b.
sum = a + b;
We can also add two constant values ​and store the result in a variable as
shown below.
int sum;
sum = 2 + 10;
The result stored The result stored in the sum after executing the add
statement would be 12 in this example.
Static values ​and variables can also be added together and the result
stored in a variable as shown here.
int a = 3;
int sum;
sum = a + 24;
After performing the addition, the amount will contain 27.
The remaining arithmetic operators can also operate on constant values,
variables, and a combination of the two.

SUBTRACTION
The subtraction operator subtracts one number from another using the
minus sign (-) as the following example illustrates.
int result;
result = 10 - 2;
The result of this calculation will be 8 and it will be stored in the resulting
variable.

MULTIPLICATION
Multiplication is done using the multiplication operator (*).
int result;
result = 4 * 3;
The calculation result will be above 12 and it will be stored in the result
variable.

DIVSION
The division operator (/) is used to perform division in an Arduino.
int result;
result = 12 / 3;
The result of the above calculation is 4.

INTEGERS VERSUS FLOATING POINT


So far, we still only use correct values ​for calculations. If the division
result is not an integer (or integer number), but contains a fraction portion,
then the fraction portion is discarded if the result is stored in an integer
variable.
The following examples illustrate what happens when a result with a
fractional portion is stored in an integer and floating-point variable.
int result;
result = 5 / 4;
The result will be 1 because the fraction is ignored when the result is
stored in the result of an integer variable.
The same arithmetic operation, but this time it specifies the result as a
floating point (floating) variable.
float result;
result = 5.0 / 4.0;
The result now included in the result variable is 1.25.
When using constant values ​in calculations that store the result in a
floating point variable, we use the decimal point and zero for the integers,
i.e. 5.0 instead of 5 alone.

REMAINDER (MODULO DIVISION)


The residual operator (or the modulo operator) is used to find the
remainder after dividing two numbers. The percent sign (%) is used as the
modulo factor.
int result;
result = 11 % 4;
The result of this calculation will be a remainder of 11 divided by 4 which
is 3 (4 goes to 11 twice and leaves the remainder by 3).

ARITHMETIC SKETCH
The following diagram called Computation illustrates all of the arithmetic
factors mentioned above.
Upload the drawing to the Arduino and have a try. Also add the above
examples that are not in the diagram, such as mixing values ​and static
variables.
void setup () {
int a = 2;
int b = 7;
int result;
float result_fl;

Serial . begin (9600);

Serial . print ( "Addition (a + b): " );


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

Serial . print ( "Subtraction (10 - 2): " );


result = 10 - 2;
Serial . println (result);

Serial . print ( "Multiplication (4 * 3): " );


result = 4 * 3;
Serial . println (result);

Serial . print ( "Int Division (5 / 4): " );


result = 5 / 4;
Serial . println (result);

Serial . print ( "Float Division (5.0 / 4.0): " );


result_fl = 5.0 / 4.0;
Serial . println (result_fl);

Serial . print ( "Remainder (11 % 4): " );


result = 11 % 4;
Serial . println (result);
}

void loop () {
}

COMMENTS ON SKETCH

print () function
The diagram contains a mixture of print () and println () functions. Print
() is called when the invisible cursor must remain on the same line, so the
text printed in the next println () statement will be printed on the same line
as well.
Println () function
Println () is used when text must be printed and then the invisible cursor
moves to the next line so that the following print () statement prints the text
on a new line.

Floating point variable


A separate result_fl variable was specified to hold the floating point
computation result.

IntegerVariable
The result of the integer variable is reused many times while drawing.
The important thing is to display its result before putting the result of the
next calculation into it.

Constants and variables


We looked at the variables in the final part of this course. Constants are
numbers that remain constant throughout the diagram - that is, they never
change.
Examples of constants are numbers that are used directly in a calculation
and are not assigned to a variable, for example SUM = 2 + 3 contains
constants 2 and 3.
The constants have no name and their values ​cannot be changed when the
diagram is run.

Floating Point Arithmetic


Although not shown in the examples above, addition, subtraction, and
multiplication operations can also be performed on floating point values.
ARDUINO LOOPS
P rogramming languages ​​provide various control structures that allow for
more complex implementation paths.
The loop statement allows us to execute a statement or a group of
statements multiple times. Here is the general look of a loop statement in
most programming languages ​-

C programming language provides the following types of loops to handle


redundancy requirements.

ARDUINO FOR-LOOP
Arduino for loop is one of the baking and butter functions that you will
use all the time in your code. Microcontrollers are good for repetitive tasks,
but instead of typing the same code multiple times, the for-loop repeats a
section of code a certain number of times.
WHERE ARE FOR-LOOPS USED
You can use for loops anywhere within a function, so you can use them in
the standard Arduino (), loop () setup functions, and in your own functions.
The following example shows a for-loop that is about printing numbers 0
through 9. It's put into the setup () function because you only want to
execute the for-loop action once - otherwise if you put it inside the loop () it
outputs the information repeatedly - which makes you spin (try it and see)!
Copy the code into the Arduino IDE. Compile and run the program. Start
the serial monitor to see the output.
This code shows an example Arduino for loop with the for loop itself
inside the setup () function. This isn't where you should normally use the
for loop (you can) - it's just here to turn off multiple outputs.
void setup ( void ){
Serial . begin ( 9600);
Serial . println ( "Arduino for loop" );
for ( int i = 0; i < 10; i ++) Serial . println ( i );
}

void loop ( void ){


}

H ow does A rduino for - loop work

Arduino for loop provides a mechanism to iterate a segment of code


depending on the value of the variable. So you set the initial value of the
variable, the condition for exit from the loop (test of the variable), and the
action on the variable every time around the loop.
Initial section: the initial value of the control variable.
Condition section: condition of stopping the episode.
Iterator section: make the loop variable (increase or decrease).
These three elements are parameters of the for loop and are separated by
semicolons:
for ( <initialiser code> ; <condition test expression> ; <iterator
expression> ) {
<body code>
}

ARDUINO LOOP COUNTER CONTROL VARIABLE


Another important point about for-loops is that they need a loop control
variable - in the example this is the variable i. This is used as a ring gauge
and is used to determine when to exit the ring.
The code shown earlier is the standard way of writing a for-loop in which
the loop variable starts at zero and increases 10 times.
For (int i = 0; i <10; i ++) Serial.println (i);
Note: The value of "i" starts from 0 to 9 and is 10 times around the ring.
The "i" can only range from 0 to 9, on exit 10. You can use the variable "i"
in the post code as well.

P arameters of the A rduino for loop

Initialize
Int i = 0;
First of all, the variable "i" is created (if it doesn't already exist) and set to
zero.
This section of the for-loop runs only once at the beginning.

TEST
i < 10;
After that the loop variable is tested. Here, if it's less than 10, go ahead -
otherwise the loop gets out. This is performed every time around the loop.

ITERATOR
i ++;
The loop control variable (ring counter) is increased by one.
This is performed every time around the loop.

ARDUINO FOR-LOOPOUTPUT
So the for-loop runs the code "Serial.print (i)" 10 times with a value of 'i'
going from 0 to 9.
And this is the result:
Arduino for loop
0
1
2
3
4
5
6
7
8
9
For a different way of doing similar work, you can allow the control
variable to change from 1 to 10.
for ( int i = 1; i < =10; i ++) Serial . println ( i );
This will print from 1 to 10. It still has 10 iterations but starts from 1.
Note: Here the value of the letter "i" ranges from 1 to 10. At the end of
Ring "i" it has the value 10 - as before.

ARDUINO FOR-LOOP BODY CODE


The body of the for-loop can be either a single statement of a block of
code between the curly braces. So you can write the episode as follows:
void setup ( void ){

Serial . begin ( 9600);

Serial . println ( "Arduino for loop" );


for ( int i = 0; i < 7; i ++){
Serial . print ( "i is : " );
Serial . println ( i );
}
}

void loop ( void ){


}

Notice how there are two terms - ending with a semicolon and both are
enclosed in square brackets. Compare this to the previous example, which
used only one phrase ending with a semicolon.
In this case the output is:
Arduino for loop
i is : 0
i is : 1
i is : 2
i is : 3
i is : 4
i is : 5
i is : 6
i is : 7

H ow to set up a countdown for - loop

You can create a for loop that counts down by changing all three
parameters in the for loop. Let's say you want to count down from 10 to 1
(ten iterations around the loop).
void setup ( void ){

Serial . begin ( 9600);

Serial . println ( "Arduino count down for loop" );


for ( int i = 10; i>= 1; i --){
Serial . print ( "i is : " );
Serial . println ( i );
}
}

void loop ( void ){


}
Here's the count down output:
Arduino count down for loop
i is : 10
i is : 9
i is : 8
i is : 7
i is : 6
i is : 5
i is : 4
i is : 3
i is : 2
i is : 1

ARDUINO FOR LOOP ARRAY EXAMPLE


The reason you start with the control loop variable at zero is that the
arrays are defined starting at index zero. If you don't use zero as your initial
starting point, you can get one error - which means you can write to an
array location that doesn't exist. For an array of 10 values, only 0..9
pointers are valid.
Note: Note: even if the position of the array does not exist, the loop will
still write data to that location - which means you are overwriting other
variables - which is a very bad idea!
Here is an example of an array setup that initializes each element with a
random number. Then print the array values ​in turn.
int myarray [ 10];

void setup ( void ){


Serial . begin ( 9600);

for ( int i = 0; i < 10; i ++) myarray [ i ]= random ( 100);

Serial . println ( "Arduino for loop" );


for ( int i = 0; i < 10; i ++){
Serial . print ( "i is : " );
Serial . print ( i );
Serial . print ( " array value is " );
Serial . println ( myarray [ i ]);
}
}

void loop ( void ){


}
The random number output is not really random unless you provide an
initial value - it must also be from a random source - like pressing a button
to pick up a timer value () - really random start.
This is because random data is generated from an algorithm and if you
start from the same initial number, all values ​will be duplicated. If you run
the program again, you will see the same set of numbers. For this symbol it
does not matter.
The randomness of the job lies in the unpredictability of the numerical
sequence.

STANDARD FORM OF FOR-LOOP


The standard for loop format initializes the control variable to 0. To exit
the loop, the condition tests whether the variable is smaller than the
required number of loops. You don't have to use this but it makes life easier
when dealing with arrays.
Tip: It's best to use the standard Arduino for-loop model so that you never
arrive at an incorrectly arrayed value.
The standard form is this:
for ( int i = 0; i < 10; i ++){
<block of code to execute>
}

INITIALIZE A FOR LOOP


In the above examples, the initialize code for the loop is used as follows:
Int i = 0;
This is a C ++ method for declaring and initializing a loop variable.
In the C code you will find the following code:
This is because you cannot initialize variables anywhere except at the
beginning of a function. So here's the type of code you'll find:
void myFunction ( void ){
int i ;

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


Serial . println ( i );
}

for ( i = 10; i > 0; i ++){


Serial . println ( i );
}
}

ARDUINO WHILE LOOP


The following illustration does exactly the same as the for loop diagram
from Part 7 of this course, except that it uses the while loop so we can see
the similarities between the two loops.
void setup () {
int i = 0;

Serial . begin (9600);

while (i < 10) {


Serial . print ( "i = " );
Serial . println (i);
i++;
}
}

void loop () {
}

While-Loop Structure
The while loop has a structure like this:
while (loop test expression goes here) {
Statements that run in the loop go here
Statement 1
Statement 2
...
}
The while loop begins with the keyword while followed by a test
expression between the open and close parentheses. The opening and
closing brackets denote the body of the ring.

TEST EXPRESSION
As with the for loop, the while loop contains a test expression that will
determine whether the statements in the loop will work or not. If the test
expression evaluates to true, then loop statements run. If the test expression
evaluates to false, then the loop statements will not run, but the statements
that follow the loop closing parenthesis will run - that is, execution
continues outside and under the loop.

INITIALIZE EXPRESSION
The for loop contains an initialization expression as part of the loop. The
while loop can use any variable from the schema that has a valid value. In
the example diagram, the variable used in loop (i) must be initialized when
defined, otherwise it will contain any random value.

INCREMENT EXPRESSION
The expression increase was used in the for-loop examples in the previous
part of this cycle. In the while loop example, the increment expression is
placed inside the body of the loop.
How does a while-loop example work?
In the example drawing, the following happens:
1. The variable i is initialized to 0 when the diagram is started.
2. The while loop evaluates the test expression (i <10).
3. The test expression is evaluated to true because i is less than 10.
4. Because the test expression is correct, the phrases in the loop are
played.
5. The current value of i is printed and then incremented.
6. Upon reaching the bottom of the loop, execution begins at the top of the
loop again.
7. The test expression is evaluated again, and it is true again, so the loop is
played again.
Only when the variable i is increased to 10 will the loop expression
evaluate to false and the loop will exit.
While-Loop example 2
In the schematic example below, the while loop is used to count up to 25
by five by adding five to a variable each time throughout the loop.
void setup () {
int sum = 0;

Serial . begin (9600);

// count up to 25 in 5s
while (sum < 25) {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
}
}

void loop () {
}
In this diagram, a variable called sum is defined and initialized to 0. The
test expression in a while loop tests whether the sum contains a value less
than 25.
Within the loop, the sum variable is incremented by 5 each time during
the loop by arithmetic expression:
sum = sum + 5;
This expression means "add 5 to the sum variable."
Then the value held by the sum variable is printed, followed by a delay of
half a second.
Since the variable's value is incremented first and then printed, we see the
value 5 printed first and not the 0 value it was initialized for.
Although the test expression will be evaluated as false when the sum is ==
25, the number 25 remains the last number printed. This is because the last
time a test expression evaluates to TRUE is when the sum is == 20, but the
sum is then increased to 25 and printed out before the test expression is
evaluated again.

ARDUINO DO-WHILE LOOP


A do while loop works the same as a while loop, except that it always
runs one time even if the test expression evaluates to false.
Do-while Loop struture
A do while loop consists of two keywords, "do and while", as shown
below.
do {
Statements that run in the loop go here
Statement 1
Statement 2
...
} while (test expression goes here);
The body of a do while loop is located between the open and close
brackets and contains expressions that run in the loop.
The while keyword and test expression come after the loop text and are
terminated with a semicolon (;).
Do while loop example
This example illustrates a do while loop.
void setup () {
int sum = 0;

Serial . begin (9600);

// count up to 25 in 5s
do {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
} while (sum < 25);
}

void loop () {
}
All statements run in the body of the loop before the test expression
evaluates.
If the sum is initialized to a value of 25 when specified, as shown in the
diagram below, the loop will run once and 30 will be printed. The loop will
not run again after that because the test expression is evaluated to false.
void setup () {
int sum = 25;

Serial . begin (9600);

// count up to 25 in 5s
do {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
} while (sum < 25);
}

void loop () {
}
Using the same scheme, but changing a do while loop to a while loop, as
shown below, the statements in the body of the loop will never work. This
is because the test expression is evaluated before the statements in the loop
body are executed. Test expression evaluates instantly to false, so loop
statements will never work.
void setup () {
int sum = 25;

Serial . begin (9600);

// count up to 25 in 5s
while (sum < 25) {
sum = sum + 5;
Serial . print ( "sum = " );
Serial . println (sum);
delay (500); // 500ms delay
}
}

void loop () {
}
In the example above, no output will appear in the serial monitor window
when the diagram is run. The while loop evaluates to false and then the
execution falls directly into the empty main Arduino loop.
ARDUINO FUNCTIONS
T he functions allow the programmer to divide a specific code into different
sections, and each section performs a specific task. Jobs are created to
perform a task multiple times in the program.
A function is a type of procedure that returns the area of ​code from which
it is called.
The function returns something, or a value called the return value. Return
values ​can be of several types, some of which are listed here:

Integers

Float

Double

Character

Void

Boolean
Another term, an argument, denotes something that is passed into the
function and is computed or used within the function. In our previous
example, the ingredients that go into our coffee making process can be
called arguments (sugar, milk, etc.), and finally we get the coffee, which is
the return value of the job.
By definition, there are two types of jobs. It is a system defined function
and a user defined function. In our Arduino code, we often saw the
following syntax:
void setup (){
}
void loop (){
}

setup () and loop () are also functions. The return type for these jobs is
void. Don't worry, we'll discuss the job type soon. Setup () and loop () are
system-defined functions. There are a number of functions specified by the
system. User-defined jobs cannot be named after them.
Before we dive into the types of functions, let's get to know the syntax of
a function. The functions could be as follows:
void functionName ()

{
//statements

Or like
void functionName ( arg1, arg2, arg3)

//statements
}

So what's the difference? Well, the first function doesn't have arguments,
but the second function has it.
There are four types of functions, depending on the return type and the
arguments. They are as follows:

Function without arguments and without return value


Function without arguments and return value
Function with arguments and no return value
A function with arguments and a return value
Now, the question is, could the arguments be of any kind? Yes, it can be
of any type, depending on the job. They can be logical, integers, floats, or
letters. It can be a mixture of data types as well. We'll look at some
examples later. Now, let's define and take a look at examples of the four job
types we just identified.
A function without arguments and without a return value, these functions
do not accept arguments. The return type for these functions is void, which
means that the function does not return anything. Let me explain this. As
we learned earlier, a job has to be called something. The job naming will
follow the variable naming rule. If we have a function name, we need to
specify its type as well. It is the basic rule for defining a job. Therefore, if
we are not sure what type of our job (the type of job it will perform), then it
is safe to use the empty keyword in front of our job, where space means no
data type, as in the following function:
void myFunction (){

//statements

Inside the function, we can do all the things we need. Suppose we want to
print I love Arduino! Ten times if the function is called. Therefore, the
function must have a loop that continues ten times and then stops.
Therefore, our function can be written as follows:
void myFunction (){
int i;

for ( i = 0 ; i

The previous function does not contain a return value. But if we call the
function from our main function (from the setup function (); we might also
call it from the loop function (), unless we don't want an infinite loop), it'll
print the function I love Arduino! Ten times. No matter how many times
we call, it will print ten times per call.
Let's write the complete code and take a look at the output. The complete
code is as follows:
void myFunction (){

int i;

for ( i = 0 ; i

In the code, we have put our (myFunction) function after the loop ()
function. The custom job posting before the prep () loop is good practice.
Inside our setup () function, we called the function, then printed out a few
dots, and finally, we called the function again. You can guess what will
happen. Yes, I love Arduino! It'll print ten times, then a few dots will print,
and finally, I love the Arduino! It will be printed ten times. Let's take a
look at the output on the serial monitor:

A FUNCTION WITHOUT ARGUMENTS AND A RETURN


VALUE
In this type of function, no arguments are passed, but it does return a
value. You have to remember that the return value depends on the type of
job. If you define a function as an integer function, the return value type
must also be an integer. If you define a function as a letter, the return type
must be a letter. This is true for all other types of data as well.
Let's look at an example. We will declare an integer function, as we will
define a few integer numbers. We'll add them and store them in another
integer, and finally we add back. The job might look something like this:
int addNum (){

int a = 3 , b = 5 , c = 6 , addition;
addition = a + b + c;
return addition;

The previous function should return 14. Let's store the function return
value to another integer type of variable in the setup () function and print it
to the serial screen.
The complete code will be as follows:
void setup (){

Serial. begin ( 9600 );

int fromFunction = addNum (); // added values to an integer


Serial. println ( fromFunction); // printed the integer

void loop (){

int addNum (){


int a = 3 , b = 5 , c = 6 , addition; //declared some integers

addition = a + b + c; // added them and stored into another integers

return addition; // Returned the addition.


}
The output will look like this:

FUNCTION WITH ARGUMENTS AND NO RETURN


VALUE
This type of function handles some arguments within the function, but it
does not return anything directly. We can do the math inside the function,
or print something out, but there will be no return value.
Suppose we need to find the sum of two integers. We might define a
number of variables to store, and then print the sum. But with the help of a
function, we can only pass two integers through a function; So inside the
function, all we need to do is add it and store it in another variable. Then
we'll print the value. Every time we call the function and pass the values ​
through it, we'll get the sum of the integers we pass. Let's define a function
that will show the sum of the two integers passed through the function.
We'll call the function sumOfTwo (), and since there's no return value, we'll
define the function as null. The job should look like this:
void sumOfTwo ( int a, int b){
int sum = a + b;

Serial. print ( “The sum is “ );

Serial. println ( sum);


}
When we call this function with appropriate arguments, the function will
print the sum of the number we pass through the function. Let's take a look
at the output first. Then we will discuss the code:
We pass the data to a function, separating it with commas. It must not
spoil the sequence of arguments during the function call. Since the function
arguments may be of different types, if we err on the call, the program may
not compile and will not execute correctly:
Say a function that looks something like this:
void myInitialAndAge ( int age , char initial ){

Serial . print ( “My age is “ );

Serial . println ( age );


Serial . print ( “And my initial is “ );
Serial . print ( initial );

}
Now, we should call the function like this: myInitialAndAge (6, 'T'); ,
Where 6 is my age and T is my initial letter. We should not do it as follows:
myInitialAndAge ("T", 6);
We called the function and ran two values ​through it (12 and 24). We get
the answer where the sum is 36. Isn't that cool? Let's delve a little deeper.
In our job, we declare the two arguments (A and B) as whole numbers.
Within the entire function, the values ​(12 and 24) that we ran through the
function are as follows:
A = 12 and b = 24;
If we call the function this sumOfTwo (24, 12) then the values ​of the
variables will be as follows:
A = 24 and b = 12;
Hope you can now understand the sequence of job arguments. How about
the experience? Call sumOfTwo () five times in setup (), with different
values ​for a and b, and compare the results.

F unction with arguments and a return value

This type of function will have both arguments and a return value. Inside
the function, there will be some operation or arithmetic using arguments,
and after that, there will be a result, which we want as a return. Since this
type of function will return a value, the function must have type. Let's look
at an example.
We will write a function that checks whether the number is prime or not.
From your math class, you might remember that a prime number is a
natural number greater than 1 and has no positive denominators other than 1
and itself.
The basic logic behind checking whether or not a number is prime is to
check all numbers starting from 2 to the number before the number itself by
dividing the number. Not clear? Okay, so let's check if 9 is a prime
number. No, it is not a prime number. why? Because it can be divided by
3. According to the definition, it cannot be divided by any number other
than 1 and the number itself.
Therefore, we will check if the number 9 is divisible by 2. No, it is not the
case. Then we divide by 3 and yes, it's divisible. So 9 is not a prime
number, according to our reasoning. Let's check if 13 is a prime number.
We will check if the number is divisible by 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 and
12. No, the number is not divisible by any of these numbers. We may also
shorten the verification process by only checking the number that is half of
the number we are verifying. Look at the following code:
int primeChecker ( int n) // n is our number which will be checked

{
int i; // Driver variable for the loop

for ( i = 2 ; i
The code is very simple. If the remainder is equal to zero, then the
number is completely divisible by a number other than 1 and itself, so it is
not a prime number. If there is any remainder, the number is a prime
number. Let's write the code completely and look at the output of the
following numbers:
23
65
235
4543
4241
The complete source code to check whether the numbers are raw or not is
as follows:
void setup (){
Serial. begin ( 9600 );
primeChecker ( 23 ); // We called our function passing our number to test.
primeChecker ( 65 );

primeChecker ( 235 );
primeChecker ( 4543 );
primeChecker ( 4241 );

void loop (){


}

int primeChecker ( int n)


{

int i; //driver variable for the loop

for ( i = 2 ; i
This is a very simple code. We just called our primeChecker () function
and passed the numbers. Inside our primeChecker () function we wrote the
logic to check the number. Now let's look at the output:
From the result, we can see that, except for 23 and 4, 241, there is no
prime number.
Let's look at an example, where we'll write four functions: add (), sub (),
mul (), and divi (). In these functions, we will pass two numbers and print
the value on the serial screen. The four functions can be defined as follows:
float sum ( float a, float b){

float sum = a + b;
return sum;
}

float sub ( float a, float b){


float sub = a - b;
return sub;

}
float mul ( float a, float b){

float mul = a * b;
return mul;
}

float divi ( float a, float b){


float divi = a / b;
return divi;

}
Now write the rest of the code, which will give the following output:

USES OF FUNCTIONS
You might be wondering what kind of job we should be using. The
answer is simple. Functionality uses depend on software operations. But
whatever the job, I suggest doing only one task with the job. Do not
multitask inside the job. This will usually speed up processing time and
symbol computation time.
You may also want to know why we need to use the functions. Well,
there are a number of uses for the functions, as follows:
✓ Functions that help programmers write more structured code
✓ Functions help reduce errors by simplifying code
✓ Functions make the entire code smaller
✓ Functions create an opportunity to use the code multiple times
TIME LIBRARY IN ARDUINO
T ime is a library that provides Arduino timer functions. With Arduino
Library Manager, install "Time by Michael Margolis".
The code is derived from the Playground DateTime library but is being
updated to provide a more flexible and easier-to-use API.
The primary goal was to enable a date and time function that can be used
with a variety of external time sources with the minimum required
differences in drawing logic.
The graphics examples show how similar graphic symbol can be used
with: Real Time Clock, NTP Online Time Service, GPS time data, and
serial time messages from a computer for time synchronization.

FUNCTIONALITY
To use the time library in an Arduino diagram, include TimeLib.h.
# include <TimeLib.h>
The functions available in the library include
hour (); // the hour now (0-23)
minute (); // the minute now (0-59)
second (); // the second now (0-59)
day (); // the day now (1-31)
weekday (); // day of the week (1-7), Sunday is day 1
month (); // the month now (1-12)
year (); // the full four digit year: (2009, 2010 etc)
there are also functions to return the hour in 12-hour format
hourFormat12 (); // the hour now in 12 hour format
isAM (); // returns true if time now is AM
isPM (); // returns true if time now is PM

now (); // returns the current time as seconds since Jan 1 1970
The time and date functions can take an optional time parameter. This
prevents errors if time passes between elements. For example, if you start a
new minute between getting the minute and the second, the values ​will be
inconsistent. Using the following functionality solves this problem
time_t t = now(); // store the current time in time variable t
hour (t); // returns the hour for the given time t
minute (t); // returns the minute for the given time t
second (t); // returns the second for the given time t
day (t); // the day for the given time t
weekday (t); // day of the week for the given time t
month (t); // the month for the given time t
year (t); // the year for the given time t
Functions for managing the timer services are:
setTime (t); // set the system time to the give time t
setTime (hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr
// (2010 or 10 sets year to 2010)
adjustTime (adjustment); // adjust system time by adding the
adjustment value
timeStatus (); // indicates if time has been set and recently
synchronized
// returns one of the following enumerations:
timeNotSet // the time has never been set, the clock started on
Jan 1, 1970
timeNeedsSync // the time had been set but a sync attempt did
not succeed
timeSet // the time is set and is synced
Date and time values ​are invalid if the status is timeNotSet. Otherwise,
the values ​could be used but the returned time would have skewed if the
status was timeNeedsSync.
setSyncProvider (getTimeFunction); // set the external time provider
setSyncInterval (interval); // set the number of seconds between re-
sync
There are several fit macros in the time.h file for time constants and time
unit conversion. To use the library, copy the download to the library
directory.

EXAMPLES
The Time Guide contains the time library and some examples of diagrams
showing how to use the library with different time sources:

❖ TimeSerial.pde displays the Arduino as a clock without external


devices. It is synced as per the time messages sent through the serial
port. The associated processing fee will save these messages
automatically if they're powered on and connected to the Arduino
serial port.
❖ TimeSerialDateStrings.pde adds the day and month name strings to
the above graphic. Short (3 characters) and long strings are available
for printing the days of the week and the names of the months.
❖ TimeRTC uses the DS1307 real time clock to provide time
synchronization. You must download and install the DS1307RTC
Basic Library in order to run this diagram.
❖ TimeRTCSet is similar to the above and adds the ability to set the
real time clock.
❖ TimeRTCLog shows how to calculate the difference between times.
It's a very simple recorder app that monitors events on the digital pins
and prints (to the serial port) the event time and the interval since the
previous event.
❖ TimeNTP uses the Arduino Ethernet Shield to access the time using
the NTP Internet Time Service. NTP uses UDP and the UdpBytewise
library is required, see:
http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Eth
ernet/
❖ TimeGPS gets the time from GPS. This requires Mikal Hart's
TinyGPS Library: http://arduiniana.org/libraries/TinyGPS

DIFFERENCES
Differences between this code and playground date and time library
Although the time library is based on the date and time database, the API
has changed. Changes to the time library API:

Time elements are functions that return int (variables on


DateTime).
Years beginning in 1970
Weekdays and Months 1 (Starts 0 on DateTime)
DateStrings do not require a separate library
Time elements can be accessed in a non-atomic way (on DateTime
it is always atomic)
A function has been added to automatically synchronize the time
with an external source
The LocalTime and maketime parameters have been changed,
LocalTime renamed breakTime

TECHNICAL NOTES
Internal system time is based on Unix time_t standard. The value is the
number of seconds since January 1, 1970. The system time starts at zero
when the drawing begins.
The internal time can be automatically synchronized at regular intervals
with an external time source. This is enabled by calling the
setSyncProvider (provider) function - the provider argument is the address
of a function that returns the current time as time_t. See drawings in the
guide for examples to use.
The default time interval for resync is 5 minutes but can be changed by
calling the setSyncInterval method to set the number of seconds between
resync attempts.
The time library defines a structure for holding time elements and is a
compact version of CTM architecture. All members of the Arduino ™
architecture are bytes and compensate for the year from 1970. The
convenient macros provide conversion to and from the Arduino format.
Low-level functions are provided for switching between system time and
individual time elements:
breakTime (time, & tm ); // break time_t into elements stored in tm struct
makeTime (& tm ); // return time_t from elements stored in tm struct
This DS1307RTC library provides an example of how a timer can use
low-level functions to interact with a time library.
ARDUINO CONTROL STATEMENTS
D ecision-making structures require that the programmer define one or
more conditions to be evaluated or tested by the program. It should be
along with a statement or clauses to perform if the condition is defined as
true, and optionally, other clauses to be performed if the condition is
defined as false.
Here is the general look of the typical decision making structure found in
most programming languages ​-

The control architecture tells how the code is organized to enable the
program to take action based on certain conditions. Take this example; you
want your software to only trigger an LED when the sensor scores 50
degrees Celsius, you have to structure your code in a way to do such an
exact thing.
The method for ensuring such procedures can be seen in the program as a
control structure of the program, also known as a "control structure". This
is especially true when there are certain conditions in the program, just as
mentioned above. In order to achieve an intelligent and efficient control
architecture in Arduino programming, we use control data.
Control statements are elements (functions) in source code that control the
flow of program execution, either to wait, jump, iterate, etc.
The Arduino control data includes:

If statement

Else statement

Else if statement

For statement

While statement

Do while statement

Switch case

Continue

IF STATEMENT
An IF statement is basically the simplest form of a conditional control
clause, it is a conditional statement. The code "if statement" evaluates a
unique condition, and executes a series of instructions or just instructions if
the condition is true.
If the control statement is basically the type of control indication used to
program the dark street lights, the statement evaluates whether the
environment is dark or not, if the environment is dark, then the if statement
code directs the microcontroller to execute the code instructions that would
turn on the light The street, and if the environment is not dark, the if
statement code directs the microcontroller to execute the code instructions
that will not turn off the street light on and off until the environment
becomes dark.
The arduino IF statement flow diagram and syntax are shown below:

Figure 1: IF Statement Flow Diagram


Figure 2: A simple IF statement code

ELSE STATEMENT
Most of the time, the IF statement is followed directly by the ELSE
clause, the ELSE clause tells the alternate instructions to execute when the
IF statement is false. Check out the drawing below.
Figure 3: IF and ELSE clauses combine
The graphic in the photo above is better than the one that only has a
statement of an energized dark street light design.

ELSE IF STATEMENT
The "Else if statement" is used when we want to check three different
conditions. Includes the IF statement, ELSE IF statement, and ELSE
statement all in the same diagram. See the image below.
Figure 4: Schematic diagram showing the ELSE IF statement

FOR STATEMENT
The For statement is also a conditional statement for the Arduino control
topology used for frequent operation. As the name suggests, it is used to
perform a repeated operation of a real case. Take, for example, when a
carrier warns you that “if you try to recharge your phone number with the
wrong recharge code for 5 times, you will be blocked” If the case is present,
you can try to recharge that number repeatedly using the wrong charging
code in order to even Four times without being prevented, however, on the
fifth track, the state breaks down and you are banned.
For a clause, give a condition and check if the condition is still in effect,
and if it does, then action is taken and repetition can occur, and this will
continue to happen until the condition stops performing the action
associated with the condition. This can be used to augment an event. For
example, we can use the For statement to hide the LED up and down. See
the image below.
Figure 5: Fading the LED up and down with the for loop
Typically, a for loop is used to iterate a block of code enclosed in square
brackets. The increment counter is usually used to increase and end the
loop.

FOR LOOP SYNTAX


For (initialization, condition, increment)
{
Formulations);
}
Initialization: Happens first and again.
Condition: Every time during the episode, the condition is tested; If this
is true, then the instruction block and increment are executed, then the
condition is tested again. When the condition goes wrong, the episode
ends.
Increment: It is executed every time through the loop when the condition
is true.
The picture in Figure 5 above is a simple schematic diagram of a fade
LED connected to the PWM pins of the Arduino board. To learn more
about arduino PWM, check out this Arduio tutorial for beginners.

WHILE STATEMENT
The while clause is like an "if" statement except that it continues to repeat
a block of code (the block of code is what is inside the curly braces) as long
as the condition is true. See the example below.

Figure 6: Indication while flashing two LEDs for two different conditions

DO WHILE STATEMENT
The do while statement is similar to the else if statement but works the
same as the while loop, except that the condition is tested at the end of the
loop, so the do statement always runs at least one time. See the drawing
below:

Do while using the phrase to flash the LED in response to the sensor
reading.

SWITCH CASE STATEMENT


There comes a time in design, when we want to take action in relation to a
particular outcome, in a wide range of outcomes. Take, for example,
suppose you are trying to monitor the water level in the tank with an
ultrasonic sensor, you want to operate an LED for different levels of water
in the tank.
Suppose we are looking at 10 levels. In our Arduino code, we will have a
variable that records the distance of the water from the ultrasonic sensor, at
this distance; We can choose the levels we want.
To program the Arduino to illuminate the LEDs at the various levels that
we have chosen, we can use an "if statement". Using the 'if' statement, we
tell the microcontroller to turn on the LED if the distance recorded by the
ultrasound sensor is such-and-such. Using "if" would do well, but to make
the program neat we use the phrase "switch case".
Using an if statement will require us to repeat the statement for each level
we wish to perform. See the image below:

Figure 8: Using an if clause to define multiple conditions


On the other hand, a drawing using a switch case statement would look
like this:
Figure 9: Using the Switch Status Indication to implement conditional
codes
Line 1 code begins with the switch statement to start checking conditions.
Line 3 code checks status when variable distance is 50.
Line code 4 takes an action if the status 50 is true, that is, if the distance is
equal to 50
Line 5 code breaks the loop to a state state distance equal to 50.
Line 6 code checks a state distance of 100.
The process is repeated to check all conditions and breaks after calling the
break function. The switch case statement makes the drawing look neat and
smart.
Continue can be used to skip steps in the iteration process. Suppose you
count the numbers from 1 to 20 and at the same time you print them out on
the screen, you can use the continue phrase to skip printing some numbers
in repetition. See the code below.
Figure 10: Using the continue statement to move to the iteration steps
Line 1 code is repeated from 1 to 20
Line code creates 3 numbers for skip (5-8)
5 line icon calls skip function
Line code 7 prints all numbers from 1 to 20 apart from the numbers that
must be skipped
UNDERSTANDING ARRAYS IN ARDUINO
A rrays are collections of the same type of data that are consecutively
placed in memory. For example, we can have an array of integers (type int)
which are two or more integers occurring one by one.
The key here is that each element in the array is placed directly after the
previous one, allowing us to access each element in turn using a loop.
An element in an array indicates every value in the array. If we have a set
of integers, then each integer is referred to as an element of the matrix. In
an array of bytes, each element is a byte (of Arduino byte).

USING ARRAYS
The graphic below illustrates the basic use of a matrix.
voidsetup () {
int my_array[5]; // an array with 5 integer elements
int i; // used as an index into the array

Serial . begin (9600);

my_array[0] = 23; // assign a value of 23 to the 1st element


my_array[1] = 1001; // assign a value of 1001 to the 2nd element, etc.
my_array[2] = 9;
my_array[3] = 1234;
my_array[4] = 987;

// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial . println (my_array[i]);
}
}

voidloop () {
}

DEFINING THE ARRAY


In this diagram, a 5-element matrix is ​identified. This creates space in
memory for five integers to be placed in memory one after the other. The
values ​contained in each element after the array definition can contain any
random data - whatever happened in memory at that time. It is also
possible that the compiler is set to make the values ​zero, but we cannot
count on that.
Define an array of 5 integers:
int my_array[5]; // an array with 5 integer elements
In this example the array is of type int, but it can be floating, bytes, etc.
The array is named my_array in the example.
The array has a length [5], which means that the area of ​5 consecutive
integers is formed in the memory.

ASSIGN VALUES ​​TO ELEMENTS IN AN ARRAY


Each element is assigned an integer value by referencing it using square
brackets [] with the number of the item to be accessed in parentheses.
my_array[0] = 23;
my_array[1] = 1001;
my_array[2] = 9;
my_array[3] = 1234;
my_array[4] = 987;
Note that the element is numbered from zero [0] and not one [1], so the
first element in the array is element 0.
Likewise, the last element in the array is numbered one less than the size
of the matrix. In the example, the size of the matrix is ​5, so the last
element number is 4 - again because we are numbering the elements
starting at 0.

ACCESSING AN ARRAY IN A LOOP


The for loop is used to get the contents of every element in the array in
turn and print the values ​into the Serial Monitor window.
for (i = 0; i < 5; i++) {
Serial . println (my_array[i]);
}
The variable i is used in the for loop as a pointer in the matrix to access
each element of the matrix.
In the loop, i is initialized to 0 and then incremented one at a time
throughout the loop so it counts from 0 to 4. It is exited from the loop when
i becomes 5.
The variable i in the matrix is ​used to obtain the value that the matrix
element maintains starting with element 0 and ending with the number 4.
(my_array[i]);
In the above code snippet, when i is 0, the first element of the matrix is ​
accessed and we can then get the value it contains which is 23 in the
example drawing.

MORE ON CONFIGURING ARRAYS


Instead of initializing each element in an array separately, the array can be
defined and initialized on a single line as shown in this symbol.
This diagram does exactly the same as the previous one.
voidsetup () {
int my_array[5] = {23, 1001, 9, 1234, 987};
int i;

Serial . begin (9600);

// display each number from the array in the serial monitor window
for (i = 0; i < 5; i++) {
Serial . println (my_array[i]);
}
}

voidloop () {
}
The values ​to initialize each element are enclosed in brackets {} after the
assignment operator (equal sign =). The first value in parentheses will be
assigned to the first element in the array (element number 0), the second
number in parentheses will be assigned to the second element in the matrix
(element number 1), etc.
The code that defines and initializes without the number of elements in
the array can also be written in square brackets:
int my_array[] = {23, 1001, 9, 1234, 987};
In this case, the compiler will work to determine how many elements the
array should contain based on the number of values ​used in its
initialization.

USES OF ARRAYS
This part of the course demonstrates that arrays can store data variables of
the same type in succession in memory allowing easy access using a loop.
There are many uses for arrays in programming, for example, arrays can
store data that is recorded, such as temperatures. Strings, which are lines of
text, are actually arrays as we'll see in the next part of this cycle.
HOW TO USE STRINGS IN ARDUINO
S trings are used to store text. Can be used to display text on the LCD
screen or in the Arduino IDE Serial Monitor window.
Strings are also useful for storing user input - for example the characters a
user types on the keyboard connected to the Arduino.
There are two types of strings in Arduino programming:

Arrays of characters that are the same strings used in C


programming
Arduino String which allows us to use a String object in a diagram
Strings, objects, and how to use strings in Arduino graphics are fully
explained in this part of the Arduino programming course. The question of
what kind of sting to use for drawing is answered at the end of this article.

STRING CHARACTER ARRAYS


The first type of string we're going to look at is char. The previous part of
this course showed what an array is - a consecutive series of the same type
of variables stored in memory. A string is an array of char variables.
A text string is a special matrix with one additional element at the end of
the text that is always 0 (zero). This is known as a "null-terminated string."

STRING CHARACTER ARRAY EXAMPLE


This graphic will show how to make a series and print it in the serial
monitor window.
voidsetup () {
char my_str[6]; // an array big enough for a 5 character string

Serial . begin (9600);


my_str[0] = 'H' ; // the string consists of 5 characters
my_str[1] = 'e' ;
my_str[2] = 'l' ;
my_str[3] = 'l' ;
my_str[4] = 'o' ;
my_str[5] = 0; // 6th array element is a null terminator

Serial . println (my_str);


}

voidloop () {
}
The diagram shows what the string is made of - it consists of a character
array with printable characters and a 0 in the last element of the array to
show that this is where the string ends.
The series can be printed to the Arduino IDE Serial Monitor window
using Serial.println () and passed the name of the series.
This same diagram can be written more conveniently in this way:
voidsetup () {
char my_str[] = "Hello" ;

Serial . begin (9600);

Serial . println (my_str);


}
voidloop () {
}
In this diagram, the compiler calculates the size of the string matrix and
also the series terminates automatically with zero. The matrix of six
elements and of five characters followed by a zero is created in exactly the
same way as in the previous drawing.

STRINGS AND CHARACTERS


The letters are written between single quotes like this:
'w'
The strings are written in double quotes like this:
"This is a chain"

MANIPULATING STRING ARRAYS


voidsetup () {
char like[] = "I like coffee and cake" ; // create a string

Serial . begin (9600);

// (1) print the string


Serial . println (like);

// (2) delete part of the string


like[13] = 0;
Serial . println (like);
// (3) substitute a word into the string
like[13] = '' ; // replace the null terminator with a space
like[18] = 't' ; // insert the new word
like[19] = 'e' ;
like[20] = 'a' ;
like[21] = 0; // terminate the string
Serial . println (like);
}

voidloop () {
}

CREATE AND PRINT THE STRINGS


In this diagram, a new series is created and printed for display in the
Serial Monitor window (1).

SHORTEN THE STRING


The string is shortened by replacing the fourteenth letter in the chain with
a zero ending with zero (2). This is the 13th element in the counting string
group of 0.
When the string is printed, all characters are printed up to the new zero
ending in zero. The other characters do not disappear - they are still in
memory and the string array is still the same size. The only difference is
that any function that works with strings will only see the string until the
first null terminator.

CHANGE A WORD IN THE STRING


Finally, the diagram replaces the word “cake” with the word “tea” (3).
The zero-ending character such as [13] must first be replaced with a space
so that the string is restored to how it was originally created.
New characters write on "cak" to make "cake" with the word "tea". This
is done by overwriting the individual characters. The letter "e" for "cake" is
replaced with a new blank termination letter. The result is that the string is
effectively terminated with two blank characters - the original letter at the
end of the series and the new letter that replaces the letter "e" in "cake". It
makes no difference when printing the new string because the function that
prints the string stops printing the string characters when it encounters the
first blank final character.

FUNCTIONS FOR MANIPULATING STRING ARRAYS


The previous drawing handled the series in a very manual way by
accessing the individual characters in the series. To make it easier to work
with string arrays, you can write your own functions to do this, or use some
string functions from the C language library.
The following diagram uses some of the C series functions.
voidsetup () {
char str[] = "This is my string" ; // create a string
char out_str[40]; // output from string functions placed
here
int num; // general purpose integer

Serial . begin (9600);

// (1) print the string


Serial . println (str);
// (2) get the length of the string (excludes null terminator)
num = strlen(str);
Serial . print ( "String length is: " );
Serial . println (num);

// (3) get the length of the array (includes null terminator)


num = sizeof(str); // sizeof() is not a C string function
Serial . print ( "Size of the array: " );
Serial . println (num);

// (4) copy a string


strcpy(out_str, str);
Serial . println (out_str);

// (5) add a string to the end of a string (append)


strcat(out_str, " sketch." );
Serial . println (out_str);
num = strlen(out_str);
Serial . print ( "String length is: " );
Serial . println (num);
num = sizeof(out_str);
Serial . print ( "Size of the array out_str[]: " );
Serial . println (num);
}
voidloop () {
}
Drawing works in the following way.

PRINT THE STRING


The newly created series is printed on the Serial Monitor window as it
does in the previous graphics.

GET THE LENGTH OF THE STRING


The strlen () function is used to find the length of the string. The string
length is for printable characters only and does not include the blank
ending.
The series has 17 characters, so we see 17 prints in the Serial Monitor
window.

GET THE LENGTH OF THE ARRAY


The sizeof () operator is used to find the length of the array containing the
string. The length includes the zero ending character, so the length is one
more than the string length.
sizeof () looks like a function, but technically it is an operator. It is not
part of the C string library, but is used in the diagram to show the difference
between array size and string size (or string length).

COPY A STRING
The strcpy () function is used to copy the str [] string into the out_num []
array. Strcpy () copies the second string passed to it in the first string.
There is now a copy of the string in the out_num [] array, but it only
contains 18 elements of the array, so we still have 22 free elements in the
array. These free items are found after the series in memory.
The series is copied into the matrix so we have more space in the matrix
to use for the next portion of the chart adding a series to the end of the
series.

APPEND A STRING TO A STRING (CONCATENATED)


A chart links one chain to another, which is known as a series. This is
done using the strcat () function. The strcat () function places the second
string passed into it at the end of the first string passed to it.
After sequencing, the chain length is printed to show the new string
length. The length of the array is then printed to show that we have a string
of 25 characters in an array with a length of 40 elements.
Remember that the long string of 25 characters actually takes up the 26
characters of the array due to the zero ending in zero.

ARRAY BOUNDS
When working with strings and matrices, it is very important to work
within the boundaries of a string or matrix. In the example drawing, an
array of 40 characters is created to allocate memory that can be used to
manipulate the strings.
If the matrix is ​very small and we try to copy a larger string from the
matrix to it, then the series will be copied at the end of the matrix. The
memory behind the end of the array can contain other important data used
in the chart which will then be replaced by our series. If the memory
beyond the end of the series is exceeded, it may crash the drawing or cause
unexpected behavior.

A rduino S tring O bject


The second type of string used in programming the Arduino is the String
object.

WHAT IS AN OBJECT?
An object is a construct that contains both data and functions. String
object can be created just like a variable and set a value or a string. A
String object contains functions (called "methods" in object-oriented
programming (OOP) that operate on the string data contained in the String
object.
The following diagram and explanation will explain what an object is and
how to use a String object.
voidsetup () {
String my_str = "This is my string." ;

Serial . begin (9600);

// (1) print the string


Serial . println (my_str);

// (2) change the string to upper-case


my_str.toUpperCase();
Serial . println (my_str);

// (3) overwrite the string


my_str = "My new string." ;
Serial . println (my_str);

// (4) replace a word in the string


my_str.replace( "string" , "Arduino sketch" );
Serial . println (my_str);
// (5) get the length of the string
Serial . print ( "String length is: " );
Serial . println (my_str.length());
}

voidloop () {
}
A string object is created and assigned a value (or string) at the top of the
diagram.
String my_str = "This is my string." ;
This creates a String object with the name my_str and gives it the value
"This is my string".
This can be compared by creating a variable and assigning it a value like
an integer:
int my_var = 102;
(1) Print the string
The string can be printed in the Serial Monitor window just like the
Character Matrix string.
(2) Convert the string to uppercase
The my_str string object generated has a number of functions or methods
that can operate on it. These methods are called using the object name
followed by the period operator (.) And then the function name to use.
my_str.toUpperCase();
The toUpperCase () function works on the string contained in the my_str
object and is of type String and converts the string data (or text) the object
contains to uppercase.
A list of the functions that the String class contains can be found in the
Arduino String reference.
Technically, String is called a class and is used to create String objects.
(3) Overwrite a string
The reference operator is used to assign a new string to the my_str object
that replaces the old string.
my_str = "My new string." ;
The assignment operator cannot be used on character array strings, it only
works on string objects.
(4) Replace a word in the string
The replace () function is used to replace the first string passed into it by
the second string it is passed to. replace () is another function included in
the String class and is available for use on the String my_str object.
(5) Get the length of the string
Thread length can be easily obtained using length (). In the example
drawing, the result returned by length () is passed directly to Serial.println
() without using an intermediate variable.

WHEN TO USE A STRING OBJECT OR A STRING


CHARACTER ARRAY
String Object is easier to use than String Character Matrix. The object has
built-in functions that can perform a number of operations on strings that
are fully documented in the references section on the Arduino website.
The main disadvantage of using a String object is that it uses a lot of
memory and can quickly use the Arduino's RAM which may cause the
Arduino to freeze, crash, or produce unexpected behavior. This is
especially true for smaller Arduinos like the Arduino Uno.
If the drawing on the Arduino is small and limits the use of objects, then
there should be no problems.
Character matrix strings are difficult to use and you may need to write
your own functions to work on these types of strings. The advantage is that
you can control the size of the string arrays you create, so that you can keep
the arrays small to save memory.
You need to ensure that the end of the bounds of the array is not
overwritten with string matrices. String Object doesn't have this problem
and will take care of string boundaries for you, provided there is enough
memory to run. String object can try to write to non-existent memory when
it runs out of memory, but it will never write at the end of the string it is
working on.

WHERE STRINGS ARE USED


This part of the Arduino programming course covered what strings are,
what they look like in memory, and some operations that can be performed
on strings.
The actual practical uses of strings will be covered in the next part of this
course when we look at how to obtain user input from the Serial Monitor
window and save entries to a string.
ARDUINO PROJECT SAMPLE

ARDUINO LIE DETECTOR


O ur skin provides a way for us to experiment with our sense of touch, it
keeps infections away and keeps the indoor spaces but I bet you didn't know
that our skin changes conductivity depending on so many different things
one of which is our mood! It's called Electrodermal Activity (EDA). The
basics is that our skin changes its conductivity depending on how we feel.

COMPONENTS AND SUPPLIES


✓ Arduino Nano R3
✓ 5 mm LED: red
✓ 5 mm LED: green
✓ LED (general)
✓ Resistor 2K
✓ Cables

NECESSARY TOOLS AND MACHINES


✓ Soldering iron (general)
✓ Hot glue gun (general)
✓ Welding wire

ONLINE APPLICATIONS AND SERVICES


✓ Arduino IDE
Step 1:
We start by connecting our Arduino to the thread and then connecting the
Arduino to a computer using the graphic software (I will cover this in detail
later)
We have to start by asking some easy questions on the topic that we know
will answer truthfully like "What is your name" and "Where do you live" to
get a baseline and from there we can start asking questions that they might
lie about, if they do that they might feel nervous and then we can Read the
change in previously established baseline if they lie:
Step 2:
We need, Aruino Nano, some bulbs, Velcro, 2K resistors and some basic
tools like cardboard, foil, hot glue, soldering iron, and craft knife.
Step 3: Wiring

The wires for this are very easy to do, we'll start connecting them in this
order:

Connect a long piece of cable to the analog Arduino pin 0


Connect the 2k resistor to ground and the extended analog pin 0
Connect a long piece of cable to the 5V Arduinos screw
Connect the anode (long leg) of the green lamp to Pin 2 and the
cathode (short leg) to the ground
Connect the anode of the orange lamp to Pin 3 and the cathode to
the ground
Connect the red LED's anode to Pin 4 and the cathode to ground
That's all about the Arduino wiring, now we need a way to keep the
sensor wires on our fingers and we'll cover this later.
Step 4: the program and the code

The main part of the program that we will be using is the latest version on
the Arduino IDE. The new update brings a new way to see the data that is
received from the Arduino, instead of being in text form from the serial
monitor, it can now be displayed in a graph in real time which will help us
determine when the data changes its pattern (when someone is lying)
To open the plotter, open the Arduino and go to the Tools menu and you'll
see there right below the serial screen.
Now the icon for the micro controller is in the code section below. Copy
it and upload it to your board.
Step 5: making the finger clips
Now that we've finished the basic look of the project, we can start adding
features to make it easier to use, we'll start adding finger clips to keep a
steady connection between our fingers and the cables. Let's start by
sticking a strip of tin foil to the bottom of the velcro tape, do this for each of
the two pieces of Velcro (hook and loop. Now tie it around your finger until
it fits tight (check pictures) then attach an exposed wire from the analog pin
0 to the tin foil and repeat this Step for pin 5V (make sure it makes good
contact)
Step 6: Making the case
The plan is to make a small chamber to fold the finger pads away and
have three holes for the bulbs to stick out. It will be made of cardboard and
for its work we will need to cut out the following shapes:

✓ Cut two 15 x 3 cm rectangles


✓ One rectangle 15 x 5 cm
✓ Three 5 x 3 cm rectangles (square cut in the middle on one for nanos
usb)
✓ Rectangle 9 x 5 cm
✓ A rectangle measuring 6 x 5 cm
The rectangle 15 x 5 is the base. Two 15x3 rectangles and two 5x3
rectangles are glued to the sides of the base. Now paste the third rectangle
5 x 3 to the base 6 cm from the side (near the middle, check the pictures)
Now you should have a rectangle divided into two sides, one of which is 6
cm long and the other is 9 cm long. The side that is 6cm is where we will
place the electronics and the other side is where the finger pads will be
placed. Then cut 3 holes (the size of the bulbs) on the 6 x 5 rectangle and
tape them to the 6 cm side (as a cover). Finally, we need to glue the short
side of the 9 x 5 rectangle to the far side of the 9 cm side (this acts as a
cover that flips up and down to reveal the finger pads)
Step 7: put it all together
The last thing we need to do is place the electronics in the case starting by
gluing the Arduino and all the wires to the 6 cm side and running the
extended wires (analog pin 0 and 5V) to the other side of the rectangle (9
cm) side). Now stick the three bulbs into the holes we made on the 6 x 5
cm rectangle and test it if all goes well you should have a small Arduino
portable lie detector but let me warn you that this is not the most accurate
system in fact most polygraphs use The real set of other sensors to
determine if someone is lying like a heart rate monitor and others.
CODE
PolyGraph.ino Arduino
Paste the code into the arduino ide
void setup ()
{
​Serial . begin ( 9600 );
​pinMode ( 2 , OUTPUT );
​pinMode ( 3 , OUTPUT );
​pinMode ( 4 , OUTPUT );
​digitalWrite ( 2 , HIGH );
​delay ( 500 );
​digitalWrite ( 3 , HIGH );
​delay ( 500 );
​digitalWrite ( 4 , HIGH );
​delay ( 500 );
}

void loop ()
{
​if ( analogRead ( A0 ) >60 )
​{
​digitalWrite ( 4 , HIGH );
}
​else
​{
​digitalWrite ( 4 , LOW );
​}
​if ( analogRead ( A0 ) >20 )
​{
​digitalWrite ( 2 , HIGH );
​}
​else
​{
​digitalWrite ( 2 , LOW );
​}
​if ( analogRead ( A0 ) >45 )
​{
​digitalWrite ( 3 , HIGH );
​}
​else
​{
​digitalWrite ( 3 , LOW );
​}

​Serial . println ( analogRead ( A0 ));


​delay ( 20 );
}
CONCLUSION
W hile some of Arduino's projects may seem trivial, the technology is
already taking advantage of a number of trends that will make it a potential
important force in the industry. The "Internet of Things" is a common
phrase used in the technology community to describe everyday items that
are connected to the Internet and are able to share information. Smart
energy meters are an often used example that can regulate device usage to
save money on energy. Many consider the Internet of Things to be an
important part of a broadly defined phenomenon called Web 3.0
Also, the ubiquitous computing concept is fast becoming a cultural norm.
General perception and comfort level shift towards integrating technology
into the fabric of everyday life. The Arduino's small form factor allows it to
be applied in all kinds of everyday things. In fact, the Arduino LilyPad
form factor allows for Arduino wearables.
Open source projects like Arduino reduce the barrier of entry for
developers looking to experiment with interactive objects. This will create
an opportunity for a new wave of energy and startups to create the Internet
of Things. These innovators will be able to quickly prototype and test
interactive devices using the Arduino platform, before building a
production-ready demonstration. The next Mark Zuckerberg or Steve Jobs
may one day be found creating new ways for computers to interact with the
physical world. It would be wise to pay attention to this space, and the
Arduino is a great way to "immerse your toes" in the possibilities of
interactive objects.

You might also like