Arduino Full Reference
Arduino Full Reference
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.
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 FTDI-
Pro 3.3v/8 3.3V 8MHz 14 6 6 1 Compatible
MHz Header
Arduino FTDI-
Pro 5V 16MHz 14 6 6 1 Compatible
5V/16MHz Header
Arduino FTDI-
mini 05 5V 16MHz 14 8 6 1 Compatible
Header
Arduino FTDI-
Pro mini 3.3V 8MHz 14 8 6 1 Compatible
3.3v/8mhz Header
Arduino FTDI-
Pro mini 5V 16MHz 14 8 6 1 Compatible
5v/16mhz Header
Arduino FTDI-
Ethernet 5V 16MHz 14 6 6 1 Compatible
Header
FTDI-
Arduino
3.3V 8MHz 14 8 6 1 Compatible
Fio
Header
LilyPad FTDI-
Arduino Compatible
3.3V 8MHz 14 6 6 1
328 main Header
board
LilyPad FTDI-
Arduino 3.3V 8MHz 9 4 5 0 Compatible
Header
simple
board
Mega FTDI-
Pro 3.3V 3.3V 8MHz 54 16 14 4 Compatible
Header
Mega FTDI-
Pro 5V 5V 16MHz 54 16 14 4 Compatible
Header
Mega FTDI-
Pro Mini 3.3V 8MHz 54 16 14 4 Compatible
3.3V Header
Arduino boards based on AT91SAM3X8E microcontroller
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 boards can be powered directly from the AC mains power supply
by connecting it to the Barrel Jack (2).
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.
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.
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.
This LED should light up when you plug your Arduino into a power source
to indicate that your board is powered up correctly. If this light does not
turn on, then there is something wrong with the connection.
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
Arduino - Installation
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.
Step 2 − Download Arduino IDE Software.
You can get different versions of Arduino IDE from the Download page on
the Arduino Official website. You must select your software, which is
compatible with your operating system (Windows, IOS, or Linux). After
your file download is complete, unzip the file.
After your Arduino IDE software is downloaded, you need to unzip the
folder. Inside the folder, you can find the application icon with an infinity
label (application.exe). Double-click the icon to start the IDE.
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.
Here, we have selected Arduino Uno board according to our tutorial, but
you must select the name matching the board that you are using.
Step 7 − Select your serial port.
Before explaining how we can upload our program to the board, we must
demonstrate the function of each symbol appearing in the Arduino IDE
toolbar.
A − Used to check if there is any compilation error.
F − Serial monitor used to receive serial data from the board and send the
serial data to the board.
Now, simply click the "Upload" button in the environment. Wait a few
seconds; you will see the RX and TX LEDs on the board, flashing. If the
upload is successful, the message "Done uploading" will appear in the
status bar.
Note − If you have an Arduino Mini, NG, or other board, you need to press
the reset button physically on the board, immediately before clicking the
upload button on the Arduino Software.
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
Void setup ( ) {
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 − -
The following table provides all the data types that you will use during
Arduino programming.
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 ; // declaration of variable with type boolean and initialize it with
true
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
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 m = 25 ;//declaration of variable with type byte and initialize it with 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.
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 Long and initialize 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).
Example
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).
Example
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.
Example
float num = 1.352;//declaration of variable with type float and initialize it with 1.352
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.
Example
double num = 45.352 ;// declaration of variable with type double and initialize it with
45.352
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 x , y ;
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.
Void setup () {
Void loop () {
int x , y ;
x = 0;
y = 0; actual initialization
z = 10;
Arduino - Operators
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 −
Show Example
A + B will
addition + Adds two operands
give 30
A * B will
multiplication * Multiply both operands
give 200
B / A will
division / Divide numerator by denominator
give 2
Comparison Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Boolean Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Show Example
Operator Operator Description Example
name simple
(A | B) will give
Binary OR Operator copies a bit if it
or | 61 which is
exists in either operand
0011 1101
Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
Show Example
A &= 2 is
compound
&= Bitwise AND assignment operator same as A = A
bitwise and
&2
Control Statements are elements in Source Code that control the flow of
program execution. They are −
If statement
If …else statement
Conditional Operator ? :
5
The conditional operator ? : is the only ternary operator in C.
Arduino - Loops
Programming languages provide various control structures that allow for
more complicated execution paths.
while loop
1 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.
do…while loop
The do…while loop is similar to the while loop. In the while loop, the loop-
2
continuation condition is tested at the beginning of the loop before
performed the body of the loop.
for loop
Nested Loop
4 C language allows you to use one loop inside another loop. The following
example illustrates the concept.
Infinite loop
5
It is the loop having no terminating condition, so the loop becomes infinite.
Arduino - Functions
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.
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.
Function Declaration
A function is declared outside any other functions, above or below the loop
function.
The first way is just writing the part of the function called a function
prototype above the loop function, which consists of −
Function name
Function argument type, no need to write the argument name
Example
int sum_func (int x, int y) // function declaration {
int z = 0;
z = x+y ;
void setup () {
Void loop () {
int result = 0 ;
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)
Example
int sum_func (int , int ) ; // function prototype
void setup () {
Void loop () {
int result = 0 ;
int z = 0;
z = x+y ;
The second method just declares the function above the loop function.
Arduino - Strings
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.
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.
A string is a special array that has one extra element at the end of the
string, which always has the value of 0 (zero). This is known as a "null
terminated string".
Example
void setup() {
Serial.begin(9600);
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
Serial.println(my_str);
void loop() {
Example
void setup() {
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() {
Serial.begin(9600);
Serial.println(like);
like[13] = 0;
Serial.println(like);
like[19] = 'e';
like[20] = 'a';
Serial.println(like);
void loop() {
Result
I like coffee and cake
I like coffee
I like coffee and tea
When the string is printed, all the characters are printed up to the new null
terminating zero. The other characters do not disappear; they still exist in
the memory and the string array is still the same size. The only difference
is that any function that works with strings will only see the string up to
the first null terminator.
New characters overwrite "cak" of the word "cake" with the word "tea".
This is done by overwriting individual characters. The 'e' of "cake" is
replaced with a new null terminating character. The result is that the string
is actually terminated with two null characters, the original one at the end
of the string and the new one that replaces the 'e' in "cake". This makes
no difference when the new string is printed because the function that
prints the string stops printing the string characters when it encounters
the first null terminator.
Example
void setup() {
Serial.begin(9600);
Serial.println(str);
num = strlen(str);
Serial.println(num);
strcpy(out_str, str);
Serial.println(out_str);
Serial.println(out_str);
num = strlen(out_str);
Serial.println(num);
num = sizeof(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
Copy a String
The strcpy() function is used to copy the str[] string to the out_num[]
array. The strcpy() function copies the second string passed to it into the
first string. A copy of the string now exists in the out_num[] array, but
only takes up 18 elements of the array, so we still have 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.
After concatenation, the length of the string is printed to show the new
string length. The length of the array is then printed to show that we have
a 25-character long string in a 40 element long array.
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.
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() {
Serial.begin(9600);
Serial.println(my_str);
my_str.toUpperCase();
Serial.println(my_str);
// (3) overwrite the string
Serial.println(my_str);
Serial.println(my_str);
Serial.println(my_str.length());
void loop() {
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.".
Overwrite a String
The assignment operator is used to assign a new string to
the my_str object that replaces the old string
my_str = "My new string." ;
The main disadvantage of using the String object is that it uses a lot of
memory and can quickly use up the Arduinos RAM memory, which may
cause Arduino to hang, crash or behave unexpectedly. If a sketch on an
Arduino is small and limits the use of objects, then there should be no
problems.
Character array strings are more difficult to use and you may need to write
your own functions to operate on these types of strings. The advantage is
that you have control on the size of the string arrays that you make, so
you can keep the arrays small to save memory.
You need to make sure that you do not write beyond the end of the array
bounds with string arrays. The String object does not have this problem
and will take care of the string bounds for you, provided there is enough
memory for it to operate on. The String object can try to write to memory
that does not exist when it runs out of memory, but will never write over
the end of the string that it is operating on.
The practical uses of strings will be covered in the next part of this course
when we study how to get user input from the Serial Monitor window and
save the input in a string.
Arduino - Time
Arduino provides four different time manipulation functions. They are −
delay () function
1 The way the delay() function works is pretty simple. It accepts a single
integer (or number) argument. This number represents the time
(measured in milliseconds).
delayMicroseconds () function
3 This function is used to return the number of milliseconds at the time, the
Arduino board begins running the current program.
micros () function
The micros() function returns the number of microseconds from the time,
4
the Arduino board begins running the current program. This number
overflows i.e. goes back to zero after approximately 70 minutes.
Arduino - Arrays
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 element’s 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].
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 ] ;
Example
void setup () {
void loop () {
Serial.print (i) ;
Serial.print (‘\r’) ;
}
for ( int j = 0; j < 10; ++j ) // output each array element's value {
Serial.print (n[j]) ;
Serial.print (‘\r’) ;
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
Example
// n is an array of 10 integers
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ;
void setup () {
void loop () {
Serial.print (i) ;
Serial.print (‘\r’) ;
for ( int j = 0; j < 10; ++j ) // output each array element's value {
Serial.print (n[j]) ;
Serial.print (‘\r’) ;
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Example 3: Summing the Elements of an Array
Often, the elements of an array represent a series of values to be used in
a calculation. For example, if the elements of an array represent exam
grades, a professor may wish to total the elements of the array and use
that sum to calculate the class average for the exam. The program sums
the values contained in the 10-element integer array a.
Example
int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;
void setup () {
void loop () {
total += a[ i ];
Serial.print(total) ;
Arrays are important to Arduino and should need a lot more attention. The
following important concepts related to array should be clear to a Arduino
−
2 Multi-Dimensional Arrays
Arrays with two dimensions (i.e., subscripts) often represent tables of
values consisting of information arranged in rows and columns.
This means that it takes very little current to switch the input pin from one
state to another. This makes the pins useful for such tasks as
implementing a capacitive touch sensor or reading an LED as a photodiode.
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.
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) ; // set pin to input without using built in pull up resistor
pinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor
Attempting to run high current devices from the output pins, can damage
or destroy the output transistors in the pin, or damage the entire Atmega
chip. Often, this results in a "dead" pin in the microcontroller but the
remaining chips still function adequately. For this reason, it is a good idea
to connect the OUTPUT pins to other devices through 470Ω or 1k resistors,
unless maximum current drawn from the pins is required for a particular
application.
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
Example
void setup () {
pinMode(button , INPUT_PULLUP);
void setup () {
}
}
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 current-limiting resistor.
pin − the number of the pin whose mode you wish to set
Example
void setup () {
void setup () {
}
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.
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
void setup() {
void loop() {
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 −
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.
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
void setup() {
void loop() {
Examples
The following example demonstrates the use of the functions isdigit,
isalpha, isalnum and isxdigit. Function isdigit determines whether its
argument is a digit (0–9). The function isalpha determines whether its
argument is an uppercase letter (A-Z) or a lowercase letter (a–z). The
function isalnumdetermines whether its argument is an uppercase,
lowercase letter or a digit. Function isxdigit determines whether its
argument is a hexadecimal digit (A–F, a–f, 0–9).
Example 1
void setup () {
Serial.begin (9600);
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
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 (a–z).
Function isupper determines whether its argument is an uppercase letter
(A–Z).
void setup () {
Serial.begin (9600);
Serial.print ("According to islower:\r") ;
void setup () {
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 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.
void setup () {
Serial.begin (9600);
void loop () {
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
Library Macros
Following are the macros defined in the header math.h −
Given below is the list of macros defined in the header math.h
Library Functions
The following functions are defined in the header math.h −
Given below is the list of functions are defined in the header math.h
Example
The following example shows how to use the most common math.h library
functions −
void setup() {
Serial.begin(9600);
void loop() {
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
Example
double sine = sin(2); // approximately 0.90929737091
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
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.
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.
The Zero applications span from smart IoT devices, wearable technology, high-
tech automation, to crazy robotics.
The board is powered by Atmel’s SAMD21 MCU, which features a 32-bit ARM
Cortex® M0+ core.
EDBG also supports a virtual COM port that can be used for device and
bootloader programming.
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 −
$$T_{total} = T_{on}+T_{off}$$
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 −
$$D = \frac{T_{on}}{T_{on}+T_{off}} = \frac{T_{on}}{T_{total}}$$
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.
The Arduino Due supports analogWrite() on pins 2 through 13, and pins
DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to
Analog converters, and act as true analog outputs.
You do not need to call pinMode() to set the pin as an output before calling
analogWrite().
value − the duty cycle: between 0 (always off) and 255 (always on).
Example
void setup() {
void loop() {
randomSeed(seed)
random()
randomSeed (seed)
The function randomSeed(seed) resets Arduino’s 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)); // randomize using noise from analog pin 5
random( )
The random function generates pseudo-random numbers. Following is the
syntax.
Example
long randNumber;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
void loop() {
Serial.print("random1=");
randNumber = random(300);
Serial.print("random2=");
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.
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).
Arduino - Interrupts
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.
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.
The Arduino Mega has six hardware interrupts including the additional
interrupts ("interrupt2" through "interrupt5") on pins 21, 20, 19, and 18.
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 −
Typically, global variables are used to pass data between an ISR and the
main program. To make sure variables shared between an ISR and the
main program are updated correctly, declare them as volatile.
volatile int state = LOW; // To make sure variables shared between an ISR
void setup() {
void loop() {
void blink() {
//ISR function
Arduino - Communication
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 1’s and 0’s.
Advantages and Drawbacks of Parallel Communication
Parallel communication certainly has its advantages. It is faster than serial,
straightforward, and relatively easy to implement. However, it requires
many input/output (I/O) ports and lines. If you have ever had to move a
project from a basic Arduino Uno to a Mega, you know that the I/O lines
on a microprocessor can be precious and few. Therefore, we prefer serial
communication, sacrificing potential speed for pin real estate.
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.
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.
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 1’s 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() {
void loop() {
After the Arduino sketch has been uploaded to Arduino, open the Serial
monitor at the top right section of Arduino IDE.
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 will make Arduino deliver output depending on the input
provided.
void setup() {
}
void loop() {
serial port
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.
Arduino I2C
We have two modes - master code and slave code - to connect two Arduino
boards using I2C. They are −
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
short age = 0;
void loop() {
Wire.beginTransmission(2);
// transmit to device #2
Wire.write("age is = ");
delay(1000);
Slave Receiver
The following functions are used −
Example
}
void loop() {
delay(250);
Master Receiver
The Master, is programmed to request, and then read bytes of data that
are sent from the uniquely addressed Slave Arduino.
Example
void loop() {
delay(500);
Slave Transmitter
The following function is used.
Example
#include <Wire.h>
void setup() {
Byte x = 0;
void loop() {
delay(100);
void requestEvent() {
x++;
}
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.beginTransaction(SPISettings(speedMaximum, dataOrder,
dataMode)) − speedMaximum is the clock, dataOrder(MSBFIRST or
LSBFIRST), dataMode(SPI_MODE0, SPI_MODE1, SPI_MODE2, or
SPI_MODE3).
We have four modes of operation in SPI as follows −
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).
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.begin ();
char c;
SPI.transfer (c);
Serial.print(c);
delay(2000);
SPI as SLAVE
Example
#include <SPI.h>
Serial.begin (115200);
process = false;
buff [indx++] = c; // save data in the next index in the array buff
process = true;
if (process) {
1 × Breadboard
1 × Arduino Uno R3
1 × LED
1 × 330Ω Resistor
2 × Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard
as shown in the image given below.
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.
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
pinMode(2, OUTPUT);
void loop() {
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
Code to Note
pinMode(2, OUTPUT) − Before you can use one of Arduino’s 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.
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.
Components Required
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × LED
1 × 330Ω Resistor
2 × Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard
as shown in the image given below.
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.
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
/*
Fade
This example shows how to fade an LED on pin 9 using the analogWrite()
function.
The analogWrite() function uses PWM, so if you want to change the pin you're
using, be
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.
*/
void setup() {
pinMode(led, OUTPUT);
void loop() {
analogWrite(led, brightness);
fadeAmount = -fadeAmount ;
delay(300);
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.
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.
Components Required
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
2 × 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.
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.
Arduino Code
/*
ReadAnalogVoltage
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V
and ground.
*/
void setup() {
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
Serial.println(voltage);
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 −
int sensorValue = analogRead(A0);
Finally, you need to print this information to your serial window. You can
do this with the command Serial.println() in your last line of code −
Serial.println(voltage)
Now, open Serial Monitor in the Arduino IDE by clicking the icon on the
right side of the top green bar or pressing Ctrl+Shift+M.
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.
Components Required
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
2 × Jumper
8 × 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.
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.
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
/*
Though this graph uses 8LEDs, you can use any number by
*/
const int analogPin = A0; // the pin that the potentiometer is attached to
// loop over the pin array and set them all to output:
pinMode(ledPins[thisLed], OUTPUT);
void loop() {
digitalWrite(ledPins[thisLed], HIGH);
digitalWrite(ledPins[thisLed], LOW);
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.
Components Required
You will need the following components −
1 × Breadboard
1 × pushbutton
1 × Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard
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.
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.
Arduino Code
/*
Keyboard logout
On OSX, CMD-SHIFT-q
To wake: Spacebar.
Circuit:
*/
#define OSX 0
#define WINDOWS 1
#define UBUNTU 2
#include "Keyboard.h"
void setup() {
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
void loop() {
delay(500);
delay(1000);
switch (platform) {
case OSX:
Keyboard.press(KEY_LEFT_GUI);
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();
Keyboard.write(KEY_RETURN);
break;
// do nothing:
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();
Keyboard.write(KEY_RETURN);
break;
}
// do nothing:
while (true);
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.
On OSX, CMD-SHIFT-q
Components Required
You will need the following components −
1 × Breadboard
1 × momentary pushbutton
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.
Arduino Code
/*
The circuit:
*/
#include "Keyboard.h"
void setup() {
void loop() {
counter++;
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.
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 −
1 × Breadboard
5 × momentary pushbuttons
Procedure
Follow the circuit diagram and hook up the components on the breadboard
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.
Arduino Code
/*
For Leonardo and Due boards only .Controls the mouse from
Hardware:
four pushbuttons, and uses them to set the movement of the mouse.
WARNING: When you use the Mouse.move() command, the Arduino takes
over your mouse! Make sure you have control before you use the mouse commands.
*/
#include "Mouse.h"
void setup() {
pinMode(upButton, INPUT);
pinMode(downButton, INPUT);
pinMode(leftButton, INPUT);
pinMode(rightButton, INPUT);
pinMode(mouseButton, INPUT);
void loop() {
// if X or Y is non-zero, move:
if (clickState == HIGH) {
if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT);
if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT);
}
// a delay so the mouse does not move too fast:
delay(responseDelay);
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.
Components Required
You will need the following components −
Procedure
Just connect your board to the computer using USB cable.
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.
Arduino Code
/*
Keyboard test
The sent keystroke is one higher than what's received, e.g. if you send a, you
get b, send
The circuit:
* none
*/
#include "Keyboard.h"
void setup() {
Serial.begin(9600);
Keyboard.begin();
void loop() {
if (Serial.available() > 0) {
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.
PIR SENSOR
ULTRASONIC SENSOR
GPS
In this example, you will learn how to use this sensor with Arduino UNO.
The room temperature and humidity will be printed to the serial monitor.
Technical Details
Power − 3-5V
Components Required
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × DHT22
Procedure
Follow the circuit diagram and hook up the components on the breadboard
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.
Arduino Code
// Example testing sketch for various DHT humidity/temperature sensors
#include "DHT.h"
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
return;
Serial.print (t);
Serial.print (f);
Serial.print (hic);
Serial.print (hif);
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.
Result
You will see the temperature and humidity display on serial port monitor
which is updated every 2 seconds.
Technical Specifications
Calibrated directly in Celsius (Centigrade)
Components Required
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × 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.
Arduino Code
float temp;
int tempPin = 0;
void setup() {
Serial.begin(9600);
void loop() {
temp = analogRead(tempPin);
Serial.print("TEMPERATURE = ");
Serial.print("*C");
Serial.println();
Code to Note
LM35 sensor has three terminals - Vs, Vout and GND. We will connect the
sensor as 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.
Components Required
You will need the following components −
1 × Breadboard
1 × Arduino Uno R3
1 × Water Sensor
1 × led
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.
Arduino Code
#define Grove_Water_Sensor 8 // Attach Water sensor to Arduino Digital Pin 8
#define LED 9 // Attach an LED to Digital Pin 9 (or use onboard LED)
void setup() {
void loop() {
Get the Arduino to illuminate the LED and activate the buzzer
when water is detected, and switch both off when no water is present */
digitalWrite(LED,HIGH);
}else {
digitalWrite(LED,LOW);
Code to Note
Water sensor has three terminals - S, Vout(+), and GND (-). Connect the
sensor as 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.
Arduino - PIR Sensor
PIR sensors allow you to sense motion. They are used to detect whether a
human has moved in or out of the sensor’s 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.
Small in size
Easy to interface
Inexpensive
Low-power
Easy to use
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 −
1 × Breadboard
1 × Arduino Uno R3
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.
Arduino Code
#define pirPin 2
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) {
if(takeLowTime){
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.
Arduino - Ultrasonic Sensor
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.
Technical Specifications
Power Supply − +5V DC
Resolution − 0.3 cm
Components Required
You will need the following components −
1 × Breadboard
1 × 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.
Arduino Code
const int pingPin = 7; // Trigger Pin of Ultrasonic Sensor
void setup() {
void loop() {
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(10);
digitalWrite(pingPin, LOW);
pinMode(echoPin, INPUT);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
return microseconds / 74 / 2;
return microseconds / 29 / 2;
Code to Note
The Ultrasonic sensor has four terminals - +5V, Trigger, Echo, and GND
connected as follows −
Result
You will see the distance measured by sensor in inches and cm on Arduino
serial monitor.
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 high-impedance. 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.
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.
Components Required
You will need the following components −
1 × LED
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.
Arduino Code
// constants won't change. They're used here to
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
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 pull-down 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.
Arduino - DC Motor
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.
DC motor
Servo motor
Stepper motor
Warning − Do not drive the motor directly from Arduino board pins. This
may damage the board. Use a driver Circuit or an IC.
1x PN2222 Transistor
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.
void setup() {
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.
void setup() {
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
while (! Serial);
Serial.println("Speed 0 to 255");
void loop() {
if (Serial.available()) {
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.
Result
The DC motor will spin with different speeds according to the value (0 to
250) received via the serial port.
We will be using the L298 H-Bridge IC here. The L298 can control the
speed and direction of DC motors and stepper motors, and can control two
motors simultaneously. Its current rating is 2A for each motor. At these
currents, however, you will need to use heat sinks.
Components Required
You will need the following components −
1 × L298 bridge IC
1 × DC motor
1 × Arduino UNO
1 × breadboard
10 × jumper wires
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.
BRAKE
1 FORWARD
1 BACKWARD
1 1 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.
Connection Steps
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 ; //initializing pin 2 as pwm
void setup() {
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
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
digitalWrite(in_1,LOW) ;
digitalWrite(in_2,HIGH) ;
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
Result
The motor will run first in the clockwise (CW) direction for 3 seconds and
then counter-clockwise (CCW) for 3 seconds.
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.
1 × Servo Motor
1 × ULN2003 driving IC
1 × 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.
Arduino Code
/* Controlling a servo position using a potentiometer (variable resistor) */
#include <Servo.h>
int val; // variable to read the value from the analog pin
void setup() {
void loop() {
val = analogRead(potpin);
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.
Vout is the output potential, which depends on the applied input voltage
(Vin) and resistors (R1 and R2) in the series. It means that the current
flowing through R1 will also flow through R2 without being divided. In the
above equation, as the value of R2 changes, the Vout scales accordingly
with respect to the input voltage, Vin.
Result
By changing the pot’s NOP position, servo motor will change its angle.
Arduino - Stepper Motor
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.
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.
All you need to know for now is that, to move a stepper motor, you tell it
to move a certain number of steps in one direction or the other, and tell it
the speed at which to step in that direction. There are numerous varieties
of stepper motors. The methods described here can be used to infer how
to use other motors and drivers which are not mentioned in this 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 −
1 × LM298 driving IC
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.
Arduino Code
/* Stepper Motor Control */
#include <Stepper.h>
void setup() {
myStepper.setSpeed(5);
Serial.begin(9600);
void loop() {
myStepper.step(stepsPerRevolution);
delay(500);
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.
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.
Components Required
You will need the following components −
1 × 8-ohm speaker
1 × 1k 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 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.
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
Arduino Code
#include "pitches.h"
int melody[] = {
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4
};
void setup() {
delay(noteDuration +30);
void loop() {
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.
Size − 30 * 14 * 7mm
Dimensions − 19 * 19mm
Operating mode − AM
1 × Rf link transmitter
1 × 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.
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.
#include <VirtualWire.h>
char *controller;
void setup() {
pinMode(13,OUTPUT);
vw_set_ptt_inverted(true);
vw_set_tx_pin(12);
void loop() {
controller="1" ;
digitalWrite(13,1);
delay(2000);
controller="0" ;
digitalWrite(13,0);
delay(2000);
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.
#include <VirtualWire.h>
void setup() {
pinMode(5, OUTPUT);
void loop() {
uint8_t buf[VW_MAX_MESSAGE_LEN];
if(buf[0]=='1') {
digitalWrite(5,1);
if(buf[0]=='0') {
digitalWrite(5,0);
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.
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 −
1 × Arduino Uno
1 × 5V relay
1 × Rectifier diode
1 × LED
For this project, you just need the usual Arduino IDE, the Adafruit’s
CC3000 library, and the CC3000 MDNS library. We are also going to use
the aREST library to send commands to the relay via WiFi.
Procedure
Follow the circuit diagram and make the connections as shown in the
image given below.
The hardware configuration for this project is very easy.
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.
After placing the relay on the breadboard, you can start identifying the two
important parts on your relay: the coil part which commands the relay,
and the switch part where we will attach the LED.
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 relay’s switch.
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.
Testing Individual Components
You can test the relay with the following sketch −
void setup() {
Serial.begin(9600);
pinMode(relay_pin,OUTPUT);
void loop() {
// Activate relay
digitalWrite(relay_pin, HIGH);
delay(1000);
// Deactivate relay
digitalWrite(relay_pin, LOW);
delay(1000);
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.
#include <SPI.h>
#include <CC3000_MDNS.h>
#include <Ethernet.h>
#include <aREST.h>
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).
// WLAN_SEC_WPA or WLAN_SEC_WPA2
#define LISTEN_PORT 80
We can then create the CC3000 instance, server and aREST instance −
// Server instance
In the setup() part of the sketch, we can now connect the CC3000 chip to
the network −
cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY);
How will the computer know where to send the data? One way would be
to run the sketch once, then get the IP address of the CC3000 board, and
modify the server code again. However, we can do better, and that is
where the CC3000 MDNS library comes into play. We will assign a fixed
name to our CC3000 board with this library, so we can write down this
name directly into the server code.
if (!mdns.begin("arduino", cc3000)) {
while(1);
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.
192.168.1.103/digital/8/1
Let us first see the HTML file, called interface.html. The first part consists
importing all the required libraries for the interface −
<head>
href =
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
src = "https://code.jquery.com/jquery-2.1.4.min.js"></script>
src = "https://cdn.rawgit.com/Foliotek/AjaxQ/master/ajaxq.js"></script>
src =
"https://cdn.rawgit.com/marcoschwartz/aREST.js/master/aREST.js"></script>
src = "script.js"></script>
</head>
Then, we define two buttons inside the interface, one to turn the relay on,
and the other to turn it off again.
<h1>Relay Control</h1>
</div>
</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
// 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 −
Try to click a button on the web interface; it should change the state of
the relay nearly instantly.