Arduino Tutorial
Arduino Tutorial
Arduino
Audience
This tutorial is intended for enthusiastic students or hobbyists. With Arduino, one can get
to know the basics of micro-controllers and sensors very quickly and can start building
prototype with very little investment.
Prerequisites
Before you start proceeding with this tutorial, we assume that you are already familiar
with the basics of C and C++. If you are not well aware of these concepts, then we will
suggest you go through our short tutorials on C and C++. A basic understanding of
microcontrollers and electronics is also expected.
Arduino
Table of Contents
About the Tutorial ............................................................................................................................................ i
Audience ........................................................................................................................................................... i
Prerequisites ..................................................................................................................................................... i
Copyright & Disclaimer ..................................................................................................................................... i
Table of Contents ............................................................................................................................................ ii
Arduino
Arduino
iv
Arduino
Arduino
Arduino Basics
Arduino Overview
Arduino
Arduino boards are able to read analog or digital input signals from different
sensors and turn it into an output such as activating a motor, turning LED on/off,
connect to the cloud and many other actions.
You can control your board functions by sending a set of instructions to the
microcontroller on the board via Arduino IDE (referred to as uploading software).
Unlike most previous programmable circuit boards, Arduino does not need an extra
piece of hardware (called a programmer) in order to load a new code onto the
board. You can simply use a USB cable.
Additionally, the Arduino IDE uses a simplified version of C++, making it easier to
learn to program.
Finally, Arduino provides a standard form factor that breaks the functions of the
micro-controller into a more accessible package.
Arduino
Board Types
Various kinds of Arduino boards are available depending on different microcontrollers used.
However, all Arduino boards have one thing in common: they are programed through the
Arduino IDE.
The differences are based on the number of inputs and outputs (the number of sensors,
LEDs, and buttons you can use on a single board), speed, operating voltage, form factor
etc. Some boards are designed to be embedded and have no programming interface
(hardware), which you would need to buy separately. Some can run directly from a 3.7V
battery, others need at least 5V.
Arduino
Here is a list of different Arduino boards available.
Arduino boards based on ATMEGA328 microcontroller
Operating
Volt
Clock
Speed
Digital
i/o
Analog
Inputs
PWM
UART
Arduino Uno
R3
5V
16MHz
14
USB via
ATMega16U2
Arduino Uno
R3 SMD
5V
16MHz
14
USB via
ATMega16U2
Red Board
5V
16MHz
14
Arduino Pro
3.3v/8 MHz
3.3V
8 MHz
14
FTDICompatible
Header
Arduino Pro
5V/16MHz
5V
16MHz
14
FTDICompatible
Header
Arduino mini
05
5V
16MHz
14
FTDICompatible
Header
Arduino Pro
mini
3.3v/8mhz
3.3V
8MHz
14
FTDICompatible
Header
Arduino Pro
mini
5v/16mhz
5V
16MHz
14
FTDICompatible
Header
Arduino
Ethernet
5V
16MHz
14
FTDICompatible
Header
Arduino Fio
3.3V
8MHz
14
FTDICompatible
Header
LilyPad
Arduino 328
main board
3.3V
8MHz
14
FTDICompatible
Header
LilyPad
Arduino
simply board
3.3V
8MHz
FTDICompatible
Header
Board Name
Programming
Interface
Arduino
Arduino boards based on ATMEGA32u4 microcontroller
Operating
Volt
Clock
Speed
Digital
i/o
Analog
Inputs
PWM
UART
Programming
Interface
Arduino
Leonardo
5V
16MHz
20
12
Native USB
Pro micro
5V/16MHz
5V
16MHz
14
Native USB
Pro micro
3.3V/8MHz
5V
16MHz
14
Native USB
3.3V
8MHz
14
Native USB
Board Name
LilyPad
Arduino USB
Operating
Volt
Clock
Speed
Digital
i/o
Analog
Inputs
PWM
UART
5V
16MHz
54
16
14
USB via
ATMega16U2
Mega Pro
3.3V
3.3V
8MHz
54
16
14
FTDICompatible
Header
Mega Pro
5V
5V
16MHz
54
16
14
FTDICompatible
Header
3.3V
8MHz
54
16
14
FTDICompatible
Header
Arduino
Mega 2560
R3
Mega Pro
Mini
3.3V
Programming
Interface
Operating
Volt
Clock
Speed
Digital
i/o
Analog
Inputs
PWM
UART
Programming
Interface
Arduino
Due
3.3V
84MHz
54
12
12
USB native
Arduino
In this chapter, we will learn about the different components on the Arduino board. We
will study the Arduino UNO board because it is the most popular board in the Arduino
board family. In addition, it is the best board to get started with electronics and coding.
Some boards look a bit different from the one given below, but most Arduinos have
majority of these components in common.
Power USB
Arduino board can be powered by using the USB cable from your computer. All you need
to do is connect the USB cable to the USB connection (1).
Arduino
Voltage Regulator
The function of the voltage regulator is to control the voltage given to the Arduino board
and stabilize the DC voltages used by the processor and other elements.
Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues. How does Arduino calculate
time? The answer is, by using the crystal oscillator. The number printed on top of the
Arduino crystal is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz.
Arduino Reset
You can reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways. First, by using the reset button (17) on the board.
Second, you can connect an external reset button to the Arduino pin labelled RESET (5).
Most of the components used with Arduino board works fine with 3.3 volt
and 5 volt.
GND (8)(Ground): There are several GND pins on the Arduino, any of which
can be used to ground your circuit.
Vin (9): This pin also can be used to power the Arduino board from an
external power source, like AC mains power supply.
Analog pins
The Arduino UNO board has five analog input pins A0 through A5. These pins can read the
signal from an analog sensor like the humidity sensor or temperature sensor and convert
it into a digital value that can be read by the microprocessor.
Arduino
Main microcontroller
Each Arduino board has its own microcontroller (11). You can assume it as the brain of
your board. The main IC (integrated circuit) on the Arduino is slightly different from board
to board. The microcontrollers are usually of the ATMEL Company. You must know what
IC your board has before loading up a new program from the Arduino IDE. This information
is available on the top of the IC. For more details about the IC construction and functions,
you can refer to the data sheet.
ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the Arduino consisting of
MOSI, MISO, SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial Peripheral
Interface), which could be considered as an "expansion" of the output. Actually, you are
slaving the output device to the master of the SPI bus.
TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX (receive). They appear in
two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the pins
responsible for serial communication. Second, the TX and RX led (13). The TX led flashes
with different speed while sending the serial data. The speed of flashing depends on the
baud rate used by the board. RX flashes during the receiving process.
Digital I / O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse
Width Modulation) output. These pins can be configured to work as input digital pins to
read logic values (0 or 1) or as digital output pins to drive different modules like LEDs,
relays, etc. The pins labeled ~ can be used to generate PWM.
AREF
AREF stands for Analog Reference. It is sometimes, used to set an external reference
voltage (between 0 and 5 Volts) as the upper limit for the analog input pins.
Arduino Installation
Arduino
After learning about the main parts of the Arduino UNO board, we are ready to learn how
to set up the Arduino IDE. Once we learn this, we will be ready to upload our program on
the Arduino board.
In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer
and prepare the board to receive the program via USB cable.
Step 1: First you must have your Arduino board (you can choose your favorite board) and
a USB cable. In case you use Arduino UNO, Arduino Duemilanove, Nano, Arduino Mega
2560, or Diecimila, you will need a standard USB cable (A plug to B plug), the kind you
would connect to a USB printer as shown in the following image.
In case you use Arduino Nano, you will need an A to Mini-B cable instead as shown in the
following image.
Arduino
10
Arduino
11
Arduino
To open an existing project example, select File -> Example -> Basics -> Blink.
12
Arduino
Here, we are selecting just one of the examples with the name Blink. It turns the LED on
and off with some time delay. You can select any other example from the list.
Step 6: Select your Arduino board.
To avoid any error while uploading your program to the board, you must select the correct
Arduino board name, which matches with the board connected to your computer.
Go to Tools -> Board and select your board.
13
Arduino
Here, we have selected Arduino Uno board according to our tutorial, but you must select
the name matching the board that you are using.
14
Arduino
Step 7: Select your serial port.
Select the serial device of the Arduino board. Go to Tools -> Serial Port menu. This is
likely to be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial
ports). To find out, you can disconnect your Arduino board and re-open the menu, the
entry that disappears should be of the Arduino board. Reconnect the board and select that
serial port.
15
Arduino
16
Arduino
In this chapter, we will study in depth, the Arduino program structure and we will learn
more new terminologies used in the Arduino world. The Arduino software is open-source.
The source code for the Java environment is released under the GPL and the C/C++
microcontroller libraries are under the LGPL.
Sketch: The first new terminology is the Arduino program called sketch.
Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions. In this tutorial, we will learn about the Arduino software
program, step by step, and how we can write the program without any syntax or
compilation error.
Let us start with the Structure. Software structure consist of two main functions:
Setup( ) function
Loop( ) function
17
Arduino
Void setup ( )
{
}
PURPOSE: The setup() function is called when a sketch starts. Use it to initialize
the variables, pin modes, start using libraries, etc. The setup function will only run
once, after each power up or reset of the Arduino board.
INPUT:
OUTPUT:
RETURN:
Void Loop ( )
{
}
PURPOSE: After creating a setup() function, which initializes and sets the initial
values, the loop() function does precisely what its name suggests, and loops
consecutively, allowing your program to change and respond. Use it to actively
control the Arduino board.
INPUT:
OUTPUT:
RETURN:
18
Arduino
Data types in C refers to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in the
storage and how the bit pattern stored is interpreted.
The following table provides all the data types that you will use during Arduino
programming.
void
Boolean
char
Unsigned
char
byte
int
Unsigned int
word
long
Unsigned
long
short
float
double
array
String-char
array
String-object
void
The void keyword is used only in function declarations. It indicates that the function is
expected to return no information to the function from which it was called.
Example
Void Loop ( )
{
// rest of the code
}
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte
of memory.
Example
boolean val = false ; // declaration of variable with type boolean and initialize
it with false
boolean state = true ;
initialize it with false
//
19
Arduino
Char
A data type that takes up one byte of memory that stores a character value. Character
literals are written in single quotes like this: 'A' and for multiple characters, strings use
double quotes: "ABC".
However, characters are stored as numbers. You can see the specific encoding in the ASCII
chart. This means that it is possible to do arithmetic operations on characters, in which
the ASCII value of the character is used. For example, 'A' + 1 has the value 66, since the
ASCII value of the capital letter A is 65.
Example
Char
chr_a = a ;//declaration of variable with type char and initialize it
with character a
Char
chr_c = 97 ;//declaration of variable with type char and initialize it
with character 97
20
Arduino
unsigned char
Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned
char data type encodes numbers from 0 to 255.
Example
Unsigned Char
chr_y = 121 ;
// declaration of variable with type Unsigned
char and initialize it with character
y
byte
A byte stores an 8-bit unsigned number, from 0 to 255.
Example
byte
25
int
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value.
This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value
of (2^15) - 1).
The int size varies from board to board. On the Arduino Due, for example, an int stores a
32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum
value of -2^31 and a maximum value of (2^31) - 1).
Example
int counter = 32 ;// declaration of variable with type int and initialize it with
32
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte
value. Instead of storing negative numbers, however, they only store positive values,
yielding a useful range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value,
ranging from 0 to 4,294,967,295 (2^32 - 1).
Example
Unsigned int counter= 60 ; // declaration of variable with type unsigned int and
initialize it with 60
Word
On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On
the Due and Zero, it stores a 32-bit unsigned number.
21
Arduino
Example
word w = 1000 ;//declaration of variable with type word and initialize it with
1000
Long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes),
from 2,147,483,648 to 2,147,483,647.
Example
Long velocity= 102346 ;//declaration of variable with type
it with
102346
unsigned long
Unsigned long variables are extended size variables for number storage and store 32 bits
(4 bytes). Unlike standard longs, unsigned longs will not store negative numbers, making
their range from 0 to 4,294,967,295 (2^32 - 1).
Unsigned Long velocity = 101006 ;// declaration of variable with type Unsigned
Long and initialize it with 101006
short
A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a
16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15
and a maximum value of (2^15) - 1).
short val= 13 ;//declaration of variable with type short and initialize it with
13
float
Data type for floating-point number is a number that has a decimal point. Floating-point
numbers are often used to approximate the analog and continuous values because they
have greater resolution than integers.
Floating-point numbers can be as large as 3.4028235E+38 and as low as 3.4028235E+38.
They are stored as 32 bits (4 bytes) of information.
float num = 1.352;//declaration of variable with type
with 1.352
22
Arduino
double
On the Uno and other ATMEGA based boards, Double precision floating-point number
occupies four bytes. That is, the double implementation is exactly the same as the float,
with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit) precision.
double num = 45.352 ;// declaration of variable with type double and initialize
it with
45.352
23
Arduino
Before we start explaining the variable types, a very important subject we need to make
sure, you fully understand is called the variable scope.
Local Variables
Variables that are declared inside a function or block are local variables. They can be used
only by the statements that are inside that function or block of code. Local variables are
not known to function outside their own. Following is the example using local variables:
Void setup ()
{
}
Void loop ()
{
int
int
x , y ;
z ;
x=
0;
y=0;
actual initialization
z=10;
}
Global Variables
Global variables are defined outside of all the functions, usually at the top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available
for use throughout your entire program after its declaration.
24
Arduino
The following example uses global and local variables:
Int T , S ;
float c =0 ; Global variable declaration
Void setup ()
{
}
Void loop ()
{
int
int
x , y ;
x=
0;
25
Arduino Operators
Arduino
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators:
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then Operator
name
Operator
simple
Description
assignment
operator
A=B
addition
A + B will give 30
subtraction
multiplication
division
B / A will give 2
modulo
B % A will give 0
Example
Example
void loop ()
{
int a=9,b=4,c;
c=a+b;
c=a-b;
26
Arduino
c=a*b;
c=a/b;
c=a%b;
}
Result
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1
Comparison Operators
Assume variable A holds 10 and variable B holds 20 then Operator
name
Operator
simple
Description
Example
equal to
==
(A == B) is not
true
not equal to
!=
(A != B) is true
<
(A < B) is true
>
<=
(A <= B) is true
>=
(A >= B) is not
true
less than
greater than
less than or
equal to
greater than
or equal to
27
Arduino
Example
void loop ()
{
int a=9,b=4
bool c = false;
if(a==b)
c=true;
else
c=false;
if(a!=b)
c=true;
else
c=false;
if(a<b)
c=true;
else
c=false;
if(a>b)
c=true;
else
c=false;
if(a<=b)
c=true;
else
c=false;
if(a>=b)
c=true;
else
c=false;
}
28
Arduino
Result
c=false
c=true
c= false
c=true
c= false
c= false
Boolean Operators
Assume variable A holds 10 and variable B holds 20 then Operator
name
and
Operator
simple
Description
&&
(A && B) is true
||
(A || B) is true
or
not
Example
Example
void loop ()
{
int a=9,b=4
bool c = false;
if((a>b)&& (b<a))
c=true;
else
c=false;
if((a==b)|| (b<a))
c=true;
else
c=false;
29
Arduino
Result
c=true
c=true
c= true
Bitwise Operators
Assume variable A holds 10 and variable B holds 20 then Operator
name
Operator
simple
Description
Example
and
&
or
(A | B) will give 61
which
is
0011
1101
xor
(A ^ B) will give
49 which is 0011
0001
not
<<
>>
shift left
shift right
30
Arduino
Example
void loop ()
{
int a=10,b=20
int c = 0;
c= a & b ;
c= a | b ;
c= a ^ b ;
c= a ~ b ;
c= a << b ;
c= a >> b ; }
Result
c=12
c=61
c= 49
c=-60
c=240
c=15
Compound Operators
Assume variable A holds 10 and variable B holds 20 then Operator
name
Operator
simple
increment
++
Increment
operator,
integer value by one
increases
decrement
--
Decrement
operator,
integer value by one
decreases
compound
addition
+=
B += A is
equivalent to B =
B+ A
-=
B -= A is
equivalent to B =
B-A
compound
subtraction
Description
Example
A++ will give 11
A-- will give 9
31
Arduino
*=
B*= A is
equivalent to B =
B* A
compound
division
/=
B /= A is
equivalent to B =
B/A
compound
modulo
%=
B
%=
A
is
equivalent to B =
B%A
compound
bitwise or
|=
A |= 2 is same as
A=A|2
compound
bitwise and
&=
A &= 2 is same as
A=A&2
compound
multiplication
Example
void loop ()
{
int a=10,b=20
int c = 0;
a++;
a--;
b+=a;
b-=a;
b*=a;
b/=a;
a%=b;
a|=b;
a&=b;
}
Result
a=11
a=9
b=30
b=10
b=200
b=2
a=0
a=61
a=12
32
Arduino
Decision making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program. It should be along with a statement or
statements to be executed if the condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages
Control Statements are elements in Source Code that control the flow of program
execution. They are:
If statement
If else statement
Conditional Operator ? :
33
Arduino
if statement
It takes an expression in parenthesis and a statement or block of statements. If the
expression is true then the statement or block of statements gets executed otherwise
these statements are skipped.
34
Arduino
Example
/* Global variable definition */
int
A = 5 ;
int
B=
9 ;
Void setup ()
{
}
Void loop ()
{
/* check the boolean condition */
if (A > B)
A++;
/* check the boolean condition */
If ( ( A>B ) && ( B!=0 )) /* if condition is true then execute
statement*/
{
the following
A+=B;
B--;
}
If else statement
An if statement can be followed by an optional else statement, which executes when the
expression is false.
35
Arduino
Example
/* Global variable definition */
int
A = 5 ;
int
B=
9 ;
Void setup ()
{
}
Void loop ()
{
/* check the boolean condition */
if (A > B)
{
A++;
}
else
{
B -= A;
}
}
36
Arduino
An if can have zero or one else statement and it must come after any else if's.
An if can have zero to many else if statements and they must come before the
else.
Once an else if succeeds, none of the remaining else if or else statements will be
tested.
37
Arduino
Example
/* Global variable definition */
int
A = 5 ;
int
B=
9 ;
int c=15;
Void setup ()
{
}
Void loop ()
{
/* check the boolean condition */
if (A > B)
38
Arduino
{
A++;
}
/* check the boolean condition */
else if ((A==B )||( B < c) ) /* if condition is true then execute
following statement*/
{
C =B* A;
}
the
else
c++;
}
39
Arduino
}
}
Example
Here is a simple example with switch. Suppose we have a variable phase with only 3
different states (0, 1, or 2) and a corresponding function (event) for each of these states.
This is how we could switch the code to the appropriate routine:
switch (phase)
{
case 0: Lo();
break;
break;
40
Arduino
Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C.
Example
/* Find max(a, b): */
max = ( a > b ) ? a : b;
/* Convert small letter to capital: */
/* (no parentheses are actually necessary) */
c = ( c >= 'a' && c <= 'z' ) ? ( c - 32 ) : c;
41
Arduino Loops
Arduino
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages
while loop
dowhile loop
for loop
nested loop
infinite loop
while loop
while loops will loop continuously, and infinitely, until the expression inside the
parenthesis, () becomes false. Something must change the tested variable, or the while
loop will never exit.
42
Arduino
dowhile loop
The dowhile loop is similar to the while loop. In the while loop, the loop-continuation
condition is tested at the beginning of the loop before performed the body of the loop. The
dowhile statement tests the loop-continuation condition after performed the loop body.
Therefore, the loop body will be executed at least once.
When a dowhile terminates, execution continues with the statement after the while
clause. It is not necessary to use braces in the dowhile statement if there is only one
statement in the body. However, the braces are usually included to avoid confusion
between the while and dowhile statements.
43
Arduino
for loop
A for loop executes statements a predetermined number of times. The control expression
for the loop is initialized, tested and manipulated entirely within the for loop parentheses.
It is easy to debug the looping behavior of the structure as it is independent of the activity
inside the loop.
Each for loop has up to three expressions, which determine its operation. The following
example shows general for loop syntax. Notice that the three expressions in the for loop
argument parentheses are separated with semicolons.
Example
for(counter=2;counter <=9;counter++)
{
//statements block will executed 10 times
}
44
Arduino
Nested Loop
C language allows you to use one loop inside another loop. The following example
illustrates the concept.
Infinite loop
It is the loop having no terminating condition, so the loop becomes infinite.
45
Arduino
2. Using while loop
while(1)
{
// statement block
}
3. Using dowhile loop
do{
Block of statements;
} while(1);
46
Arduino - Functions
Arduino
Functions allow structuring the programs in segments of code to perform individual tasks.
The typical case for creating a function is when one needs to perform the same action
multiple times in a program.
Standardizing code fragments into functions has several advantages:
Functions help the programmer stay organized. Often this helps to conceptualize
the program.
Functions codify one action in one place so that the function only has to be thought
about and debugged once.
This also reduces chances for errors in modification, if the code needs to be
changed.
Functions make the whole sketch smaller and more compact because sections of
code are reused many times.
They make it easier to reuse code in other programs by making it modular, and
using functions often makes the code more readable.
There are two required functions in an Arduino sketch or a program i.e. setup () and loop().
Other functions must be created outside the brackets of these two functions.
The most common syntax to define a function is:
47
Arduino
Function Declaration
A function is declared outside any other functions, above or below the loop function.
We can declare the function in two different ways 1. The first way is just writing the part of the function called a function prototype above
the loop function, which consists of:
Function name
Example
int sum_func (int
x, int y)
// function declaration
{
int z=0;
z= x+y ;
return z;
}
void setup ()
48
Arduino
{
Statements
// group of statements
}
Void loop ()
{
int
result =0 ;
// function call
}
2. The second part, which is called the function definition or declaration, must be declared
below the loop function, which consists of
Function name
Function argument type, here you must add the argument name
The function body (statements inside the function executing when the function is
called)
The following example demonstrates the declaration of function using the second method.
Example
int
sum_func
(int , int )
// function prototype
void setup ()
{
Statements
// group of statements
}
Void loop ()
{
int
result =0 ;
// function call
x, int y)
// function declaration
{
int z=0;
z= x+y ;
return z;
49
Arduino
The second method just declares the function above the loop function.
50
Arduino Strings
Arduino
Strings are used to store text. They can be used to display text on an LCD or in the Arduino
IDE Serial Monitor window. Strings are also useful for storing the user input. For example,
the characters that a user types on a keypad connected to the Arduino.
There are two types of strings in Arduino programming:
Arrays of characters, which are the same as the strings used in C programming.
In this chapter, we will learn Strings, objects and the use of strings in Arduino sketches.
By the end of the chapter, you will learn which type of string to use in a sketch.
Serial.begin(9600);
my_str[0] = 'H';
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0;
Serial.println(my_str);
}
void loop()
{ }
51
Arduino
The following example shows what a string is made up of; a character array with printable
characters and 0 as the last element of the array to show that this is where the string
ends. The string can be printed out to the Arduino IDE Serial Monitor window by using
Serial.println() and passing the name of the string.
This same example can be written in a more convenient way as shown below:
Example
void setup()
{
char my_str[] = "Hello";
Serial.begin(9600);
Serial.println(my_str);
}
void loop()
{
}
In this sketch, the compiler calculates the size of the string array and also automatically
null terminates the string with a zero. An array that is six elements long and consists of
five characters followed by a zero is created exactly the same way as in the previous
sketch.
Example
void setup()
{
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] = ' ';
like[18] = 't';
like[19] = 'e';
like[20] = 'a';
52
Arduino
like[21] = 0;
Serial.println(like);
}
void loop()
{
}
Result
I like coffee and cake
I like coffee
I like coffee and tea
53
Arduino
Description
String()
The String class, part of the core as of version 0019, allows you
to use and manipulate strings of text in more complex ways
than character arrays do. You can concatenate Strings, append
to them, search for and replace substrings, and more. It takes
more memory than a simple character array, but it is also more
useful.
For reference, character arrays are referred to as strings with
a small s, and instances of the String class are referred to as
Strings with a capital S. Note that constant strings, specified in
"double quotes" are treated as char arrays, not instances of the
String class
charAt()
compareTo()
concat()
c_str()
endsWith()
equals()
Compares two strings for equality. The comparison is casesensitive, meaning the String "hello" is not equal to the String
"HELLO".
equalsIgnoreCase()
Compares two strings for equality. The comparison is not casesensitive, meaning the String("hello") is equal to the
String("HELLO").
getBytes()
indexOf()
54
Arduino
from a given index, allowing to locate all instances of the
character or String.
lastIndexOf()
length()
remove()
replace()
reserve()
setCharAt()
startsWith()
toCharArray()
substring()
toInt()
toFloat()
toLowerCase()
toUpperCase()
55
Arduino
Get a version of the String with any leading and trailing
whitespace removed. As of 1.0, trim() modifies the string in
place rather than returning a new one.
trim()
Example
void setup()
{
char str[] = "This is my string";
// create a string
char out_str[40];
int num;
Serial.begin(9600);
56
Arduino
num = sizeof(out_str);
Serial.print("Size of the array out_str[]: ");
Serial.println(num);
}
void loop()
{
}
Result
This is my string
String length is: 17
Size of the array: 18
This is my string
This is my string sketch.
String length is: 25
Size of the array out_str[]: 40
57
Arduino
22 free char elements in the array. These free elements are found after the string in
memory.
The string was copied to the array so that we would have some extra space in the array
to use in the next part of the sketch, which is adding a string to the end of a string.
Array Bounds
When working with strings and arrays, it is very important to work within the bounds of
strings or arrays. In the example sketch, an array was created, which was 40 characters
long, in order to allocate the memory that could be used to manipulate strings.
If the array was made too small and we tried to copy a string that is bigger than the array
to it, the string would be copied over the end of the array. The memory beyond the end
of the array could contain other important data used in the sketch, which would then be
overwritten by our string. If the memory beyond the end of the string is overrun, it could
crash the sketch or cause unexpected behavior.
58
Arduino
The second type of string used in Arduino programming is the String Object.
What is an Object?
An object is a construct that contains both data and functions. A String object can be
created just like a variable and assigned a value or string. The String object contains
functions (which are called "methods" in object oriented programming (OOP)) which
operate on the string data contained in the String object.
The following sketch and explanation will make it clear what an object is and how the
String object is used.
Example
void setup()
{
}
void loop()
{ }
59
Arduino
Result
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22
A string object is created and assigned a value (or string) at the top of the sketch.
String my_str = "This is my string." ;
This creates a String object with the name my_str and gives it a value of "This is my
string.".
This can be compared to creating a variable and assigning a value to it such as an integer:
int my_var = 102;
The sketch works in the following way.
60
Arduino
61
Arduino Time
Arduino
delay () function
delayMicroseconds () function
millis () function
micros () function
delay() function
The way the delay() function works is pretty simple. It accepts a
number) argument. This number represents the time (measured in
program should wait until moving on to the next line of code when
function. However, the problem is, the delay() function is not a good
program wait, because it is known as a blocking function.
*/
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop()
{
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
62
Arduino
delayMicroseconds() function
The delayMicroseconds() function accepts a single integer (or number) argument. This
number represents the time and is measured in microseconds. There are a thousand
microseconds in a millisecond, and a million microseconds in a second.
Currently, the largest value that can produce an accurate delay is 16383. This may change
in future Arduino releases. For delays longer than a few thousand microseconds, you
should use the delay() function instead.
*/
int ledPin = 13; // LED connected to digital pin 13
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() {
digitalWrite(ledPin, HIGH); // sets the LED on
delayMicroseconds(1000);
digitalWrite(ledPin, LOW);
delayMicroseconds(1000);
millis() function
This function is used to return the number of milliseconds at the time, the Arduino board
begins running the current program. This number overflows i.e. goes back to zero after
approximately 50 days.
63
Arduino
micros() function
The micros() function returns the number of microseconds from the time, the Arduino
board begins running the current program. This number overflows i.e. goes back to zero
after approximately 70 minutes. On 16 MHz Arduino boards (e.g. Duemilanove and Nano),
this function has a resolution of four microseconds (i.e. the value returned is always a
multiple of four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has a resolution
of eight microseconds.
64
Arduino
Serial.println(time);
// wait a second so as not to send massive amounts of data
delay(1000);
}
65
Arduino Arrays
Arduino
An array is a consecutive group of memory locations that are of the same type. To refer
to a particular location or element in the array, we specify the name of the array and the
position number of the particular element in the array.
The illustration given below shows an integer array called C that contains 11 elements.
You refer to any one of these elements by giving the array name followed by the particular
elements position number in square brackets ([]). The position number is more formally
called a subscript or index (this number specifies the number of elements from the
beginning of the array). The first element has subscript 0 (zero) and is sometimes called
the zeros element.
Thus, the elements of array C are C[0] (pronounced C sub zero), C[1], C[2] and so on.
The highest subscript in array C is 10, which is 1 less than the number of elements in the
array (11). Array names follow the same conventions as other variable names.
A subscript must be an integer or integer expression (using any integral type). If a program
uses an expression as a subscript, then the program evaluates the expression to determine
the subscript. For example, if we assume that variable a is equal to 5 and that variable b
is equal to 6, then the statement adds 2 to array element C[11].
A subscripted array name is an lvalue, it can be used on the left side of an assignment,
just as non-array variable names can.
66
Arduino
Let us examine array C in the given figure, more closely. The name of the entire array is
C. Its 11 elements are referred to as C[0] to C[10]. The value of C[0] is -45, the value of
C[1] is 6, the value of C[2] is 0, the value of C[7] is 62, and the value of C[10] is 78.
To print the sum of the values contained in the first three elements of array C, we would
write:
Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] );
To divide the value of C[6] by 2 and assign the result to the variable x, we would write:
x = C[ 6 ] / 2;
Declaring Arrays
Arrays occupy space in memory. To specify the type of the elements and the number of
elements required by an array, use a declaration of the form:
type arrayName [ arraySize ] ;
The compiler reserves the appropriate amount of memory. (Recall that a declaration,
which reserves memory is more properly known as a definition). The arraySize must be
an integer constant greater than zero. For example, to tell the compiler to reserve 11
elements for integer array C, use the declaration:
int C[ 12 ]; // C is an array of 12 integers
Arrays can be declared to contain values of any non-reference data type. For example, an
array of type string can be used to store character strings.
67
Arduino
{
}
void loop ()
{
for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0
{
n[ i ] = 0; // set element at location i to 0
Serial.print (i) ;
Serial.print (\r) ;
}
for ( int j = 0; j < 10; ++j )
{
Serial.print (n[j]) ;
Serial.print (\r) ;
} }
Result: It will produce the following result:
Element
0
1
2
3
4
5
6
7
8
9
Value
0
0
0
0
0
0
0
0
0
0
68
Arduino
{
}
void loop ()
{
for ( int i = 0; i < 10; ++i ) // initialize elements of array n to 0
{
Serial.print (i) ;
Serial.print (\r) ;
}
for ( int j = 0; j < 10; ++j )
{
Serial.print (n[j]) ;
Serial.print (\r) ;
} }
Result: It will produce the following result:
Element
Value
0
1
2
3
4
5
6
7
8
9
32
27
64
18
95
14
90
70
60
37
69
Arduino
}
void loop ()
{
// sum contents of array a
for ( int i = 0; i < arraySize; ++i )
total += a[ i ];
Serial.print (Total of array elements
: ) ;
Serial.print(total) ;
}
Important Points
Here is a list of some important points that you need to know while passing arrays to
functions:
When passing an array to a function, normally the array size is passed as well, so
the function can process the specific number of elements in the array. Otherwise,
we would need to build this knowledge into the called function itself or, worse yet,
place the array size in a global variable.
C++ passes arrays to functions by reference i.e. the called functions can modify
the element values in the callers original arrays.
The value of the name of the array is the address in the computers memory of the
first element of the array. Since the starting address of the array is passed, the
called function knows precisely where the array is stored in the memory. Therefore,
when the called function modifies array elements in its function body, it is modifying
the actual elements of the array in their original memory locations.
Although the entire arrays are passed by reference, individual array elements are
passed by value exactly as simple variables are.
To pass an element of an array to a function, use the subscripted name of the array
element as an argument in the function call.
70
Arduino
For a function to receive an array through a function call, the functions parameter
list must specify that the function expects to receive an array.
For example, the function header for function modifyArray might be written as:
void modifyArray( int b[], int arraySize )
The statement indicates that modifyArray expects to receive the address of an array
of integers in parameter b and the number of array elements in parameter
arraySize. The arrays size is not required in the array brackets. If it is included,
the compiler ignores it; thus, arrays of any size can be passed to the function.
C++ passes arrays to the functions by reference. When the called function uses
the array name b, it refers to the actual array in the caller (i.e.,
arrayhourlyTemperatures discussed at the beginning of this section).
Example
void modifyArray( int [], int ); // appears strange; array and size
void modifyElement( int ); // receive array element value
void setup ()
{
Serial.begin (9600);
const int arraySize = 5; // size of array a
int a[ arraySize ] = { 0, 1, 2, 3, 4 }; // initialize array a
Serial.print ( "Effects of passing entire array by reference:" ) ;
// output original array elements
for ( int i = 0; i < arraySize ; ++i )
Serial.print ( a[ i ] ) ;
71
Arduino
Serial.print ("\r" ) ;
Serial.print ("The values of the modified array are:\n" );
// output modified array elements
for ( int j = 0; j < arraySize; ++j )
Serial.print ( a[j ] ) ;
Serial.print ("\r" ) ;
Serial.print ("\r\rEffects of passing array element by value:" );
Serial.print ( "\ra[3] before modifyElement: "
);
Serial.print ( a[ 3 ] );
Serial.print ( "\ra[3] after modifyElement: "
);
Serial.print ( a[ 3 ] );
}
void loop ()
{
Result
72
Arduino
Multidimensional Arrays
Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of
information arranged in rows and columns.
Following are the key features of multidimensional arrays:
By convention, the first identifies the elements row and the second identifies the
elements column.
Arrays that require two subscripts to identify a particular element are called twodimensional arrays or 2-D arrays.
Arrays with two or more dimensions are known as multidimensional arrays and can
have more than two dimensions.
The following figure illustrates a two-dimensional array, a. The array contains three rows
and four columns, so it is a 3-by-4 array. In general, an array with m rows and n columns
is called an m-by-n array.
73
Arduino
Every element in array a is identified by an element name of the form a[i][j]. Here, a is
the name of the array, and i and j are the subscripts that uniquely identify each element
in a. Notice that the names of the elements in row 0 all have a first subscript of 0; the
names of the elements in column 3 all have a second subscript of 3.
A multidimensional array can be initialized in its declaration much like a one-dimensional
array. For example, a two-dimensional array b with values 1 and 2 in its row 0 elements
and values 3 and 4 in its row 1 elements could be declared and initialized as follows:
int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } };
The values are grouped by row in braces. Therefore, 1 and 2 initialize b[0][0] and b[0][1],
respectively, and 3 and 4 initialize b[1][0] and b[1][1], respectively. If there are not
enough initializers for a given row, the remaining elements of that row are initialized to 0.
Thus, the following declaration initializes b[0][0] to 1, b[0][1] to 0, b[1][0] to 3 and
b[1][1] to 4.
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Example
Here is an example that demonstrates initializing two-dimensional arrays in declarations.
Lines ac declare three arrays, each with two rows and three columns.
The declaration of array1 (line a) provides six initializers in the two sub lists. The
first sub list initializes row 0 of the array to the values 1, 2 and 3; the second sub
list initializes row 1 of the array to the values 4, 5 and 6.
If the braces around each sub-list are removed from the array1 initializer list, the
compiler initializes the elements of row 0 followed by the elements of row 1,
yielding the same result.
The initializers are assigned to row 0, then row 1. Any elements that do not have
an explicit initializer are initialized to zero, so array2[1][2] is initialized to zero.
The declaration of array3 (line c) provides three initializers in two sub lists.
The sub list for row 0 explicitly initializes the first two elements of row 0 to 1 and
2; the third element is implicitly initialized to zero.
The sub list for row 1 explicitly initializes the first element to 4 and implicitly
initializes the last two elements to zero.
The program calls function printArray to output each arrays elements. Notice that
the function prototype (line k) specify the parameter const int a[][columns].
74
Arduino
The size of a two-dimensional arrays first dimension (i.e., the number of rows) is
not required either, but all the subsequent dimension sizes are required. The
compiler uses these sizes to determine the locations in memory of elements in
multidimensional arrays.
All array elements are stored consecutively in memory, regardless of the number
of dimensions. In a two-dimensional array, row 0 is stored in memory followed by
row 1.
Example
void printArray ( const int [][ 3 ] ); // prototype
const int rows = 2;
const int columns = 3;
int array1[ rows ][ columns ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ rows ][ columns ] = { 1, 2, 3, 4, 5 };
int array3[ rows ][ columns ] = { { 1, 2 }, { 4 } };
void setup ()
{
}
void loop ()
{
Serial.print ("Values in array1 by row are: ") ;
Serial.print (\r ) ;
printArray(array1) ;
Serial.print ("Values in array2 by row are: ") ;
Serial.print (\r ) ;
printArray(array2) ;
Serial.print ("Values in array3 by row are: ") ;
Serial.print (\r ) ;
printArray(array3) ;
}
// output array with two rows and three columns
void printArray( const int a[][ columns ] )
{
// loop through array's rows
for ( int i = 0; i < rows; ++i )
{
// loop through columns of current row
for ( int j = 0; j < columns; ++j )
75
Arduino
Serial.print (a[ i ][ j ] );
Serial.print (\r ) ; // start new line of output
} // end outer for
} // end function printArray
Result
Values in array1 by row are:
1 2 3
4 5 6
Values in array2 by row are:
1 2 3
4 5 0
Values in array3 by row are:
1 2 0
4 0 0
Note: Each row is a one-dimensional array. To locate an element in a particular row, the
function must know exactly how many elements are in each row so it can skip the proper
number of memory locations when accessing the array. Thus, when accessing a[1][2], the
function knows to skip row 0s three elements in memory to get to row 1. Then, the
function accesses element 2 of that row. Many common array manipulations use FOR
statements.
For example, the following FOR statement sets all the elements in row 2 of array a.
for ( int column = 0; column < 4; ++column )
a[ 2 ][ column ] = 0;
The FOR statement varies only the second subscript (i.e., the column subscript). The
preceding FOR statement is equivalent to the following assignment statements:
a[ 2 ][ 0 ] = 0;
a[ 2 ][ 1 ] = 0;
a[ 2 ][ 2 ] = 0;
a[ 2 ][ 3 ] = 0;
The following Nested FOR statement determines the total of all the elements in array a:
total = 0;
for ( int row = 0; row < 3; ++row )
for ( int column = 0; column < 4; ++column )
total += a[ row ][ column ];
76
Arduino
The FOR statement totals the elements of the array one row at a time. The outer FOR
statement begins by setting the row (i.e., the row subscript) to 0. Therefore, the elements
of row 0 may be totaled by the inner FOR statement.
The outer FOR statement then increments row to 1, so that the elements of row 1 can be
totaled. Then, the outer FOR statement increments row to 2, so that, the elements of row
2 can be totaled. When the nested FOR statement terminates, the total contains the sum
of all the array elements.
77
Arduino
78
Arduino
The pins on the Arduino board can be configured as either inputs or outputs. We will
explain the functioning of the pins in those modes. It is important to note that a majority
of Arduino analog pins, may be configured, and used, in exactly the same manner as
digital pins.
Pull-up Resistors
Pull-up resistors are often useful to steer an input pin to a known state if no input is
present. This can be done by adding a pull-up resistor (to +5V), or a pull-down resistor
(resistor to ground) on the input. A 10K resistor is a good value for a pull-up or pull-down
resistor.
79
Arduino
Same registers (internal chip memory locations) that control whether a pin is HIGH or
LOW control the pull-up resistors. Consequently, a pin that is configured to have pull-up
resistors turned on when the pin is in INPUTmode, will have the pin configured as HIGH if
the pin is then switched to an OUTPUT mode with pinMode(). This works in the other
direction as well, and an output pin that is left in a HIGH state will have the pull-up resistor
set if switched to an input with pinMode().
Example
pinMode(3,INPUT) ;
pinMode(5,INPUT_PULLUP) ;
pinMode() Function
The pinMode() function is used to configure a specific pin to behave either as an input or
an output. It is possible to enable the internal pull-up resistors with the mode
INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pull-ups.
pin: the number of the pin whose mode you wish to set
80
Arduino
Example
int button = 5 ;
int LED = 6;
void setup ()
{
pinMode(button , INPUT_PULLUP);
resistor
pinMode(button , OUTPUT);
void setup ()
{
If (digitalRead(button )==LOW)
// if button pressed
{
digitalWrite(LED,HIGH);
delay(500);
// turn on led
}
}
digitalWrite() Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the
pin has been configured as an OUTPUT with pinMode(), its voltage will be set to the
corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the
pin is configured as an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the
internal pullup on the input pin. It is recommended to set the pinMode()
to INPUT_PULLUP to enable the internal pull-up resistor.
If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling
digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(),
digitalWrite() will have enabled the internal pull-up resistor, which acts like a large currentlimiting resistor.
81
Arduino
pin: the number of the pin whose mode you wish to set
Example
int LED = 6;
void setup ()
{
pinMode(LED, OUTPUT);
}
void setup ()
{
digitalWrite(LED,HIGH);
delay(500);
// turn on led
analogRead( ) function
Arduino is able to detect whether there is a voltage applied to one of its pins and report it
through the digitalRead() function. There is a difference between an on/off sensor (which
detects the presence of an object) and an analog sensor, whose value continuously
changes. In order to read this type of sensor, we need a different type of pin.
In the lower-right part of the Arduino board, you will see six pins marked Analog In.
These special pins not only tell whether there is a voltage applied to them, but also its
value. By using the analogRead() function, we can read the voltage applied to one of the
pins.
This function returns a number between 0 and 1023, which represents voltages between
0 and 5 volts. For example, if there is a voltage of 2.5 V applied to pin number 0,
analogRead(0) returns 512.
82
Arduino
pin: the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on
the Mini and Nano, 0 to 15 on the Mega)
Example
int analogPin = 3;//potentiometer wiper (middle terminal) connected to analog
pin 3
int val = 0;
// variable to store the value read
void setup()
{
Serial.begin(9600); //
setup serial
}
void loop()
{
val = analogRead(analogPin);
Serial.println(val);
83
Arduino
In this chapter, we will learn some advanced Input and Output Functions.
analogReference() Function
Configures the reference voltage used for analog input (i.e. the value used as the top of
the input range). The options are:
DEFAULT: The default analog reference of 5 volts (on 5V Arduino boards) or 3.3
volts (on 3.3V Arduino boards)
EXTERNAL: The voltage applied to the AREF pin (0 to 5V only) is used as the
reference
the follow
(DEFAULT,
INTERNAL,
INTERNAL1V1,
Do not use anything less than 0V or more than 5V for external reference voltage on the
AREF pin. If you are using an external reference on the AREF pin, you must set the analog
reference to EXTERNAL before calling the analogRead() function. Otherwise, you will
short the active reference voltage (internally generated) and the AREF pin, possibly
damaging the microcontroller on your Arduino board.
84
Arduino
Alternatively, you can connect the external reference voltage to the AREF pin through a
5K resistor, allowing you to switch between external and internal reference voltages.
Note that the resistor will alter the voltage that is used as the reference because there is
an internal 32K resistor on the AREF pin. The two act as a voltage divider. For example,
2.5V applied through the resistor will yield 2.5 * 32 / (32 + 5) = ~2.2V at the AREF pin.
Example
int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog
pin
3
int val = 0;
// variable to store the read value
void setup()
{
Serial.begin(9600);
//
setup serial
85
Arduino
All data is entered into computers as characters, which includes letters, digits and various
special symbols. In this section, we discuss the capabilities of C++ for examining and
manipulating individual characters.
The character-handling library includes several functions that perform useful tests and
manipulations of character data. Each function receives a character, represented as an int,
or EOF as an argument. Characters are often manipulated as integers.
Remember that EOF normally has the value 1 and that some hardware architectures do
not allow negative values to be stored in char variables. Therefore, the character-handling
functions manipulate characters as integers.
The following table summarizes the functions of the character-handling library. When using
functions from the character-handling library, include the <cctype> header.
Prototype
Description
(' '), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t'),
or vertical tab ('\v')and 0 otherwise.
86
Arduino
Examples
The following example demonstrates the use of the functions isdigit, isalpha, isalnum
and isxdigit. Function isdigit determines whether its argument is a digit (09). The
function isalpha determines whether its argument is an uppercase letter (A-Z) or a
lowercase letter (az). The function isalnum determines whether its argument is an
uppercase, lowercase letter or a digit. Function isxdigit determines whether its argument
is a hexadecimal digit (AF, af, 09).
Example 1
void setup ()
{
Serial.begin (9600);
Serial.print ("According to isdigit:\r");
Serial.print (isdigit( '8' ) ? "8 is a": "8 is not a");
Serial.print (" digit\r" );
Serial.print (isdigit( '8' ) ?"# is a": "# is not a") ;
Serial.print (" digit\r");
Serial.print ("\rAccording to isalpha:\r" );
Serial.print (isalpha('A' ) ?"A is a": "A is not a");
Serial.print (" letter\r");
Serial.print (isalpha('A' ) ?"b is a": "b is not a");
Serial.print (" letter\r");
Serial.print (isalpha('A') ?"& is a": "& is not a");
Serial.print (" letter\r");
Serial.print (isalpha( 'A' ) ?"4 is a":"4 is not a");
Serial.print (" letter\r");
Serial.print ("\rAccording to isalnum:\r");
Serial.print (isalnum( 'A' ) ?"A is a" : "A is not a" );
87
Arduino
digit\r" );
digit\r" );
}
void loop ()
{
}
Result
According to isdigit:
8 is a digit
# is not a digit
According to isalpha:
A is a letter
b is a letter
& is not a letter
4 is not a letter
According to isalnum:
A is a digit or a letter
88
Arduino
8 is a digit or a letter
# is not a digit or a letter
According to isxdigit:
F is a hexadecimal digit
J is not a hexadecimal digit
7 is a hexadecimal digit
Example 2
The following example demonstrates the use of the functions islower and isupper. The
function islower determines whether its argument is a lowercase letter (az). Function
isupper determines whether its argument is an uppercase letter (AZ).
int thisChar = 0xA0;
void setup ()
{
Serial.begin (9600);
Serial.print ("According to islower:\r") ;
Serial.print (islower( 'p' ) ? "p is a" : "p is not a" );
Serial.print (
"
lowercase letter\r" );
Serial.print (
"
lowercase letter\r" );
Serial.print (
"
uppercase letter\r" );
Serial.print (
89
Arduino
Serial.print ( "
uppercase letter\r" );
"
uppercase letter\r" );
Serial.print (
Result
According to islower:
p is a lowercase letter
P is not a lowercase letter
5 is not a lowercase letter
! is not a lowercase letter
According to isupper:
D is an uppercase letter
d is not an uppercase letter
8 is not an uppercase letter
$ is not an uppercase letter
Example 3
The following example demonstrates the use of functions isspace, iscntrl, ispunct,
isprint and isgraph.
The function iscntrl determines whether its argument is a control character such
as horizontal tab ('\t'), vertical tab ('\v'), form feed ('\f'), alert ('\a'), backspace
('\b'), carriage return ('\r') or newline ('\n').
The function ispunct determines whether its argument is a printing character other
than a space, digit or letter, such as $, #, (, ), [, ], {, }, ;, : or %.
The function isprint determines whether its argument is a character that can be
displayed on the screen (including the space character).
The function isgraph tests for the same characters as isprint, but the space
character is not included.
90
Arduino
void setup ()
{
Serial.begin (9600);
Serial.print ( " According to isspace:\rNewline ") ;
Serial.print (isspace( '\n' )? " is a" : " is not a" );
Serial.print ( " whitespace character\rHorizontal tab") ;
Serial.print (isspace( '\t' )? " is a" : " is not a" );
Serial.print ( " whitespace character\n") ;
Serial.print (isspace('%')? " % is a" : " % is not a" );
is not a" );
91
Arduino
Result
According to isspace:
Newline is a whitespace character
Horizontal tab is a whitespace character
% is not a whitespace character
According to iscntrl:
Newline is a control character
$ is not a control character
According to ispunct:
; is a punctuation character
Y is not a punctuation character
# is a punctuation character
According to isprint:
$ is a printing character
Alert is not a printing character
Space is a printing character
According to isgraph:
Q is a printing character other than a space
Space is not a printing character other than a space
92
Arduino
The Arduino Math library (math.h) includes a number of useful mathematical functions for
manipulating floating-point numbers.
Library Macros
Following are the macros defined in the header math.h:
Macros
M_E
M_LOG2E
M_1_PI
M_2_PI
M_2_SQRTPI
M_LN10
M_LN2
M_LOG10E
M_PI
M_PI_2
M_PI_4
M_SQRT1_2
Value
2.7182818284590452354
1.4426950408889634074
/* log_2 e */
0.31830988618379067154
/* 1/pi */
0.63661977236758134308
/* 2/pi */
1.12837916709551257390
/* 2/sqrt(pi) */
2.30258509299404568402
/* log_e 10 */
0.69314718055994530942
/* log_e 2 */
0.43429448190325182765
/* log_10 e */
3.14159265358979323846
/* pi */
3.3V1.57079632679489661923
/* pi/2 */
0.78539816339744830962
/* pi/4 */
0.70710678118654752440
Description
The constant e.
The logarithm of the e to base
2
The constant 1/pi
93
Arduino
/* 1/sqrt(2) */
M_SQRT2
1.41421356237309504880
/* sqrt(2) */
acosf
asinf
atan2f
cbrtf
ceilf
copysignf
for
copysign()
coshf
expf
fabsf
fdimf
floorf
fmaxf
fminf
fmodf
frexpf
hypotf
INFINITY
INFINITY constant
isfinitef
isinff
isnanf
ldexpf
94
Arduino
log10f
logf
lrintf
lroundf
Library Functions
The following functions are defined in the header math.h:
Library Function
Description
95
Arduino
double fma
double __z)
__y)
96
Arduino
97
Arduino
round() function, but it differs in type of
return value and in that an overflow is
possible.
Returns
The rounded long integer value. If __x is
not a finite number or an overflow was, this
realization returns the LONG_MIN value
(0x80000000).
The modf() function breaks the argument
__x into integral and fractional parts, each
of which has the same sign as the
argument. It stores the integral part as a
double in the object pointed to by __iptr.
double modf (double
__iptr )
__x,
double
float modff
Returns
The rounded value. If __x is an integral or
infinite, __x itself is returned. If __x is
NaN, then NaN is returned.
98
Arduino
The sqrt() function returns
negative square root of __x.
the
non-
Example
The following example shows how to use the most common math.h library functions:
double double__x = 45.45 ;
double double__y = 30.20 ;
void setup()
{
Serial.begin(9600);
Serial.print("cos num = ");
Serial.println (cos (double__x) );
// returns cosine of x
sqrt (double__x)
tan (double__x) );
// returns tangent of x
99
Arduino
Result
cos num = 0.10
absolute value of num = 45.45
floating point modulo =15.25
sine of num = 0.99
square root of num : 6.74
tangent of num : 9.67
exponential value of num : ovf
cos num : 1.55
tangent of num : 0.59
arc tangent of num : 3.82
cos num : 1.66
logarithm of num to base 10 : inf
power of num : 2065.70
100
Arduino
You need to use Trigonometry practically like calculating the distance for moving object or
angular speed. Arduino provides traditional trigonometric functions (sin, cos, tan, asin,
acos, atan) that can be summarized by writing their prototypes. Math.h contains the
trigonometry function's prototype.
//returns
Example
double sine
= sin(2);
// approximately
0.90929737091
double cosine
= cos(2);
// approximately -0.41614685058
// approximately -2.18503975868
101
Arduino
Arduino Advanced
102
Arduino
The Arduino Due is a microcontroller board based on the Atmel SAM3X8E ARM Cortex-M3
CPU. It is the first Arduino board based on a 32-bit ARM core microcontroller.
Important features
It has 54 digital input/output pins (of which 12 can be used as PWM outputs)
12 analog inputs
2 DAC (digital to analog), 2 TWI, a power jack, an SPI header, a JTAG header
103
Arduino
CPU
speed
Analog
in/out
3.3 Volt
84 Mhz
12/2
Digital
EEPROM
SRAM
Flash
IO/
PWM
[KB]
[KB]
[KB]
54/12
96
512
USB
UART
2
micro
Communication
4 Hardware UARTs
2 I2C
1 SPI
1 Programming Port
Unlike most Arduino boards, the Arduino Due board runs at 3.3V. The maximum voltage
that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin
could damage the board.
The board contains everything needed to support the microcontroller. You can simply
connect it to a computer with a micro-USB cable or power it with an AC-to-DC adapter or
battery to get started. The Due is compatible with all Arduino shields that work at 3.3V.
Arduino Zero
The Zero is a simple and powerful 32-bit extension of the platform established by the UNO.
The Zero board expands the family by providing increased performance, enabling a variety
of project opportunities for devices, and acts as a great educational tool for learning about
32-bit application development.
Important features are
The Zero applications span from smart IoT devices, wearable technology, high-tech
automation, to crazy robotics.
The board is powered by Atmels SAMD21 MCU, which features a 32-bit ARM
Cortex M0+ core.
One of its most important features is Atmels Embedded Debugger (EDBG), which
provides a full debug interface without the need for additional hardware,
significantly increasing the ease-of-use for software debugging.
EDBG also supports a virtual COM port that can be used for device and bootloader
programming.
104
Arduino
CPU
speed
Analog
in/out
3.3 Volt
48 Mhz
6/1
Digital
EEPROM
SRAM
Flash
IO/
PWM
[KB]
[KB]
[KB]
14/10
32
256
USB
UART
2
micro
Unlike most Arduino and Genuino boards, the Zero runs at 3.3V. The maximum voltage
that the I/O pins can tolerate is 3.3V. Applying voltages higher than 3.3V to any I/O pin
could damage the board.
The board contains everything needed to support the microcontroller. You can simply
connect it to a computer with a micro-USB cable or power it with an AC-to-DC adapter or
a battery to get started. The Zero is compatible with all the shields that work at 3.3V.
105
Arduino
Pulse Width Modulation or PWM is a common technique used to vary the width of the
pulses in a pulse-train. PWM has many applications such as controlling servos and speed
controllers, limiting the effective power of motors and LEDs.
Period
As shown in the figure, Ton denotes the on-time and Toff denotes the off-time of signal.
Period is the sum of both on and off times and is calculated as shown in the following
equation:
106
Arduino
Duty Cycle
Duty cycle is calculated as the on-time of the period of time. Using the period calculated
above, duty cycle is calculated as -
analogWrite() Function
The analogWrite() function writes an analog value (PWM wave) to a pin. It can be used
to light a LED at varying brightness or drive a motor at various speeds. After a call of
the analogWrite() function, the pin will generate a steady square wave of the specified
duty cycle until the next call to analogWrite() or a call to digitalRead() or digitalWrite() on
the same pin). The frequency of the PWM signal on most pins is approximately 490 Hz.
On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz.
Pins 3 and 11 on the Leonardo also run at 980 Hz.
On most Arduino boards (those with the ATmega168 or ATmega328), this function works
on pins 3, 5, 6, 9, 10, and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46.
Older Arduino boards with an ATmega8 only support analogWrite() on pins 9, 10, and
11.
) ;
value: the duty cycle: between 0 (always off) and 255 (always on).
107
Arduino
Example
int
ledPin = 9;
int
analogPin = 3;
int val = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
val = analogRead(analogPin);
108
Arduino
To generate random numbers, you can use Arduino random number functions. We have
two functions
randomSeed(seed)
random()
randomSeed (seed)
The function randomSeed(seed) resets Arduinos pseudorandom number generator.
Although the distribution of the numbers returned by random() is essentially random, the
sequence is predictable. You should reset the generator to some random value. If you
have an unconnected analog pin, it might pick up random noise from the surrounding
environment. These may be radio waves, cosmic rays, electromagnetic interference from
cell phones, fluorescent lights and so on.
Example
randomSeed(analogRead(5));
random( )
The random function generates pseudo-random numbers. Following is the syntax.
Example
long randNumber;
void setup()
{
Serial.begin(9600);
// if analog input pin 0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
109
Arduino
randomSeed(analogRead(0));
}
void loop() {
// print a random number from 0 to 299
Serial.print("random1=");
randNumber = random(300);
Serial.println(randNumber);
Serial.print("random2=");
randNumber = random(10, 20);// print a random number from 10 to 19
Serial.println (randNumber);
delay(50);
}
Let us now refresh our knowledge on some of the basic concepts such as bits and bytes.
Bits
A bit is just a binary digit.
Similar to the decimal number system, in which digits of a number do not have the
same value, the significance of a bit depends on its position in the binary number.
For example, digits in the decimal number 666 are the same, but have different
values.
Bytes
A byte consists of eight bits.
110
Arduino
The leftmost bit has the greatest value called the Most Significant Bit (MSB).
The rightmost bit has the least value and is therefore, called the Least Significant
Bit (LSB).
Since eight zeros and ones of one byte can be combined in 256 different ways, the
largest decimal number that can be represented by one byte is 255 (one
combination represents a zero).
111
Arduino Interrupts
Arduino
Interrupts stop the current work of Arduino such that some other work can be done.
Suppose you are sitting at home, chatting with someone. Suddenly the telephone rings.
You stop chatting, and pick up the telephone to speak to the caller. When you have finished
your telephonic conversation, you go back to chatting with the person before the telephone
rang.
Similarly, you can think of the main routine as chatting to someone, the telephone ringing
causes you to stop chatting. The interrupt service routine is the process of talking on the
telephone. When the telephone conversation ends, you then go back to your main routine
of chatting. This example explains exactly how an interrupt causes a processor to act.
The main program is running and performing some function in a circuit. However, when
an interrupt occurs the main program halts while another routine is carried out. When this
routine finishes, the processor goes back to the main routine again.
Important features
Here are some important features about interrupts:
Interrupts can come from various sources. In this case, we are using a hardware
interrupt that is triggered by a state change on one of the digital pins.
Most Arduino designs have two hardware interrupts (referred to as "interrupt0" and
"interrupt1") hard-wired to digital I/O pins 2 and 3, respectively.
The Arduino Mega has six hardware interrupts including the additional interrupts
("interrupt2" through "interrupt5") on pins 21, 20, 19, and 18.
112
Arduino
You can define a routine using a special function called as Interrupt Service
Routine (usually known as ISR).
You can define the routine and specify conditions at the rising edge, falling edge or
both. At these specific conditions, the interrupt would be serviced.
Types of Interrupts
There are two types of interrupts
//argument ISR: the ISR to call when the interrupt occurs; this function must
take no parameters and return nothing. This function is sometimes referred to as
an interrupt service routine.
//argument mode: defines when the interrupt should be triggered.
The following three constants are predefined as valid values
113
Arduino
Example
int pin = 2;
as volatile.
void setup() {
pinMode(13, OUTPUT);
114
Arduino Communication
Arduino
Hundreds of communication protocols have been defined to achieve this data exchange.
Each protocol can be categorized into one of the two categories: parallel or serial.
Parallel Communication
Parallel connection between the Arduino and peripherals via input/output ports is the ideal
solution for shorter distances up to several meters. However, in other cases when it is
necessary to establish communication between two devices for longer distances it is not
possible to use parallel connection. Parallel interfaces transfer multiple bits at the same
time. They usually require buses of data - transmitting across eight, sixteen, or more
wires. Data is transferred in huge, crashing waves of 1s and 0s.
115
Arduino
One of the most important things concerning serial communication is the Protocol, which
should be strictly observed. It is a set of rules, which must be applied such that the devices
can correctly interpret data they mutually exchange. Fortunately, Arduino automatically
takes care of this, so that the work of the programmer/user is reduced to simple write
(data to be sent) and read (received data).
Synchronous - Devices that are synchronized use the same clock and their timing
is in synchronization with each other.
Asynchronous - Devices that are asynchronous have their own clocks and are
triggered by the output of the previous state.
It is easy to find out if a device is synchronous or not. If the same clock is given to all the
connected devices, then they are synchronous. If there is no clock line, it is asynchronous.
For example,
asynchronous.
UART
(Universal
Asynchronous
Receiver
Transmitter)
module
is
The asynchronous serial protocol has a number of built-in rules. These rules are nothing
but mechanisms that help ensure robust and error-free data transfers. These mechanisms,
which we get for eschewing the external clock signal, are:
Synchronization bits
Data bits
Parity bits
Baud rate
Synchronization Bits
The synchronization bits are two or three special bits transferred with each packet of data.
They are the start bit and the stop bit(s). True to their name, these bits mark the
beginning and the end of a packet respectively.
There is always only one start bit, but the number of stop bits is configurable to either one
or two (though it is normally left at one).
The start bit is always indicated by an idle data line going from 1 to 0, while the stop bit(s)
will transition back to the idle state by holding the line at 1.
116
Arduino
Data Bits
The amount of data in each packet can be set to any size from 5 to 9 bits. Certainly, the
standard data size is your basic 8-bit byte, but other sizes have their uses. A 7-bit data
packet can be more efficient than 8, especially if you are just transferring 7-bit ASCII
characters.
Parity Bits
The user can select whether there should be a parity bit or not, and if yes, whether the
parity should be odd or even. The parity bit is 0 if the number of 1s among the data bits
is even. Odd parity is just the opposite.
Baud Rate
The term baud rate is used to denote the number of bits transferred per second [bps].
Note that it refers to bits, not bytes. It is usually required by the protocol that each byte
is transferred along with several control bits. It means that one byte in serial data stream
may consist of 11 bits. For example, if the baud rate is 300 bps then maximum 37 and
minimum 27 bytes may be transferred per second.
Arduino UART
The following code will make Arduino send hello world when it starts up.
void setup()
{
Serial.begin(9600);
Serial.println("hello world");
}
void loop()
{
}
After the Arduino sketch has been uploaded to Arduino, open the Serial monitor
top right section of Arduino IDE.
at the
Type anything into the top box of the Serial Monitor and press send or enter on your
keyboard. This will send a series of bytes to the Arduino.
The following code returns whatever it receives as an input.
117
Arduino
The following code will make Arduino deliver output depending on the input provided.
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available()) //if number of bytes (characters) available for reading
from
{ serial port
Serial.print("I received:");
//print I received
Serial.write(Serial.read());
}
}
Notice that Serial.print and Serial.println will send back the actual ASCII code, whereas
Serial.write will send back the actual text. See ASCII codes for more information.
118
Arduino
Inter-integrated circuit (I2C) is a system for serial data exchange between the
microcontrollers and specialized integrated circuits of a new generation. It is used when
the distance between them is short (receiver and transmitter are usually on the same
printed board). Connection is established via two conductors. One is used for data transfer
and the other is used for synchronization (clock signal).
As seen in the following figure, one device is always a master. It performs addressing of
one slave chip before the communication starts. In this way, one microcontroller can
communicate with 112 different devices. Baud rate is usually 100 Kb/sec (standard mode)
or 10 Kb/sec (slow baud rate mode). Systems with the baud rate of 3.4 Mb/sec have
recently appeared. The distance between devices, which communicate over an I2C bus is
limited to several meters.
A4 (SDA), A5 (SCL)
Mega, Due
20 (SDA), 21 (SCL)
Leonardo, Yun
2 (SDA), 3 (SCL)
Arduino I2C
We have two modes - master code and slave code - to connect two Arduino boards using
I2C. They are:
119
Arduino
Master Transmitter
The following functions are used to initialize the Wire library and join the I2C bus as a
master or slave. This is normally called only once.
Example
#include <Wire.h>
void setup()
{
Wire.begin();
}
short age = 0;
void loop()
{
Wire.beginTransmission(2);
// transmit to device #2
Wire.write("age is=");
Wire.write(age);
Wire.endTransmission();
// stop transmitting
delay(1000);
}
Slave Receiver
The following functions are used
120
Arduino
Example
#include <Wire.h>
void setup()
{
Wire.begin(2);
{
char c = Wire.read();
Serial.print(c);
}
}
Master Receiver
The Master, is programmed to request, and then read bytes of data that are sent from the
uniquely addressed Slave Arduino.
The following function is used:
Wire.requestFrom(address,number of bytes) Used by the master to request bytes
from a slave device. The bytes may then be retrieved with the functions
wire.available() and wire.read() functions.
121
Arduino
Example
#include <Wire.h> //include wire library void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
Wire.requestFrom(2, 1);
while (Wire.available())
{
char c = Wire.read(); // receive a byte as character
Serial.print(c);
}
delay(500);
}
Slave Transmitter
The following function is used.
Wire.onRequest(handler) A function is called when a master requests data from this
slave device.
Example
#include <Wire.h>
void setup()
{
Wire.begin(2);
Wire.onRequest(requestEvent);
// register event
}
Byte x=0;
void loop() {
delay(100);
}
// function that executes whenever data is requested by master
// this function is registered as an event, see setup()
void requestEvent()
{
Wire.write(x);
x++;
}
122
Arduino
A Serial Peripheral Interface (SPI) bus is a system for serial communication, which uses
up to four conductors, commonly three. One conductor is used for data receiving, one for
data sending, one for synchronization and one alternatively for selecting a device to
communicate with. It is a full duplex connection, which means that the data is sent and
received simultaneously. The maximum baud rate is higher than that in the I2C
communication system.
MOSI: This is the master output / slave input driven by the master.
MISO: This is the master input / slave output driven by the master.
The following functions are used. You have to include the SPI.h.
SPI.begin() - Initializes the SPI bus by setting SCK, MOSI, and SS to outputs,
pulling SCK and MOSI low, and SS high.
SPI.beginTransaction(SPISettings(speedMaximum,
dataOrder,
dataMode)) speedMaximum is the clock, dataOrder(MSBFIRST or LSBFIRST),
dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or SPI_MODE3).
Mode 0 (the default) - Clock is normally low (CPOL = 0), and the data is sampled
on the transition from low to high (leading edge) (CPHA = 0).
Mode 1 - Clock is normally low (CPOL = 0), and the data is sampled on the
transition from high to low (trailing edge) (CPHA = 1).
123
Arduino
Mode 2 - Clock is normally high (CPOL = 1), and the data is sampled on the
transition from high to low (leading edge) (CPHA = 0).
Mode 3 - Clock is normally high (CPOL = 1), and the data is sampled on the
transition from low to high (trailing edge) (CPHA = 1).
Now, we will connect two Arduino UNO boards together; one as a master and the other as
a slave.
(SS)
: pin 10
(MOSI) : pin 11
(MISO) : pin 12
(SCK)
: pin 13
SPI as MASTER
Example
#include <SPI.h>
void setup (void)
{
Serial.begin(115200);
124
Arduino
digitalWrite(SS, HIGH);
SPI.begin ();
SPI.setClockDivider(SPI_CLOCK_DIV8);//divide the clock by 8
}
void loop (void)
{
char c;
digitalWrite(SS, LOW);
delay(2000);
}
SPI as SLAVE
Example
#include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;
void setup (void)
{
Serial.begin (115200);
pinMode(MISO, OUTPUT);
SPCR |= _BV(SPE);
indx = 0;
// buffer empty
process = false;
SPI.attachInterrupt();
// turn on interrupt
}
ISR (SPI_STC_vect)
{
byte c = SPDR;
125
Arduino
if (c == '\r')
process = true;
}
}
void loop (void)
{
if (process)
{
process = false;
Serial.println (buff);
indx= 0;
}
}
126
Arduino
Arduino Projects
127
Arduino
LEDs are small, powerful lights that are used in many different applications. To start, we
will work on blinking an LED, the Hello World of microcontrollers. It is as simple as turning
a light on and off. Establishing this important baseline will give you a solid foundation as
we work towards experiments that are more complex.
Components Required
You will need the following components
1x Breadboard
1x Arduino Uno R3
1x LED
1x 330 Resistor
2x Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
128
Arduino
Note: To find out the polarity of an LED, look at it closely. The shorter of the two legs,
towards the flat edge of the bulb indicates the negative terminal.
Components like resistors need to have their terminals bent into 90 angles in order to fit
the breadboard sockets properly. You can also cut the terminals shorter.
129
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open the new sketch File by clicking New.
Arduino Code
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/
// the setup function runs once when you press reset or power the board
void setup()
{
// initialize digital pin 13 as an output.
pinMode(2, OUTPUT);
}
// the loop function runs over and over again forever
void loop()
{
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
130
Arduino
Code to Note
pinMode(2, OUTPUT) - Before you can use one of Arduinos pins, you need to tell Arduino
Uno R3 whether it is an INPUT or OUTPUT. We use a built-in function called pinMode() to
do this.
digitalWrite(2, HIGH) - When you are using a pin as an OUTPUT, you can command it
to be HIGH (output 5 volts), or LOW (output 0 volts).
Result
You should see your LED turn on and off. If the required output is not seen, make sure
you have assembled the circuit correctly, and verified and uploaded the code to your
board.
131
Arduino
This example demonstrates the use of the analogWrite() function in fading an LED off.
AnalogWrite uses pulse width modulation (PWM), turning a digital pin on and off very
quickly with different ratios between on and off, to create a fading effect.
Components Required
You will need the following components
1x Breadboard
1x Arduino Uno R3
1x LED
1x 330 Resistor
2x Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
132
Arduino
Note: To find out the polarity of an LED, look at it closely. The shorter of the two legs
towards the flat edge of the bulb indicates the negative terminal.
Components like resistors need to have their terminals bent into 90 angles in order to fit
the breadboard sockets properly. You can also cut the terminals shorter.
133
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking on New.
Arduino Code
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
sure to use another PWM capable pin. On most Arduino, the PWM pins are identified
with
a "~" sign, like ~3, ~5, ~6, ~9, ~10 and ~11.
*/
int led = 9;
int brightness = 0;
int fadeAmount = 5;
134
Arduino
Code to Note
After declaring pin 9 as your LED pin, there is nothing to do in the setup() function of your
code. The analogWrite() function that you will be using in the main loop of your code
requires two arguments: One, telling the function which pin to write to and the other
indicating what PWM value to write.
In order to fade the LED off and on, gradually increase the PWM values from 0 (all the way
off) to 255 (all the way on), and then back to 0, to complete the cycle. In the sketch given
above, the PWM value is set using a variable called brightness. Each time through the
loop, it increases by the value of the variable fadeAmount.
If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed
to its negative. In other words, if fadeAmount is 5, then it is set to -5. If it is -5, then it is
set to 5. The next time through the loop, this change causes brightness to change direction
as well.
135
Arduino
analogWrite() can change the PWM value very fast, so the delay at the end of the sketch
controls the speed of the fade. Try changing the value of the delay and see how it changes
the fading effect.
Result
You should see your LED brightness change gradually.
136
Arduino
This example will show you how to read an analog input on analog pin 0. The input is
converted from analogRead() into voltage, and printed out to the serial monitor of the
Arduino Software (IDE).
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
2x Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
Potentiometer
A potentiometer (or pot) is a simple electro-mechanical transducer. It converts rotary or
linear motion from the input operator into a change of resistance. This change is (or can
be) used to control anything from the volume of a hi-fi system to the direction of a huge
container ship.
137
Arduino
The pot as we know it was originally known as a rheostat (essentially a variable wirewound
resistor). The variety of available pots is now quite astonishing, and it can be very difficult
for the beginner (in particular) to work out which type is suitable for a given task. A few
different pot types, which can all be used for the same task makes the job harder.
The image on the left shows the standard schematic symbol of a pot. The image on the
right is the potentiometer.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
138
Arduino
Arduino Code
/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result
to the serial monitor.
Graphical representation is available using serial plotter (Tools > Serial
Plotter menu)
Attach the center pin of a potentiometer to pin A0, and the outside pins to
+5V and ground.
*/
Code to Note
In the program or sketch given below, the first thing that you do in the setup function is
begin serial communications, at 9600 bits per second, between your board and your
computer with the line:
Serial.begin(9600);
In the main loop of your code, you need to establish a variable to store the resistance
value (which will be between 0 and 1023, perfect for an int datatype) coming from your
potentiometer:
139
Arduino
Result
You will see a steady stream of numbers ranging from 0.0 - 5.0. As you turn the pot, the
values will change, corresponding to the voltage at pin A0.
140
Arduino
This example shows you how to read an analog input at analog pin 0, convert the values
from analogRead() into voltage, and print it out to the serial monitor of the Arduino
Software (IDE).
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
2x Jumper
8x LED or you can use (LED bar graph display as shown in the image below)
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
141
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
142
Arduino
These 10-segment bar graph LEDs have many uses. With a compact footprint, simple
hookup, they are easy for prototype or finished products. Essentially, they are 10 individual
blue LEDs housed together, each with an individual anode and cathode connection.
They are also available in yellow, red, and green colors.
Note: The pin out on these bar graphs may vary from what is listed on the datasheet.
Rotating the device 180 degrees will correct the change, making pin 11 the first pin in line.
Arduino Code
/*
LED bar graph
Turns on a series of LEDs based on the value of an analog sensor. This is a
simple way to make
a bar graph display. Though this graph uses 8LEDs, you can
use any number by changing the LED count and the pins in the array.
This method can be used to control any series of digital outputs that depends on
an analog input.
*/
// these constants won't change:
const int analogPin = A0;
const int ledCount = 8;
void setup()
{
// loop over the pin array and set them all to output:
143
Arduino
Code to Note
The sketch works like this: first, you read the input. You map the input value to the output
range, in this case ten LEDs. Then you set up a for-loop to iterate over the outputs. If
the output's number in the series is lower than the mapped input range, you turn it on. If
not, you turn it off.
Result
You will see the LED turn ON one by one when the value of analog reading increases and
turn OFF one by one while the reading is decreasing.
144
Arduino
This example uses the Keyboard library to log you out of your user session on your
computer when pin 2 on the ARDUINO UNO is pulled to ground. The sketch simulates the
keypress in sequence of two or three keys at the same time and after a short delay, it
releases them.
Warning: When you use the Keyboard.print() command, Arduino takes over your
computer's keyboard. To ensure you do not lose control of your computer while running a
sketch with this function, set up a reliable control system before you call Keyboard.print().
This sketch is designed to only send a Keyboard command after a pin has been pulled to
ground.
Components Required
You will need the following components:
1x Breadboard
1x pushbutton
1x Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image below.
145
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
For this example, you need to use Arduino IDE 1.6.7
Note: You must include the keyboard library in your Arduino library file. Copy and paste
the keypad library file inside the file with the name libraries (highlighted) as shown in the
following screenshot.
146
Arduino
Arduino Code
/*
Keyboard logout
This sketch demonstrates the Keyboard library.
When you connect pin 2 to ground, it performs a logout.
It uses keyboard combinations to do this, as follows:
On Windows, CTRL-ALT-DEL followed by ALT-l
On Ubuntu, CTRL-ALT-DEL, and ENTER
On OSX, CMD-SHIFT-q
To wake: Spacebar.
Circuit:
* Arduino Leonardo or Micro
* wire to connect D2 to ground.
*/
#define OSX 0
#define WINDOWS 1
#define UBUNTU 2
#include "Keyboard.h"
// change this to match your platform:
int platform = WINDOWS;
void setup()
{
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop()
{
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);
147
Arduino
switch (platform) {
case OSX:
Keyboard.press(KEY_LEFT_GUI);
// Shift-Q logs out:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('Q');
delay(100);
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-l:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
}
// do nothing:
148
Arduino
while (true);
}
Keyboard.releaseAll();
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-l:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
}
// do nothing:
while (true);
}
149
Arduino
Code to Note
Before you upload the program to your board, make sure you assign the correct OS you
are currently using to the platform variable.
While the sketch is running, pressing the button will connect pin 2 to the ground and the
board will send the logout sequence to the USB connected PC.
Result
When you connect pin 2 to the ground, it performs a logout operation.
It uses the following keyboard combinations to logout
On OSX, CMD-SHIFT-q
150
Arduino
In this example, when the button is pressed, a text string is sent to the computer as
keyboard input. The string reports the number of times the button is pressed. Once you
have the Leonardo programmed and wired up, open your favorite text editor to see the
results.
Warning: When you use the Keyboard.print() command, the Arduino takes over your
computer's keyboard. To ensure you do not lose control of your computer while running a
sketch with this function, set up a reliable control system before you call
Keyboard.print(). This sketch includes a pushbutton to toggle the keyboard, so that it
only runs after the button is pressed.
Components Required
You will need the following components:
1x Breadboard
1x momentary pushbutton
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
151
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
Arduino Code
/*
Keyboard Message test For the Arduino Leonardo and Micro, Sends a text string
when a button
is pressed.
The circuit:
* pushbutton attached from pin 4 to +5V
* 10-kilohm resistor attached from pin 4 to ground
*/
#include "Keyboard.h"
const int buttonPin = 4;
int counter = 0;
void setup() {
pinMode(buttonPin, INPUT);
152
Arduino
{
// increment the button counter
counter++;
// type out a message
Keyboard.print("You pressed the button ");
Keyboard.print(counter);
Keyboard.println(" times.");
}
// save the current button state for comparison next time:
previousButtonState = buttonState;
}
Code to Note
Attach one terminal of the pushbutton to pin 4 on Arduino. Attach the other pin to 5V. Use
the resistor as a pull-down, providing a reference to the ground, by attaching it from pin
4 to the ground.
Once you have programmed your board, unplug the USB cable, open a text editor and put
the text cursor in the typing area. Connect the board to your computer through USB again
and press the button to write in the document.
Result
By using any text editor, it will display the text sent via Arduino.
153
Arduino
Using the Mouse library, you can control a computer's onscreen cursor with an Arduino
Leonardo, Micro, or Due.
This particular example uses five pushbuttons to move the onscreen cursor. Four of the
buttons are directional (up, down, left, right) and one is for a left mouse click. Cursor
movement from Arduino is always relative. Every time an input is read, the cursor's
position is updated relative to its current position.
Whenever one of the directional buttons is pressed, Arduino will move the mouse, mapping
a HIGH input to a range of 5 in the appropriate direction.
The fifth button is for controlling a left-click from the mouse. When the button is released,
the computer will recognize the event.
Components Required
You will need the following components:
1x Breadboard
5x momentary pushbuttons
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image below.
154
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
For this example, you need to use Arduino IDE 1.6.7
Arduino Code
/*
Button Mouse Control
For Leonardo and Due boards only .Controls the mouse from five pushbuttons on an
Arduino Leonardo, Micro or Due.
Hardware:
* 5 pushbuttons attached to D2, D3, D4, D5, D6
The mouse movement is always relative. This sketch reads
four pushbuttons, and uses them to set the movement of the mouse.
WARNING:
Make sure you have control before you use the mouse commands.
*/
#include "Mouse.h"
// set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
155
Arduino
void setup()
{
// initialize the buttons' inputs:
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT);
// initialize mouse control:
Mouse.begin();
}
void loop()
{
// read the buttons:
int upState = digitalRead(upButton);
int downState = digitalRead(downButton);
int rightState = digitalRead(rightButton);
int leftState = digitalRead(leftButton);
int clickState = digitalRead(mouseButton);
int
// if X or Y is non-zero, move:
if ((xDistance != 0) || (yDistance != 0)) {
Mouse.move(xDistance, yDistance, 0);
}
156
Arduino
Code to Note
Connect your board to your computer with a micro-USB cable. The buttons are connected
to digital inputs from pins 2 to 6. Make sure you use 10k pull-down resistors.
157
Arduino
This example listens for a byte coming from the serial port. When received, the board
sends a keystroke back to the computer. The sent keystroke is one higher than what is
received, so if you send an "a" from the serial monitor, you will receive a "b" from the
board connected to the computer. A "1" will return a "2" and so on.
Warning: When you use the Keyboard.print() command, the Leonardo, Micro or Due
board takes over your computer's keyboard. To ensure you do not lose control of your
computer while running a sketch with this function, set up a reliable control system before
you call Keyboard.print(). This sketch is designed to only send a Keyboard command after
the board has received a byte over the serial port.
Components Required
You will need the following components:
Procedure
Just connect your board to the computer using USB cable.
158
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
Notes: You must include the keypad library in your Arduino library file. Copy and paste
the keypad library file inside the file with the name libraries highlighted with yellow color.
159
Arduino
Arduino Code
/*
Keyboard test
For the Arduino Leonardo, Micro or Due Reads a byte from the serial port, sends
a keystroke back. The sent keystroke is one higher than what's received, e.g. if
you send a, you get b, send
A you get B, and so forth.
The circuit:
* none
*/
#include "Keyboard.h"
void setup() {
// open the serial port:
Serial.begin(9600);
// initialize control over the keyboard:
Keyboard.begin();
}
void loop() {
// check for incoming serial data:
if (Serial.available() > 0) {
// read incoming serial data:
char inChar = Serial.read();
// Type the next ASCII value from what you received:
Keyboard.write(inChar + 1);
}
}
Code to Note
Once programed, open your serial monitor and send a byte. The board will reply with a
keystroke, that is one number higher.
Result
The board will reply with a keystroke that is one number higher on Arduino IDE serial
monitor when you send a byte.
160
Arduino
Arduino Sensors
161
Arduino
In this section, we will learn how to interface our Arduino board with different sensors. We
will discuss the following sensors
PIR SENSOR
ULTRASONIC SENSOR
GPS
The connections are simple. The first pin on the left to 3-5V power, the second pin to the
data input pin and the right-most pin to the ground.
162
Arduino
Technical Details
Power: 3-5V
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
1x DHT22
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image below.
163
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
Arduino Code
// Example testing sketch for various DHT humidity/temperature sensors
#include "DHT.h"
#define DHTPIN 2
164
Arduino
// DHT 11
// DHT 22
(AM2302), AM2321
// DHT 21 (AM2301)
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
delay(2000);
float h = dht.readHumidity();
// Reading temperature or humidity takes about 250 milliseconds!
float t = dht.readTemperature();
// Read temperature as Celsius (the default)
float f = dht.readTemperature(true);
// Read temperature as Fahrenheit (isFahrenheit = true)
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f))
{
Serial.println("Failed to read from DHT sensor!");
return;
165
Arduino
Code to Note
DHT22 sensor has four terminals (Vcc, DATA, NC, GND), which are connected to the board
as follows:
We need to connect 10k ohm resistor (pull up resistor) between the DATA and the
Vcc pin
Once hardware connections are done, you need to add DHT22 library to your Arduino
library file as described earlier.
166
Arduino
Result
You will see the temperature and humidity display on serial port monitor which is updated
every 2 seconds.
167
Arduino
The Temperature Sensor LM35 series are precision integrated-circuit temperature devices
with an output voltage linearly proportional to the Centigrade temperature.
The LM35 device has an advantage over linear temperature sensors calibrated in Kelvin,
as the user is not required to subtract a large constant voltage from the output to obtain
convenient Centigrade scaling. The LM35 device does not require any external calibration
or trimming to provide typical accuracies of C at room temperature and C over a
full 55C to 150C temperature range.
Technical Specifications
168
Arduino
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
1x LM35 sensor
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
169
Arduino
Arduino Code
float temp;
int tempPin = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
temp = analogRead(tempPin);
// read analog volt from sensor and save to variable temp
Serial.print("*C");
Serial.println();
delay(1000);
Code to Note
LM35 sensor has three terminals - Vs, Vout and GND.
follows:
The Analog to Digital Converter (ADC) converts analog values into a digital approximation
based on the formula ADC Value = sample * 1024 / reference voltage (+5v). So with a
+5 volt reference, the digital approximation will be equal to input voltage * 205.
Result
You will see the temperature display on the serial port monitor which is updated every
second.
170
Arduino
Water sensor brick is designed for water detection, which can be widely used in sensing
rainfall, water level, and even liquid leakage.
Connecting a water sensor to an Arduino is a great way to detect a leak, spill, flood, rain,
etc. It can be used to detect the presence, the level, the volume and/or the absence of
water. While this could be used to remind you to water your plants, there is a better Grove
sensor for that. The sensor has an array of exposed traces, which read LOW when water
is detected.
In this chapter, we will connect the water sensor to Digital Pin 8 on Arduino, and will enlist
the very handy LED to help identify when the water sensor comes into contact with a
source of water.
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
1x Water Sensor
1x led
171
Arduino
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in
the image given below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking on New.
172
Arduino
Arduino Code
#define
Grove_Water_Sensor
#define
LED
void setup()
{
pinMode(Grove_Water_Sensor, INPUT);
pinMode(LED, OUTPUT);
}
void loop()
{
/* The water sensor will switch LOW when water is detected.
Get the Arduino to illuminate the LED and activate the buzzer
when water is detected, and switch both off when no water is present
*/
if( digitalRead(Grove_Water_Sensor) == LOW)
{
digitalWrite(LED,HIGH);
}
else
{
digitalWrite(LED,LOW);
}
}
Code to Note
Water sensor has three terminals - S, Vout(+), and GND (-).
follows:
When the sensor detects water, pin 8 on Arduino becomes LOW and then the LED on
Arduino is turned ON.
Result
You will see the indication LED turn ON when the sensor detects water.
173
Arduino
PIR sensors allow you to sense motion. They are used to detect whether a human has
moved in or out of the sensors range. They are commonly found in appliances and gadgets
used at home or for businesses. They are often referred to as PIR, "Passive Infrared",
"Pyroelectric", or "IR motion" sensors.
Following are the advantages of PIR Sensors
Small in size
Easy to interface
Inexpensive
Low-power
Easy to use
PIRs are made of pyroelectric sensors, a round metal can with a rectangular crystal in the
center, which can detect levels of infrared radiation. Everything emits low-level radiation,
and the hotter something is, the more radiation is emitted. The sensor in a motion detector
is split in two halves. This is to detect motion (change) and not average IR levels. The two
halves are connected so that they cancel out each other. If one-half sees more or less IR
radiation than the other, the output will swing high or low.
174
Arduino
PIRs have adjustable settings and have a header installed in the 3-pin ground/out/power
pads.
For many basic projects or products that need to detect when a person has left or entered
the area, PIR sensors are great. Note that PIRs do not tell you the number of people
around or their closeness to the sensor. The lens is often fixed to a certain sweep at a
distance and they are sometimes set off by the pets in the house.
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
175
Arduino
Procedure
Follow the circuit diagram and make the connections as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
176
Arduino
Arduino Code
#define pirPin 2
int calibrationTime = 30;
long unsigned int lowIn;
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int PIRValue = 0;
void setup()
{
Serial.begin(9600);
pinMode(pirPin, INPUT);
}
void loop()
{
PIRSensor();
}
void PIRSensor()
{
if(digitalRead(pirPin) == HIGH)
{
if(lockLow)
{
PIRValue = 1;
lockLow = false;
Serial.println("Motion detected.");
delay(50);
}
takeLowTime = true;
}
if(digitalRead(pirPin) == LOW)
177
Arduino
{
if(takeLowTime){lowIn = millis();takeLowTime = false;}
if(!lockLow && millis() - lowIn > pause)
{
PIRValue = 0;
lockLow = true;
Serial.println("Motion ended.");
delay(50);
}
}
}
Code to Note
PIR sensor has three terminals - Vcc, OUT and GND. Connect the sensor as follows:
You can adjust the sensor sensitivity and delay time via two variable resistors located at
the bottom of the sensor board.
Once the sensor detects any motion, Arduino will send a message via the serial port to
say that a motion is detected. The PIR sense motion will delay for certain time to check if
there is a new motion. If there is no motion detected, Arduino will send a new message
saying that the motion has ended.
Result
You will see a message on your serial port if a motion is detected and another message
when the motion stops.
178
Arduino
The HC-SR04 ultrasonic sensor uses SONAR to determine the distance of an object just
like the bats do. It offers excellent non-contact range detection with high accuracy and
stable readings in an easy-to-use package from 2 cm to 400 cm or 1 to 13 feet.
The operation is not affected by sunlight or black material, although acoustically, soft
materials like cloth can be difficult to detect. It comes complete with ultrasonic transmitter
and receiver module.
Technical Specifications
Power Supply:+5V DC
179
Arduino
Resolution: 0.3 cm
Components Required
You will need the following components:
1x Breadboard
1x Arduino Uno R3
Procedure
Follow the circuit diagram and make the connections as shown in the image given below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
180
Arduino
Arduino Code
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor
void setup()
{
Serial.begin(9600); // Starting Serial Terminal
}
void loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
181
Arduino
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
Code to Note
The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND connected as
follows:
In our program, we have displayed the distance measured by the sensor in inches and cm
via the serial port.
Result
You will see the distance measured by sensor in inches and cm on Arduino serial monitor.
182
Arduino
Pushbuttons or switches connect two open terminals in a circuit. This example turns on
the LED on pin 2 when you press the pushbutton switch connected to pin 8.
Pull-down Resistor
Pull-down resistors are used in electronic logic circuits to ensure that inputs to Arduino
settle at expected logic levels if external devices are disconnected or are at highimpedance. As nothing is connected to an input pin, it does not mean that it is a logical
zero. Pull down resistors are connected between the ground and the appropriate pin on
the device.
An example of a pull-down resistor in a digital circuit is shown in the following figure. A
pushbutton switch is connected between the supply voltage and a microcontroller pin. In
such a circuit, when the switch is closed, the micro-controller input is at a logical high
value, but when the switch is open, the pull-down resistor pulls the input voltage down to
the ground (logical zero value), preventing an undefined state at the input.
The pull-down resistor must have a larger resistance than the impedance of the logic
circuit, or else it might pull the voltage down too much and the input voltage at the pin
would remain at a constant logical low value, regardless of the switch position.
183
Arduino
Components Required
You will need the following components:
1x LED
Procedure
Follow the circuit diagram and make the connections as shown in the image given below .
184
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking on New.
Arduino Code
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 8;
const int ledPin =
2;
void setup()
{
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop()
{
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
185
Arduino
Code to Note
When the switch is open, (pushbutton is not pressed), there is no connection between the
two terminals of the pushbutton, so the pin is connected to the ground (through the pulldown resistor) and we read a LOW. When the switch is closed (pushbutton is pressed), it
makes a connection between its two terminals, connecting the pin to 5 volts, so that we
read a HIGH.
Result
LED is turned ON when the pushbutton is pressed and OFF when it is released.
186
Arduino
187
Arduino DC Motor
Arduino
In this chapter, we will interface different types of motors with the Arduino board (UNO)
and show you how to connect the motor and drive it from your board.
There are three different type of motors
DC motor
Servo motor
Stepper motor
A DC motor (Direct Current motor) is the most common type of motor. DC motors normally
have just two leads, one positive and one negative. If you connect these two leads directly
to a battery, the motor will rotate. If you switch the leads, the motor will rotate in the
opposite direction.
Warning: Do not drive the motor directly from Arduino board pins. This may damage the
board. Use a driver Circuit or an IC.
We will divide this chapter into three parts
Components Required
You will need the following components:
1x PN2222 Transistor
188
Arduino
1x Small 6V DC Motor
1x 1N4001 diode
1x 270 Resistor
Procedure
Follow the circuit diagram and make the connections as shown in the image given below.
Precautions
Take the following precautions while making the connections.
First, make sure that the transistor is connected in the right way. The flat side of
the transistor should face the Arduino board as shown in the arrangement.
Second, the striped end of the diode should be towards the +5V power line
according to the arrangement shown in the image.
189
Arduino
}
void loop()
{
digitalWrite(motorPin, HIGH);
}
Code to Note
The transistor acts like a switch, controlling the power to the motor. Arduino pin 3 is used
to turn the transistor on and off and is given the name 'motorPin' in the sketch.
Result
Motor will spin in full speed when the Arduino pin number 3 goes high.
Arduino Code
int motorPin = 9;
void setup()
{
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
while (! Serial);
190
Arduino
Serial.println("Speed 0 to 255");
}
void loop()
{
if (Serial.available())
{
int speed = Serial.parseInt();
if (speed >= 0 && speed <= 255)
{
analogWrite(motorPin, speed);
}
}
}
Code to Note
The transistor acts like a switch, controlling the power of the motor. Arduino pin 3 is used
to turn the transistor on and off and is given the name 'motorPin' in the sketch.
When the program starts, it prompts you to give the values to control the speed of the
motor. You need to enter a value between 0 and 255 in the Serial Monitor.
In the 'loop' function, the command 'Serial.parseInt' is used to read the number entered
as text in the Serial Monitor and convert it into an 'int'. You can type any number here.
The 'if' statement in the next line simply does an analog write with this number, if the
number is between 0 and 255.
Result
The DC motor will spin with different speeds according to the value (0 to 250) received
via the serial port.
191
Arduino
Components Required
You will need the following components:
1 x L298 bridge IC
1 x DC motor
1 x Arduino UNO
1 x breadboard
10 x jumper wires
192
Arduino
Procedure
Following is the schematic diagram of the DC motor interface to Arduino Uno board.
The above diagram shows how to connect the L298 IC to control two motors. There are
three input pins for each motor, Input1 (IN1), Input2 (IN2), and Enable1 (EN1) for Motor1
and Input3, Input4, and Enable2 for Motor2.
Since we will be controlling only one motor in this example, we will connect the Arduino
to IN1 (pin 5), IN2 (pin 7), and Enable1 (pin 6) of the L298 IC. Pins 5 and 7 are digital,
i.e. ON or OFF inputs, while pin 6 needs a pulse-width modulated (PWM) signal to control
the motor speed.
The following table shows which direction the motor will turn based on the digital values
of IN1 and IN2.
IN1
IN2
Motor Behavior
BRAKE
FORWARD
1
BACKWARD
BRAKE
Pin IN1 of the IC L298 is connected to pin 8 of Arduino while IN2 is connected to pin 9.
These two digital pins of Arduino control the direction of the motor. The EN A pin of IC is
connected to the PWM pin 2 of Arduino. This will control the speed of the motor.
To set the values of Arduino pins 8 and 9, we have used the digitalWrite() function, and
to set the value of pin 2, we have to use the analogWrite() function.
193
Arduino
Connection Steps
Connect 5V and the ground of the IC to 5V and the ground of Arduino, respectively.
Connect Arduino using Arduino USB cable and upload the program to Arduino using
Arduino IDE software.
Provide power to Arduino board using power supply, battery, or USB cable.
Arduino Code
const int pwm = 2 ;
pinMode(in_1,OUTPUT) ;
pinMode(in_2,OUTPUT) ;
}
void loop()
{
//For Clock wise motion , in_1 = High , in_2 = Low
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,LOW) ;
analogWrite(pwm,255) ;
/* setting pwm of the motor to 255 we can change the speed of rotation
by changing pwm input but we are only using arduino so we are using highest
value to driver the motor
*/
194
Arduino
Result
The motor will run first in the clockwise (CW) direction for 3 seconds and then counterclockwise (CCW) for 3 seconds.
195
Arduino
A Servo Motor is a small device that has an output shaft. This shaft can be positioned to
specific angular positions by sending the servo a coded signal. As long as the coded signal
exists on the input line, the servo will maintain the angular position of the shaft. If the
coded signal changes, the angular position of the shaft changes. In practice, servos are
used in radio-controlled airplanes to position control surfaces like the elevators and
rudders. They are also used in radio-controlled cars, puppets, and of course, robots.
Servos are extremely useful in robotics. The motors are small, have built-in control
circuitry, and are extremely powerful for their size. A standard servo such as the Futaba
S-148 has 42 oz/inches of torque, which is strong for its size. It also draws power
proportional to the mechanical load. A lightly loaded servo, therefore, does not consume
much energy.
The guts of a servo motor is shown in the following picture. You can see the control
circuitry, the motor, a set of gears, and the case. You can also see the 3 wires that connect
to the outside world. One is for power (+5volts), ground, and the white wire is the control
wire.
196
Arduino
How Do You Communicate the Angle at Which the Servo Should Turn?
The control wire is used to communicate the angle. The angle is determined by the duration
of a pulse that is applied to the control wire. This is called Pulse Coded Modulation. The
servo expects to see a pulse every 20 milliseconds (.02 seconds). The length of the pulse
will determine how far the motor turns. A 1.5 millisecond pulse, for example, will make
the motor turn to the 90-degree position (often called as the neutral position). If the pulse
is shorter than 1.5 milliseconds, then the motor will turn the shaft closer to 0 degrees. If
the pulse is longer than 1.5 milliseconds, the shaft turns closer to 180 degrees.
Components Required
You will need the following components:
1x Servo Motor
197
Arduino
1x ULN2003 driving IC
1x 10 K Resistor
Procedure
Follow the circuit diagram and make the connections as shown in the image given below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking on New.
198
Arduino
Arduino Code
/* Controlling a servo position using a potentiometer (variable resistor) */
#include <Servo.h>
Servo myservo;
int potpin = 0;
int val;
void setup()
{
myservo.attach(9);
}
void loop()
{
val = analogRead(potpin);
// reads the value of the potentiometer (value between 0 and 1023)
delay(15);
}
Code to Note
Servo motors have three terminals - power, ground, and signal. The power wire is typically
red, and should be connected to the 5V pin on the Arduino. The ground wire is typically
black or brown and should be connected to one terminal of ULN2003 IC (10 -16). To
protect your Arduino board from damage, you will need some driver IC to do that. Here
we have used ULN2003 IC to drive the servo motor. The signal pin is typically yellow or
orange and should be connected to Arduino pin number 9.
199
Arduino
Result
By changing the pots NOP position, servo motor will change its angle.
200
Arduino
A Stepper Motor or a step motor is a brushless, synchronous motor, which divides a full
rotation into a number of steps. Unlike a brushless DC motor, which rotates continuously
when a fixed DC voltage is applied to it, a step motor rotates in discrete step angles.
The Stepper Motors therefore are manufactured with steps per revolution of 12, 24, 72,
144, 180, and 200, resulting in stepping angles of 30, 15, 5, 2.5, 2, and 1.8 degrees per
step. The stepper motor can be controlled with or without feedback.
Imagine a motor on an RC airplane. The motor spins very fast in one direction or another.
You can vary the speed with the amount of power given to the motor, but you cannot tell
the propeller to stop at a specific position.
Now imagine a printer. There are lots of moving parts inside a printer, including motors.
One such motor acts as the paper feed, spinning rollers that move the piece of paper as
ink is being printed on it. This motor needs to be able to move the paper an exact distance
to be able to print the next line of text or the next line of an image.
There is another motor attached to a threaded rod that moves the print head back and
forth. Again, that threaded rod needs to be moved an exact amount to print one letter
after another. This is where the stepper motors come in handy.
201
Arduino
tutorial. However, it is always recommended that you consult the datasheets and guides
of the motors and drivers specific to the models you have.
Components Required
You will need the following components
1x LM298 driving IC
202
Arduino
Procedure
Follow the circuit diagram and make the connections as shown in the image given below.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
203
Arduino
Arduino Code
/* Stepper Motor Control */
#include <Stepper.h>
const int stepsPerRevolution = 90;
// change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(5);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
// step one revolution
in one direction:
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
// step one revolution in the other direction:
Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}}
Code to Note
This program drives a unipolar or bipolar stepper motor. The motor is attached to digital
pins 8 - 11 of Arduino.
Result
The motor will take one revolution in one direction, then one revolution in the other
direction.
204
Arduino
205
Arduino
In this chapter, we will use the Arduino Tone Library. It is nothing but an Arduino Library,
which produces square-wave of a specified frequency (and 50% duty cycle) on any Arduino
pin. A duration can optionally be specified, otherwise the wave continues until the stop()
function is called. The pin can be connected to a piezo buzzer or a speaker to play the
tones.
Warning: Do not connect the pin directly to any audio input. The voltage is considerably
higher than the standard line level voltages, and can damage sound card inputs, etc. You
can use a voltage divider to bring the voltage down.
You MUST have a resistor in line with the speaker, or you WILL damage the controller.
Components Required
You will need the following components
1x 8-ohm speaker
1x 1k resistor
Procedure
Follow the circuit diagram and make the connections as shown in the image given below.
206
Arduino
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
To make the pitches.h file, either click the button just below the serial monitor icon and
choose "New Tab", or use Ctrl+Shift+N.
207
Arduino
Then paste the following code:
/*************************************************
* Public Constants
*************************************************/
#define NOTE_B0
31
#define NOTE_C1
33
#define NOTE_CS1 35
#define NOTE_D1
37
#define NOTE_DS1 39
#define NOTE_E1
41
#define NOTE_F1
44
#define NOTE_FS1 46
#define NOTE_G1
49
#define NOTE_GS1 52
#define NOTE_A1
55
#define NOTE_AS1 58
#define NOTE_B1
62
#define NOTE_C2
65
#define NOTE_CS2 69
#define NOTE_D2
73
#define NOTE_DS2 78
#define NOTE_E2
82
#define NOTE_F2
87
#define NOTE_FS2 93
#define NOTE_G2
98
110
123
#define NOTE_C3
131
147
208
Arduino
165
#define NOTE_F3
175
196
220
247
#define NOTE_C4
262
294
330
#define NOTE_F4
349
392
440
494
#define NOTE_C5
523
587
659
#define NOTE_F5
698
784
880
988
#define NOTE_C6
1047
209
Arduino
#define NOTE_D6
1175
1319
#define NOTE_F6
1397
1568
1760
1976
#define NOTE_C7
2093
2349
2637
#define NOTE_F7
2794
3136
3520
3951
#define NOTE_C8
4186
4699
Arduino Code
#include "pitches.h"
// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_GS3, NOTE_G3,0, NOTE_B3, NOTE_C4};
// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };
210
Arduino
void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {
// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);
//pause for the note's duration plus 30 ms:
delay(noteDuration +30);
}
}
void loop()
{
// no need to repeat the melody.
}
Code to Note
The code uses an extra file, pitches.h. This file contains all the pitch values for typical
notes. For example, NOTE_C4 is middle C. NOTE_FS4 is F sharp, and so forth. This note
table was originally written by Brett Hagman, on whose work the tone() command was
based. You may find it useful whenever you want to make musical notes.
Result
You will hear musical notes saved in the pitches.h. file.
211
Arduino
The wireless transmitter and receiver modules work at 315 Mhz. They can easily fit into a
breadboard and work well with microcontrollers to create a very simple wireless data link.
With one pair of transmitter and receiver, the modules will only work communicating data
one-way, however, you would need two pairs (of different frequencies) to act as a
transmitter/receiver pair.
Note: These modules are indiscriminate and receive a fair amount of noise. Both the
transmitter and receiver work at common frequencies and do not have IDs.
Size: 30 * 14 * 7mm
Dimensions: 19 * 19mm
Operating mode: AM
212
Arduino
Components Required
You will need the following components
1x Rf link transmitter
1x Rf link receiver
Procedure
Follow the circuit diagram and make the connections as shown in the image given below .
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will
control your circuit. Open a new sketch File by clicking New.
213
Arduino
Note: You must include the keypad library in your Arduino library file. Copy and paste the
VirtualWire.lib file in the libraries folder as highlighted in the screenshot given below.
214
Arduino
vw_set_ptt_inverted(true);
vw_set_tx_pin(12);
vw_setup(4000);// speed of data transfer Kbps
}
void loop()
{
controller="1"
Code to Note
This is a simple code. First, it will send character '1' and after two seconds it will send
character '0' and so on.
pinMode(5, OUTPUT);
vw_rx_start();
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
215
Arduino
Code to Note
The LED connected to pin number 5 on the Arduino board is turned ON when character '1'
is received and turned OFF when character '0' received.
216
Arduino
The CC3000 WiFi module from Texas Instruments is a small silver package, which finally
brings easy-to-use, affordable WiFi functionality to your Arduino projects.
It uses SPI for communication (not UART!) so you can push data as fast as you want or
as slow as you want. It has a proper interrupt system with IRQ pin so you can have
asynchronous connections. It supports 802.11b/g, open/WEP/WPA/WPA2 security, TKIP &
AES. A built-in TCP/IP stack with a "BSD socket" interface supports TCP and UDP in both
the client and the server mode.
Components Required
You will need the following components:
1xArduino Uno
1x5V relay
1xRectifier diode
1x LED
For this project, you just need the usual Arduino IDE, the Adafruits CC3000 library, and
the CC3000 MDNS library. We are also going to use the aREST library to send commands
to the relay via WiFi.
217
Arduino
Procedure
Follow the circuit diagram and make the connections as shown in the image given below .
Connect the IRQ pin of the CC3000 board to pin number 3 of the Arduino board.
Connect the SPI pins to Arduino board: MOSI, MISO, and CLK to pins 11, 12, and
13, respectively.
First, connect pin number 8 of Arduino board to one pin of the coil.
You also have to place the rectifier diode (anode connected to the ground pin) over the
pins of the coil to protect your circuit when the relay is switching.
Connect the +5V of Arduino board to the common pin of the relays switch.
218
Arduino
Finally, connect one of the other pin of the switch (usually, the one which is not
connected when the relay is off) to the LED in series with the 220 Ohm resistor,
and connect the other side of the LED to the ground of Arduino board.
Code to Note
The code is self-explanatory. You can just upload it to the board and the relay will switch
states every second, and the LED will switch ON and OFF accordingly.
219
Arduino
You need to define inside the code what is specific to your configuration, i.e. Wi-Fi name
and password, and the port for TCP communications (we have used 80 here).
// WiFi network (change with your settings!)
#define WLAN_SSID "yourNetwork"
//
This
can
be
WLAN_SEC_UNSEC,
We can then create the CC3000 instance, server and aREST instance:
// Server instance
Adafruit_CC3000_Server restServer(LISTEN_PORT); // DNS responder instance
MDNSResponder
mdns;
220
Arduino
We also need to listen for incoming connections.
restServer.begin();
Next, we will code the loop() function of the sketch that will be continuously executed. We
first have to update the mDNS server.
mdns.update();
The server running on Arduino board will wait for the incoming connections and handle
the requests.
Adafruit_CC3000_ClientRef client = restServer.available();
rest.handle(client);
It is now quite easy to test the projects via WiFi. Make sure you updated the sketch with
your own WiFi name and password, and upload the sketch to your Arduino board. Open
your Arduino IDE serial monitor, and look for the IP address of your board.
Let us assume for the rest here that it is something like 192.168.1.103.
Then, simply go to your favorite web browser, and type:
192.168.1.103/digital/8/1
You should see that your relay automatically turns ON.
221
Arduino
</head>
Then, we define two buttons inside the interface, one to turn the relay on, and the other
to turn it off again.
<div class='container'>
<h1>Relay Control</h1>
<div class='row'>
<div class="col-md-1">Relay</div>
<div class="col-md-2">
<button id='on' class='btn btn-block btn-success'>On</button>
</div>
<div class="col-md-2">
<button id='off' class='btn btn-block btn-danger'>On</button>
</div>
</div>
</div>
Now, we also need a client-side Javascript file to handle the clicks on the buttons. We will
also create a device that we will link to the mDNS name of our Arduino device. If you
changed this in Arduino code, you will need to modify it here as well.
// Create device
var device = new Device("arduino.local");
// Button
$('#on').click(function() {
device.digitalWrite(8, 1);
});
$('#off').click(function() {
device.digitalWrite(8, 0);
});
The complete code for this project can be found on the GitHub repository. Go into the
interface folder, and simply open the HTML file with your favorite browser. You should see
something similar inside your browser:
222
Arduino
Try to click a button on the web interface; it should change the state of the relay nearly
instantly.
If you managed to get it working, bravo! You just built a Wi-Fi-controlled light switch. Of
course, you can control much more than lights with this project. Just make sure your relay
supports the power required for the device you want to control, and you are good to go.
223