Arduino For Beginners - A Step by Step Ultimate Guide To Learn Arduino Programming PDF
Arduino For Beginners - A Step by Step Ultimate Guide To Learn Arduino Programming PDF
◆ ◆ ◆
Board types
Different types of Arduino cards are available, depending on the different
microcontrollers used. However, all Arduino boards have one thing in
common: they are programmed via the Arduino IDD.
Variations depend on the number of inputs and outputs (number of
sensors, LEDs, buttons that you can use on one panel), speed, operating
voltage, form factor, etc. Some motherboards are designed to be embedded
and do not have a programming interface (hardware) that you must
purchase separately. Some can work directly on a 3.7-volt battery, while
others need at least 5 volts.
list of the various Arduino boards available.
Power USB
Arduino board can be powered using the USB cable from your
computer. All you have to do is connect the USB cable to the USB
connection (1).
Power (Barrel Jack)
You can reset your Arduino board, i.e. start your program from the
beginning. You can reset the UN board in two ways. First use the reset
button (17) on the board. Secondly, you can connect an external reset
button to the Arduino pin with the RESET label (5).
Pins (3.3, 5, GND, Vin)
The Arduino UNO board has six analog input pins A0 to A5. These
pins can read the signal from an analog sensor such as 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 take
it as the brain of your board. The main IC (integrated circuit) on the
Arduino differs slightly from board to board. The microcontrollers are
usually from the ATMEL Company. You need to know which IC your
board has before you load a new program from the Arduino IDE. This
information is at the top of the IC. For more information about the IC
construction and functions, you can consult the data sheet.
ICSP pin
Installation
After learning the most important parts of the Arduino UNO board, we
are ready to learn how to set up the Arduino IDE. As soon as we learn
this, we are ready to download our software on the Arduino board.
In this section we learn in simple steps how to set up Arduino IDE on our
computer and set up the board to receive the software via a USB cable.
Step 1 - First you must have your Arduino board ( choose your favorite
board) and a USB cable. If you use Arduino UNO, Arduino Duemilanove,
Nano, Arduino Mega 2560 or Diecimila, you need a standard USB cable
(one plug to B plug), as you can connect in the image below.
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.
Void setup ( ) {
}
PURPOSE - The setup () function is called when the sketch
starts. Use it to initialize the variables, pin modes, use libraries,
etc. The setup function will only run once, after each start-up or
reset of the Arduino board.
INPUT
OUTPUT
RETURN
Void Loop ( ) {
}
PURPOSE − After creating a function setup (), which
initializes and sets the initial values, the function loop () does
exactly what the name suggests, and follows it repeatedly so
that your program can be changed and responded. Use it to
actively control the Arduino board.
INPUT
OUTPUT
RETURN
Data Types
Data types in C refer to an extensive system that is used to declare
variables or functions of various types. The type of a variable determines
how much space it takes in the storage and how the stored bit pattern is
interpreted.
The following table contains all data types that you will use during
programming with Arduino.
void Boolean
char Unsigned byte int Unsigned word
char int
long Unsigned short float double array String- String-
long char array object
void
The invalid keyword is only used in job statements. It indicates that the
function is not expected to return information to the function from which
it was called.
Example
Void Loop ( ) {
// rest of the code
}
Boolean
A Boolean has one of two values, true or false. Each Boolean variable
takes up one byte of memory.
Example
boolean val = false ; // declaration of variable with Boolean type and
initialize with false
boolean state = true ; // declaration of variable with boolean type and
initialize with tru e
Char
A data type that takes up one byte of memory and stores a character
value. Fonts of characters are written between single quotes as follows:
"A" and for multiple characters, double quotes use characters: "ABC."
However, characters are stored as numbers. You can see the specific
encoding in the ASCII chart . This means that it is possible to perform
arithmetic operations on characters, using the ASCII value of the
character. For example, "A" + 1 has the value 66 because the ASCII value
of the capital 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
Intergers are the primary data type for number storage. int stores a 16-bit
(2 bytes) 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 plate to plate. On the Arduino Due, for example,
an int stores a 32-bit (4 bytes) value. This yields range from
-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 an int in the way they
store a value of 2 bytes. Instead of storing negative numbers, however,
they only store positive values, yielding a useful range from 0 to 65,535 (2
^ 16) - 1). This 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 store 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 the number storage, and it
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
Long unsigned variables are variables with extended size for number
storage and store 32 bits (4 bytes). Unlike standard longs, unsigned longs
do not store negative numbers, so they 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 (based on ATMega and
ARM), a short stores a 16-bit (2-byte) value. This yields the range from
-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
The data type for the floating-point number is a number with a decimal
point. Floating-point numbers are often used to approximate the analog
and continuous values because they have a higher resolution than integers.
Floating-point numbers can be large as 3.4028235E + 38 and low as
-3.4028235E + 38. They are stored as 32 bits (4 bytes) of information .
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, the double precision
floating point number occupies four bytes. That is, the dual
implementation is exactly the same as the float, with no gain in precision.
On the Arduino Due, doubles have an accuracy of 8 bytes (64 bit).
Example
double num = 45.352 ;// declaration of variable with type double and
initialize it with 45.352
Variables & Constants
Before we start explaining the variable types, a very important topic that
we must take care of, you fully understand that the variable range is
mentioned.
What is a variable range?
Variables in the programming language C, which Arduino uses, have the
scope property. A scope is a region of the program and there are three
places where variables can be specified. They are -
• Within a function or a block, called local variables .
• When defining function parameters, which are called formal
parameters.
• Outside of all functions, which is called global variables.
Local variables
Variables declared within a function or block are local variables. They can
only be used by the instructions contained in that function or code block. It
is not known that local variables function outside of their own. The
following is an example using local variables -
Void setup () {
}
Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}
Global variables
Global variables are defined outside of all functions, usually at the top of
the program. The global variables retain their value during the lifetime of
your program.
A global variable is accessible for every function. That is, a global
variable is available for use throughout your entire program after its
explanation.
The following example uses global and local variables −
Int T , S ;
float c = 0 ; Global variable declaration
Void setup () {
}
Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}
Operators
A factor is a code that tells the interpreter to perform specific mathematical
or logical functions. C is rich in embedded operators and offers the
following types of factors –
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arithmetic Operators
Assume A variable holds 10 and B variable holds 20 then
Operator Operator Description Example
name simple
assignment = Stores the value to the right A=B
operator of the equal sign in the
variable to the left of the
equal sign.
addition + Adds two operands A + B will
give 30
subtraction - Subtracts second operand A - B will
from the first give -10
multiplication * Multiply both the operands A * B will
give 200
division / Divide numerator by B / A will
denominator give 2
modulo % Modulus Operator and B%A
remainder of after an integer will give 0
division
Example
void loop () {
int a = 9,b = 4,c;
c = a + b;
c = a - b;
c = a * b;
c = a / b;
c = a % b;
}
Output
a + b = 13
a-b=5
a * b = 36
a/b=2
Remainder when a divided by b = 1
Comparison Operators
Assume A variable holds 10 and B variable holds 20 then −
Operator Operator Description Example
name simple
equal to == Checks whether the value of two (A == B)
operands is the same or not, if so, is not true
the condition becomes true.
not equal != Checks whether the value of two (A != B)
to operands is equal or not, if values is true
are not equal, the condition
becomes true.
less than < Checks whether the value of the left (A < B)
operand is smaller than the right is true
operand if so, the condition
becomes true.
greater > Checks whether the value of the left (A > B)
than operand is greater than the right is not true
operand if so, the condition
becomes true.
less than <= Checks whether the value of the left (A <= B)
or equal operand is less than or equal to the is true
to value of the right operand if so, the
condition is true.
greater >= Checks whether the value of the left (A >= B)
than or operand is greater than or equal to is not true
equal to the value of the right operand if so,
the condition becomes true.
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;
}
Output
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 Operator Description Example
name simple
and && Called logical AND operator. If (A &&
both operands are not zero, the B) is true
condition becomes true.
or || Logically called OR operator. If (A || B) is
one of the two operands is not true
zero, the condition becomes
true.
not ! Logically NOT called operator. !(A &&
Use to invert the logical status B) is
of the operand. If a condition is false
true, the Logical operator does
NOT make false.
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;
if( !(a == b)&& (b < a))
c = true;
else
c = false;
}
Output
c = true
c = true
c = tru e
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Operator Operator Description Example
name simple
and & Binary AND Operator copies (A & B) will
a bit to the result if it occurs give 12
in both operands. which is
0000 1100
or | Binary OR Operator copies a (A | B) will
bit if it occurs in both give 61
operands which is
0011 1101
xor ^ Binary XOR Operator copies (A ^ B) will
the bit if it is set in one give 49
operand, but not in both. which is
0011 0001
not ~ Binary One's Complement (~A ) will
Operator is unary and has the give -60
impact of 'flipping' bits. which is
1100 0011
shift left << Binary left shift operator. A << 2 will
The value of the left give 240
operands is moved to the left which is
by the number of bits 1111 0000
specified by the right
operand.
shift right >> Binary Right Shift operator. A >> 2 will
The value of the left give 15
operands is moved to the which is
right by the number of bits 0000 111 1
specified by the right
operand.
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 ;
}
Output
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 Description Example
simple
increment ++ Increase operator increases A++ will
whole value by one give 11
decrement -- Decrease operator A-- will
decreases the entire value give 9
by one
compound += Add AND operator. It adds B += A is
addition the right operand to left equivalent
operand and assigns the to B = B+
result to the left operand A
compound -= Subtract operator for AND. B -= A is
subtraction It subtracts right operand equivalent
from left operand and to B = B -
assigns the result to left A
operand
compound *= Multiply AND allocation B*= A is
multiplication operator. It multiplies the equivalent
right operand with left to B = B*
operand and assigns the A
result to left operand
compound /= Divide AND order B /= A is
division operator. It shares the left equivalent
operand with the right to B = B /
operand and assigns the A
result to the left operand
compound %= Modulus AND allocation B %= A is
modulo operator. It takes modulus equivalent
using two operands and it to B = B
assigns the result to left %A
operand
compound |= bitwise inclusive OR and A |= 2 is
bitwise or assignment operator same as A
=A|2
compound &= Bitwise AND assignment A &= 2 is
bitwise and operator same as A
=A&2
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;
}
Output
a = 11
a=9
b = 30
b = 10
b = 200
b=2
a=0
a=0
a = 30
Control Statements
For decision-making structures, the programmer must specify one or more
conditions that must be evaluated or tested by the software. It must be
executed with one or more instructions to execute if the condition is
specified as true, and optionally other instructions to execute if the
condition is specified are false.
The following is the general form of the typical decision-making structure
found in most programming languages:
Control statements are the elements in source code that control the flow of
program execution. They are -
If statement
It takes the expression in the parentheses and an statement or block of the
statements. If the expression is true, the instruction or the block of
instructions is executed, otherwise, these instructions are skipped.-
Different type forms of if statement
Form 1
if (expression)
statement;
You can also use if statement without braces { } if you have one
statement.
Form 2
if (expression) {
Block of statements;
}
if Statement – Execution Sequence
Example
/* Global variable definition */
int A = 5 ;
int B = 9 ;
Void setup () {
}
Void loop () {
/* check the boolean condition */
if (A > B) /* if condition is true then execute the following statement*/
A++;
/* check the boolean condition */
If ( ( A < B ) && ( B != 0 )) /* if condition is true then execute the
following statement*/ {
A += B;
B--;
}
}
If …else statement
An if statement followed by the optional else statement, that is dead once
the expression is false.
Syntax
if (expression) {
Block of statements;
}
else {
Block of statements;
}
if…else Statement – Execution Sequence
Example
/* Global variable definition */
int A = 5 ;
int B = 9 ;
Void setup () {
}
Void loop () {
/* check the boolean condition */
if (A > B) /* if condition is true then execute the following statement*/
{
A++;
}else {
B -= A;
}
}
If…else if …else statement
The if statement followed by the optional else if ... else statement, that
was terribly helpful for testing numerous conditions using with single if ...
else if statement.
When exploitation if ... else if ... else statements, confine mind -
• An if can have zero or one else statement and must follow another if.
• An if can have zero to many other if statements and these must come
before the else.
• Once an else if succeeds, none of the remaining if or else statements
will be tested.
Syntax
if (expression_1) {
Block of statements;
}
else if(expression_2) {
Block of statements;
}
.
.
.
else {
Block of statements; }
For loop
A for loop executes a predetermined number of times instructions. The
control expression for the loop is initialized, tested, and completely
manipulated within the formalities. It is easy to debug the loop behaviour
of the structure because it is independent of the activity in the loop.
Each for loop has a maximum of three expressions that determine how it
works. The following example shows general for loop syntax. Note that
the three expressions in parentheses of the for loop argument are separated
by semicolons.
Syntax
for ( initialize; control; increment or decrement) {
// statement block
}
Example
for(counter = 2;counter <= 9;counter++) {
//statements block will executed 10 times
}
for loop Execution Sequence
Nested loop
With C you can use one loop in another loop. The following example
illustrates the concept.
Syntax
for ( initialize ;control; increment or decrement) {
// statement block
for ( initialize ;control; increment or decrement) {
// statement block
}
}
Example
for(counter = 0;counter <= 9;counter++) {
//statements block will executed 10 times
for(i = 0;i <= 99;i++) {
//statements block will executed 100 times
}
}
Infinite loop
It is the loop that has no terminating condition, so the loop becomes
infinite.
Syntax
Using for loop
for (;;) {
// statement block
}
Using while loop
while(1) {
// statement block
}
Using do…while loop
do {
Block of statements;
}
while(1);
Functions
Functions make it possible to structure the programs in code segments to
perform individual tasks. The typical case for creating a function is when
one has to perform the same action multiple times in a program .
Standardizing code fragments in functions has several advantages -
• Functions help the programmer to stay organized. This often helps to
conceptualize the program.
• Functions encode one action in one place so that the function only
needs to be considered once and errors are solved.
• This also reduces the chance of errors when changing if the code
needs to be changed.
• Functions make the whole sketch smaller and more compact because
sections of code are often reused.
• They make it easier to reuse code in other programs by making it
modular, and the use of functions often makes the code more readable.
There are two required functions in an Arduino sketch or a program, for
example, setup () and loop (). Other functions should be created outside
the brackets of these two functions.
The most common syntax to define function is -
Function Declaration
A function is declared outside of all other functions, above or below the
loop function.
We can explain the function in two different ways :
The first way is simply to write the part of the function that is called a
function prototype above the loop function, which consists of -
• Function return type
• Function name
• Function argument type, it is not necessary to write the argument
name
Functional prototype must be followed by a semicolon (;).
The following example shows the demonstration of the function
declaration using first method.
Example
int sum_func (int x, int y) // function declaration {
int z = 0;
z = x+y ;
return z; // return the value
}
void setup () {
Statements // group of statements
}
Void loop () {
int result = 0 ;
result = Sum_func (5,6) ; // function call
}
The second part, which is called the function definition or declaration,
must be indicated under the loop function, which consists of -
• Function return type
• Function name
• Type of function argument, here you must add the name of the
argument
• The main text (instructions within the function that are executed
when the function is called)
The following example shows the function statement with the second
method .
Example
int sum_func (int , int ) ; // function prototype
void setup () {
Statements // group of statements
}
Void loop () {
int result = 0 ;
result = Sum_func (5,6) ; // function call
}
int sum_func (int x, int y) // function declaration {
int z = 0;
z = x+y ;
return z; // return the value
}
The second method just to declares the function above the loop function.
Strings
Strings are used to store text. They can be used to display text on an LCD
screen or in the Arduino IDE Serial Monitor window. Strings are also
useful for saving user input. For example, the characters that a user types
on a keyboard that is connected to the Arduino.
There are 2 types of strings in Arduino programming -
• Arrays of characters that are the same as the strings used in C
programming.
• The Arduino String, with which we can use a string object in a
sketch.
In this chapter we learn strings, objects and the use of strings in Arduino
sketches. At the end of the chapter you will learn what type of string to
use in a sketch.
String Character Array s
The first type of string that we will learn is the string that is a string of
char type characters. In the previous chapter, we learned what an array is;
a consecutive sequence of the same type of variable stored in the memory.
A string is a series of char variables.
A string is a special array that has one extra element at the end of the
string, which always has the value 0 (zero). This is known as a "null-
terminated string".
Example
This will show how to make a string and print it to the serial monitor
window.
void setup() {
char my_str[6]; // an array big enough for a 5 character string
Serial.begin(9600);
my_str[0] = 'H'; // the string consists of 5 characters
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // 6th array element is a null terminator
Serial.println(my_str);
}
void loop() {
}
The following example shows what a string consists of; a string of
printable characters and 0 as the last element of the string to indicate that
this is where the string ends. The string can be printed to the Arduino IDE
Serial Monitor window with Serial.println () and the name of the string
passed.
The 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 matrix and
also automatically terminates the string with a zero. An array of six
elements long and consisting of five characters followed by a zero is
created in exactly the same way as in the previous sketch.
Manipulating String Arrays
We can alter the string array within a sketch as shown in the following
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] = ' '; // replace the null terminator with a space
like[18] = 't'; // insert the new word
like[19] = 'e';
like[20] = 'a';
like[21] = 0; // terminate the string
Serial.println(like);
}
void loop() {
}
Output
I like coffee and cake
I like coffee
I like coffee and tea
The sketch works in the following way.
Creating and Printing the String
In the sketch above, a new string is created and then printed for display in
the Serial monitor window.
Shorten the string
The string is shortened by replacing the 14th character in the string with a
zero with zero (2). This is element number 13 in the string matrix from 0.
When the character string is printed, all characters are printed to the new
zero that ends with zero. The other characters does not disappear; and
they still exist in memory and the string array is still the same size. The
only difference is that every function that works with strings sees the
string only up to the first zero terminator.
Change a word in the string
Finally, the sketch replaces the word "cake" with "tea" (3). First, the zero
terminator on like [13] must be replaced with a space, so that the string is
restored to the originally created format.
New characters overwrite "cak" from the word "cake" with the word
"thee". This is done by overwriting individual characters. The 'e' of 'cake'
is replaced by a new zero-ending character. The result is that the string is
actually closed with two zero characters, the original 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
zero terminator .
Functions to Manipulate String Arrays
The previous sketch manually manipulated the string by gaining access to
individual characters in the string. To make it easier to manipulate string
arrays, you can write your own functions or use a number of string
functions from the C language library.
Given below is the list Functions to Manipulate String Arrays
The next sketch uses some C string functions.
Example
void setup() {
char str[] = "This is my string"; // create a string
char out_str[40]; // output from string functions placed here
int num; // general purpose integer
Serial.begin(9600);
// (1) print the string
Serial.println(str);
// (2) get the length of the string (excludes null terminator)
num = strlen(str);
Serial.print("String length is: ");
Serial.println(num);
// (3) get the length of the array (includes null terminator)
num = sizeof(str); // sizeof() is not a C string function
Serial.print("Size of the array: ");
Serial.println(num);
// (4) copy a string
strcpy(out_str, str);
Serial.println(out_str);
// (5) add a string to the end of a string (append)
strcat(out_str, " sketch.");
Serial.println(out_str) ;
num = strlen(out_str);
Serial.print("String length is: ");
Serial.println(num);
num = sizeof(out_str);
Serial.print("Size of the array out_str[]: ");
Serial.println(num);
}
void loop() {
}
Output
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
The sketch works in the following way.
Print the String
The newly created string is printed to the Serial monitor window as in
earlier sketches.
Get the length of the string
The strlen () function is used to get the length of the string. The length of
the string is only for the printable characters and does not include the zero
terminator.
The string contains the17 characters, so we see that17 printed in the Serial
monitor window .
Get the length of the array
The sizeof () operator is used to get the length of the array that contains
the string. The length includes the zero terminator, so the length is one
more than the length of the string.
sizeof () looks like a function, but is technically an operator. It was not a
part of the C-string library, but was used in the sketch to show the
difference between the size of the array and the size of the string (or string
length).
The strcpy () function copy the str [] string to the out_num [] array. The
strcpy () function copies the second string that is passed to it to the first
string. The 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 is found after the string in memory.
The string has been copied to the array so that we have some extra space
in the array to use in the next part of the sketch, which adds a string to the
end of a string.
Add a string to a string (concatenated)
The sketch connects one string with the other, which is known as
concatenation. This is done using the strcat () function. The strcat ()
function places the second string that is passed to it at the end of the first
string that is passed to it.
After concatenation, the length of the string is printed to display the new
string length. The length of the sequence is then printed to indicate that
we have a sequence of 25 characters in a sequence of 40 elements.
Remember that the long 25-character string actually takes 26 characters
from the array because of the zero that is zero.
Array Bounds
When working with strings and arrays it is very important to work within
the limits of strings or arrays. In the example sketch, an array is created
with a length of 40 characters to allocate the memory that can be used to
manipulate strings .
If the array was made too small and we tried to copy a string that was
larger than the array, the string would be copied over the end of the array.
The memory beyond the end of the array may contain other important data
that is used in the sketch and which is then overwritten by our string. If the
memory is exceeded beyond the end of the string, the sketch may crash or
cause unexpected behaviour.
String Object
The 2nd type of string used in Arduino programming is the String Object.
What is an Object?
An object is a construction that contains both data and functions. A String
object can be created just like a variable and a value or string can be
assigned. The String object contains functions (called "methods" in object-
oriented programming (OOP)) that work on the string data in the String
object.
The following sketch and explanation will clarify what an object is and
how the String object is used.
Example
void setup() {
String my_str = "This is my string.";
Serial.begin(9600);
// (1) print the string
Serial.println(my_str);
// (2) change the string to upper-case
my_str.toUpperCase();
Serial.println(my_str);
// (3) overwrite the string
my_str = "My new string.";
Serial.println(my_str);
// (4) replace a word in the strin g
my_str.replace("string", "Arduino sketch");
Serial.println(my_str);
// (5) get the length of the string
Serial.print("String length is: ");
Serial.println(my_str.length());
}
void loop() {
}
Output
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 is given a value (or string) at the top of the
sketch.
String my_str = "This is my string." ;
This creates a String object named my_str and gives it the value "This is
my string."
This can be compared to creating a variable and assigning a value such as
an integer –
int my_var = 102;
The sketch works in the following way.
Printing the String
The string can be printed to the Serial monitor window, just like a string
with strings.
Convert the string to uppercas e
The string object my_str that has been created has a number of functions
or methods that can be operated on it. These methods are invoked using
the object name followed by the point operator (.) And then the name of
the function to be used.
my_str.toUpperCase ();
The toUpperCase () function works on the string in the my_str object of
the String type and converts the string data (or text) that the object
contains to uppercase. A list of functions that contain String class can be
found in the Arduino String reference. String is called a class and is used
to create String objects.
Override a string
The mapping operator is used to assign a new string to the my_str object
that replaces the old string
my_str = "My new string." ;
The mapping operator cannot be used on string strings, but only works on
String objects.
Replace a word in the string
The remove () function is used to replace the first string that was passed to
it with the second string that was passed to it. replace () is another function
that is built into the String class and therefore available for use on the
my_str String object.
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
This prototype also have been written in the following way for
documentation purposes.
void modifyArray( int anyArrayName[], int anyVariableName ) ;
Output
Effects of passing entire array by reference:01234
The values of the modified array are:01234
Effects of passing array element by value:
a[3] before modifyElement: 3
a[3] after modifyElement: 3
$ is not a hexadecimal digit
f is a hexadecimal digit
2. Multi-Dimensional Arrays
Two-dimension arrays (i.e., subscripts) often represent value tables that
consist of information arranged in rows and columns.
Below are the most important features of multidimensional arrays -
• To identify a specific table element, we must specify two subscripts.
• By convention, the first identifies the row of the element and the
second the column of the element.
• Arrays that require two subscripts to identify a specific element are
called two-dimensional arrays or 2D arrays.
• Arrays with two or more dimensions are known as multidimensional
arrays and can have more than two dimensions.
The following image illustrates a two-dimensional array, a. The array
contains three rows and four columns, so it is a 3-by-4 array. In common,
an array with m rows and n columns is called an m-by-n array .
int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } };
Example
Here is an example of initializing two-dimensional arrays in statements.
• Lines a - c indicate three arrays, each with two rows and three
columns.
• • The declaration of array1 (line a) offers six initializers in the two
sublists. The first sublist initializes row 0 of the array with the values
1, 2 and 3; the second sublist initializes row 1 of the array with the
values 4, 5 and 6.
• If the braces around each sublist are removed from the initialization
list of array1, the compiler initializes the elements of row 0 followed
by the elements of row 1, yielding the same result.
• The declaration of array2 (line b) offers only five initializers.
• The initializers are assigned to row 0 and then to row 1. All elements
that have no explicit initialization are initialized to zero, so array2 [1]
[2] is initialized to zero.
• The declaration of array3 (line c) offers three initializers in two
sublists.
• The sublist for row 0 explicitly initializes the first two elements of
rows 0 to 1 and 2; the third element is implicitly initialized to zero.
• The sublist for row 1 explicitly initializes the first element to 4 and
implicitly initializes the last two elements to zero.
• The program calls the printArray function to execute the elements of
each array. Note that the function prototype (line k) specifies the const
int a [] [columns] parameter.
• When a function receives a one-dimensional array as an argument, the
array brackets are empty in the function's parameter list.
• The size of the first dimension of a two-dimensional array (i.e., the
number of rows) is also not required, but all subsequent dimension
sizes are required. The compiler uses these formats to determine the
locations in the memory of elements in multidimensional arrays.
• All array elements are sequentially stored in memory, regardless of
the number of dimensions. In a 2-D 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 )
Serial.print (a[ i ][ j ] );
Serial.print (“\r” ) ; // start new line of output
}
// end outer for
}
// end function printArray
Output
Values in array1 by row are:
123
456
Values in array2 by row are:
123
450
Values in array3 by row are:
120
400
Note :
Each row is a one-dimensional array. To find an element in a particular
row, the function must know exactly how many elements are in each row
so that it can skip the correct number of memory locations when accessing
the array. So when opening a [1] [2], the function manages to skip the
three elements of row 0 in memory to go to row 1. The function then gets
access to element 2 of that row. Many common matrix manipulations use
FOR statements .
For Instance, 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 only varies the second subscript (i.e., the column
subscript). The previous FOR statement is the same as the following
assignment instructions –
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 ];
The FOR statement makes the total of the elements of the array row by row. The outer FOR
statement begins by setting the row (i.e., the row subscript) to 0. Therefore, the elements of row 0
can be added by the inner FOR statement.
The outer FOR statement then increases the row to 1, so that the elements of row 1 can be added.
The outer FOR statement then increases row to 2, so that the elements of row 2 can be added. When
the nested FOR statement ends, the total contains the sum of all array elements.
ARDUINO FUNCTION
LIBRARIES
I/O Functions
The pins on the Arduino board can be configured as input or output. We
will explain the operation of the pins in those modes. It is important to
note that most analogue Arduino pins can be configured and used in the
same way as digital pins.
Pins configured as INPUT
Arduino pins are configured as inputs by default, so they do not need to be
explicitly specified as inputs with pinMode () when you use them as
inputs. It is said that pins configured in this way are in a high impedance
state. Input pins make extremely low demands on the circuit that they
sample, equivalent to a series resistance of 100 megaohms for the pin.
This means that very little power is needed to switch the input pin from
one state to the other. This makes the pins useful for tasks such as
implementing a capacitive touch sensor or reading an LED as a photo
diode.
Pins which configured as pinMode (pin, INPUT) without anything
connected to them, or with wires connected to them and not connected to
other circuits, report seemingly random changes in pin state, pick up
electrical noise from the environment on or capacitively linking the state
of a pin nearby.
Pull-up resistors
Pick-up resistors are often useful to send an input pin to a known state if
no input is present. This can be done by adding a pull-up resistor (up to +
5V) or a pull-down resistor (resistor to ground) at the input. The 10K
resistor is a good value for a pull-up or pull-down resistor.
Using Built-in Pull-up Resistor with Pins Configured as Input
There are 20,000 pull-up resistors built into the Atmega chip that are
accessible via software. These built-in pull-up resistors are accessible by
setting the pinMode () as INPUT_PULLUP. This effectively reverses the
behavior of the INPUT mode, where HIGH means that the sensor is OFF
and LOW means that the sensor is ON. The value of pull-up depends on
the microcontroller used. On most AVR-based cards, the value is
guaranteed between 20 kΩ and 50 kΩ. On the Arduino Due, this is
between 50 kΩ and 150 kΩ. Consult the microcontroller datasheet on
your board for the exact value.
When a sensor is connected to a pin configured with INPUT_PULLUP,
the other end must be connected to the ground. In the case of a simple
switch, this causes the pin to indicate HIGH when the switch is open and
LOW when the switch is pressed. The pull-up resistors provide sufficient
current to illuminate an LED that is poorly connected to a pin that is
configured as an input. If LEDs seem to work in a project, but are very
vague, this is probably what is going on.
The same registers (internal chip memory locations) that determine
whether a pin is HIGH or LOW, control the pull-up resistors.
Consequently, a pin configured to have pull-up resistors enabled when the
pin is in INPUT mode, the pin will be configured as HIGH if the pin is
subsequently switched to an OUTPUT mode with pinMode (). This also
works in the other direction and on an output pin that is left in a HIGH
state, the pull-up resistor is set when it is switched to 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
pin − the number of the pin whose mode you wish to set
mode − INPUT, OUTPUT, or INPUT_PULLUP.
Example
int button = 5 ; // button connected to pin 5
int LED = 6; // LED connected to pin 6
void setup () {
pinMode(button , INPUT_PULLUP);
// set the digital pin as input with pull-up resistor
pinMode(button , OUTPUT); // set the digital pin as output
}
void setup () {
If (digitalRead(button ) == LOW) // if button pressed {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
}
digitalWrite() Function
The digitalWrite () function is used to write a HIGH or LOW value to a
digital pin. If the pin was configured as the OUTPUT with pinMode (),
then the voltage is set to corresponding value: 5V (or 3.3V on 3.3V cards)
for HIGH, 0V (ground) for LOW. If the pin is configured as an INPUT,
digitalWrite () turns the internal pullup on the input pin on (HIGH) or off
(LOW). It is suggested to set the pinMode () to INPUT_PULLUP to
enable the internal pull-up resistor.
If you do not set pinMode () to OUTPUT and connect an LED to a pin
when you call digitalWrite (HIGH), the LED may appear dim. Without
any explicitly setting digitalWrite () ,pinMode () will have enabled the
internal pull-up resistor, which works as a large current-limiting resistor.
digitalWrite() Function Syntax
Void loop() {
digitalWrite (pin ,value);
}
pin − the number of the pin whose mode you wish to set
value − HIGH, or LOW.
Example
int LED = 6; // LED connected to pin 6
void setup () {
pinMode(LED, OUTPUT); // set the digital pin as output
}
void setup () {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
analogRead( ) function
Arduino can detect if there is voltage on one of its pins and report this via
the digitalRead () function. There is a difference between an on / off sensor
(which detects the presence of an object) and an analog sensor, the value
of which changes continuously. To be able to read this type of sensor, we
need a different type of pin.
At the bottom right of the Arduino board, you will see six pins marked
"Analog In". These special pins not only tell you if there is voltage on
them but also what their value is. By using analogRead () function, we can
read the voltage applied to one of the pins.
This function returns a number between 0 and 1023, which stands for
voltages between 0 and 5 volts. For example, if a voltage of 2.5 V is
applied to pin number 0, analogRead (0) returns 512.
analogRead() function Syntax
analogRead(pin);
pin − the number of 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); // read the input pin
Serial.println(val); // debug value
}
Advanced I/O Function
In this topic, we will learn some advanced Input and Output Functions.
analogReference() Function
Configures the reference voltage used for the analog input (i.e., the value
used as the top of the input range). The options are -
• DEFAULT - The standard analog reference of 5 volts (on Arduino
cards of 5 V) or 3.3 volts (on Arduino boards of 3.3 V)
• INTERNAL - A built-in reference, equivalent to 1.1 volts on the
ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not
available on the Arduino Mega)
• INTERNAL1V1 - (Arduino Mega only) A built-in 1.1V reference
• INTERNAL2V56 - (Arduino Mega only) A built-in 2.56V reference
• EXTERNAL - The voltage on the AREF pin (only 0 to 5V) is used
as a reference
analogReference() Function Syntax
analogReference (type);
type - use any type of the follow (DEFAULT, INTERNAL,
INTERNAL1V1, INTERNAL2V56, EXTERNAL)
Use nothing less than 0V or more than 5V for external reference voltage
on the AREF pin. If you use an external reference on the AREF pin, you
must set the analog reference to EXTERNAL before calling the
analogRead () function. Otherwise, short the active reference voltage
(internally generated) and the AREF pin, possibly damaging the
microcontroller on your Arduino board.
Instead of, you can connect the external reference voltage to AREF pin
via a 5K resistor, so that you can switch between external and internal
reference voltages.
Note that the resistor will change the voltage used as a reference because
there is an internal 32K resistor on the AREF pin. The two-act as a
voltage divider. For example, 2.5 V applied through the resistor yields 2.5
* 32 / (32 + 5) = ~ 2.2 V on 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
analogReference(EXTERNAL); // the voltage applied to the AREF pin (0 to 5V only)
// is used as the reference.
}
void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
Character Functions
All data is entered into computers as characters, including letters,
numbers and various special symbols. In this section, we discuss the
possibilities of C ++ for investigating and manipulating individual
characters.
The character processing library contains various functions that perform
useful tests and manipulations of character data. Each function is given a
character, represented as an int, or EDF as an argument. Characters are
often manipulated as integers.
Remid that EOF normally has value –1 and that some hardware
architectures does not allow negative values to be stored in the char
variables. However, the character handling functions manipulate
characters as integers .
The following table provides an overview of the library's functions for
processing characters. When using functions from the character
processing library, include the <cctype> heading.
Examples
The following example shows the use of the isdigit, isalpha, isalnum and
isxdigit functions. The iscipher function determines whether the
argument is a number (0–9). The isalpha function determines whether the
argument is uppercase (A-Z) or lowercase (a - z). The isalnum function
determines whether the argument is uppercase, lowercase or a number.
The isxdigit function determines whether the argument is a hexadecimal
digit (A - F, a - f, 0–9).
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" );
Serial.print (" digit or a letter\r" );
Serial.print (isalnum( '8' ) ?"8 is a" : "8 is not a" ) ;
Serial.print (" digit or a letter\r");
Serial.print (isalnum( '#' ) ?"# is a" : "# is not a" );
Serial.print (" digit or a letter\r");
Serial.print ("\rAccording to isxdigit:\r");
Serial.print (isxdigit( 'F' ) ?"F is a" : "F is not a" );
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( 'J' ) ?"J is a" : "J is not a" ) ;
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( '7' ) ?"7 is a" : "7 is not a" ) ;
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( '$' ) ? "$ is a" : "$ is not a" );
Serial.print (" hexadecimal digit\r" );
Serial.print (isxdigit( 'f' ) ? “f is a" : "f is not a");
}
void loop () {
}
Output
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
$ is not a hexadecimal digit
f is a hexadecimal digit
We use the conditional operator (? :) with each function to determine
whether the string is "one" or the string is "none" to be printed in the
output for each tested character. For example, line a indicates that if '8' is a
digit, i.e. if isdigit returns a true (non-zero) value, the string '8 is a' is
printed. If "8" is not a digit (i.e., if is-digit returns 0), the string "8 is not" is
printed.
Example 2
The following example shows the use of the islower and isupper functions.
The islower function determines whether the argument is lowercase (a - z).
The isupper function determines whether the 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 ( islower( 'P') ? "P is a" : "P is not a") ;
Serial.print ("lowercase letter\r");
Serial.print (islower( '5' ) ? "5 is a" : "5 is not a" );
Serial.print ( " lowercase letter\r" );
Serial.print ( islower( '!' )? "! is a" : "! is not a") ;
Serial.print ("lowercase letter\r");
Serial.print ("\rAccording to isupper:\r") ;
Serial.print (isupper ( 'D' ) ? "D is a" : "D is not an" );
Serial.print ( " uppercase letter\r" );
Serial.print ( isupper ( 'd' )? "d is a" : "d is not an") ;
Serial.print ( " uppercase letter\r" );
Serial.print (isupper ( '8' ) ? "8 is a" : "8 is not an" );
Serial.print ( " uppercase letter\r" );
Serial.print ( islower( '$' )? "$ is a" : "$ is not an") ;
Serial.print ("uppercase letter\r ");
}
void setup () {
}
Output
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 lette r
Example 3
The following example shows the use of the isspace, iscntrl, ispunct,
isprint, and isgraph functions.
• The isspace function determines whether the argument is a white space
character, such as space (''), form input ('\ f'), newline ('\ n'), carriage
return ('\ r'), horizontal tab ('\ t') ) or vertical tab ("\ v").
• The iscntrl function determines whether the argument is a checkmark,
such as horizontal tab ('\ t'), vertical tab ('\ v'), form feed ('\ f'), alert
('\ a'), backspace (' \ b '), carriage return (' \ r ') or newline (' \
n ').
• The ispunct function determines whether the argument is a print
character other than a space, number, or letter, such as $, #, (,), [,], {,},;
:: or%.
• The isprint function determines whether the argument is a character
that can be displayed on the screen (including the space character).
• The isgraph test function for the same characters as isprint, but the
space character is not included.
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" );
Serial.print ( " \rAccording to iscntrl:\rNewline") ;
Serial.print ( iscntrl( '\n' )?"is a" : " is not a" ) ;
Serial.print (" control character\r");
Serial.print (iscntrl( '$' ) ? " $ is a" : " $ is not a" );
Serial.print (" control character\r");
Serial.print ("\rAccording to ispunct:\r");
Serial.print (ispunct(';' ) ?"; is a" : "; is not a" ) ;
Serial.print (" punctuation character\r");
Serial.print (ispunct('Y' ) ?"Y is a" : "Y is not a" ) ;
Serial.print ("punctuation character\r") ;
Serial.print (ispunct('#' ) ?"# is a" : "# is not a" ) ;
Serial.print ("punctuation character\r");
Serial.print ( "\r According to isprint:\r");
Serial.print (isprint('$' ) ?"$ is a" : "$ is not a" );
Serial.print (" printing character\rAlert ");
Serial.print (isprint('\a' ) ?" is a" : " is not a" );
Serial.print (" printing character\rSpace ");
Serial.print (isprint(' ' ) ?" is a" : " is not a" );
Serial.print (" printing character\r");
Serial.print ("\r According to isgraph:\r");
Serial.print (isgraph ('Q' ) ?"Q is a" : "Q is not a" );
Serial.print ("printing character other than a space\rSpace ");
Serial.print (isgraph (' ') ?" is a" : " is not a" );
Serial.print ("printing character other than a space ");
}
void loop () {
}
Output
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 characte r
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
Math Library
The Arduino Math library (math.h) contains the number of useful
mathematical functions for manipulating floating-point numbers.
Library macros
Here are the macros defined in math.h - header
Below is the list of macros defined in the math heading. H
Library functions
The following functions are defined in the heading mathematics. H -
Below is the list of functions defined in the heading mathematics. H
Example
The following example shows how to use the most common math 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
Serial.print("absolute value of num = ");
Serial.println (fabs (double__x) ); // absolute value of a float
Serial.print("floating point modulo = ");
Serial.println (fmod (double__x, double__y)); // floating point modulo
Serial.print("sine of num = ");
Serial.println (sin (double__x) ) ;// returns sine of x
Serial.print("square root of num : ") ;
Serial.println ( sqrt (double__x) );// returns square root of x
Serial.print("tangent of num : ");
Serial.println ( tan (double__x) ); // returns tangent of x
Serial.print("exponential value of num : ");
Serial.println ( exp (double__x) ); // function returns the exponential
value of x.
Serial.print("cos num : ");
Serial.println (atan (double__x) ); // arc tangent of x
Serial.print("tangent of num : ");
Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x
Serial.print("arc tangent of num : ");
Serial.println (log (double__x) ) ; // natural logarithm of x
Serial.print("cos num : ");
Serial.println ( log10 (double__x)); // logarithm of x to base 10.
Serial.print("logarithm of num to base 10 : ");
Serial.println (pow (double__x, double__y) );// x to power of y
Serial.print("power of num : ");
Serial.println (square (double__x)); // square of x
}
void loop() {
}
Output
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
Trigonometric Functions
You must use Trigonometry in a practical way such as calculating the
distance for a moving object or angular velocity. Arduino offers traditional
trigonometric functions (sin, cos, tan, asin, acos, atan) that can be
summarized by writing their prototypes. Math.h contains the prototype of
the trigonometry function.
Syntax
double sin(double x); //returns sine of x radians
double cos(double y); //returns cosine of y radians
double tan(double x); //returns the tangent of x radians
double acos(double x); //returns A, the angle corresponding to cos (A) = x
double asin(double x); //returns A, the angle corresponding to sin (A) = x
double atan(double x); //returns A, the angle corresponding to tan (A) = x
Example
double sine = sin(2); // approximately 0.90929737091
double cosine = cos(2); // approximately -0.41614685058
double tangent = tan(2); // approximately -2.18503975868
ARDUINO ADVANCED
Due & Zero
The Arduino Due is a microcontroller card based on the Atmel SAM3X8E
ARM Cortex-M3 CPU. It was the first Arduino board based on a 32-bit
ARM core microcontroller.
Important features -
• It has 54 digital output/input pins (12 of which can be used as PWM
outputs)
• 12 analog inputs
• 4 UARTs (serial hardware ports)
• 84 MHz clock, a USB OTG compatible connection
• 2 DAC (digital to analog), 2 TWI, a power connection, an SPI
header, a JTAG header
• Reset button and an erase button
Communication
2 I2C
1 Interface JTAG (10 pin)
1 CAN Interface (Automotive communication protocol)
1 SPI1 USB Host (like as Leonardo)
4 Hardware UARTs
1 Programming Port
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 Atmel’s SAMD21 MCU, which
features a 32-bit ARM Cortex® M0+ core.
One of its most important features is Atmel’s 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.
analogWrite() Function
The analogWrite () function writes an analog value (PWM wave) to a pin.
It can be used to light an LED with different brightness or to drive a motor
at different speeds. After a call to the analogWrite () function, the pin
generates a constant square wave of the specified task cycle until the next
call to digitalRead () or a call to analogWrite () or digitalWrite () on the
same pin. The frequency of PWM signal on most pins is approximately
490 Hz. Pins 5 and 6 on the Uno and similar cards have a frequency of
approximately 980 Hz. Pins 3 and 11 on the Leonardo also work at 980
Hz.
On most Arduino cards (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 pin 9, 10 and 11.
Bytes
A byte consists of eight bits.
• If a bit is a number, it is logical that bytes represent numbers.
• All mathematical operations can be performed on it.
• The numbers in a byte do not have the same meaning either.
• The leftmost bit has the largest value called the most significant bit
(MSB).
• The rightmost bit has least value and is therefore called as the least
significant bit (LSB).
• Since 8 zeros and ones of 1 byte can be combined in 256 different
ways, the largest decimal number that can be represented by 1 byte is
255 (one combination represents a zero).
interrupts
Interruptions stop the current work of Arduino so that other work can be
done.
Suppose you are chatting with someone at home. Suddenly the telephone
rings. You stop chatting and pick up the phone to talk to the caller. When
you have finished your phone call, return to chat with the person before the
phone rang.
In the same way, you can see the main routine as chatting with someone,
the phone rings and you stop chatting. The interrupt routine is the
telephone process. When the phone call ends, go back to your main
routine. This example explains exactly how an interrupt makes a processor
work.
The main program is active and performs a function in a circuit. However,
if an interruption occurs, the main program will stop while another routine
is running. When this routine is complete, the processor returns to the main
routine.
Important features
Here are some important features about interruptions -
• Interruptions can come from different sources. In this case we use a
hardware interrupt that is triggered by a status change on one of the
digital pins.
• Most Arduino designs have two hardware interrupts (referred to as
"interrupt0" and "interrupt1"), wired to digital I / O pins 2 and 3,
respectively.
• The Arduino Mega has six hardware interrupts including the
additional interrupts ("interrupt2" to "interrupt5") on pins 21, 20, 19
and 18.
• You can define a routine using the special function called "ISR"
(Interrupt Service Routine).
• You can define the routine and specify conditions for the rising edge,
falling edge, or both. The interruption would be maintained under these
specific circumstances.
• It is possible to have this function performed automatically whenever
an event occurs on an input pen .
Types of interruptions
There are two types of interruptions -
• Hardware interrupts - They act in response to an external event, such
as an external interrupt pin that becomes high or low.
• Software interrupts - They act in response to an instruction sent in
software. The only interrupt type that supports the "Arduino language"
is the attachInterrupt () function.
Arduino I2C
We have 2 modes - master code and slave code - to connect 2 Arduino
boards using I2C. They are
Master Transmitter / Slave Receiver
Master Receiver / Slave Transmitter
Example
#include <Wire.h> //include wire library
void setup() //this will run only once {
Wire.begin(); // join i2c bus as master
}
short age = 0;
void loop() {
Wire.beginTransmission(2);
// transmit to device #2
Wire.write("age is = ");
Wire.write(age); // sends one byte
Wire.endTransmission(); // stop transmitting
delay(1000);
}
Slave Receiver
The following functions are used -
• Wire.begin (address) - Address is the Seven-bit slave address.
• Wire.onReceive (data handler received) - Function to be recalled
when a slave device receives data from the master.
• Wire.available () - Returns the number of available bytes for
retrieving with Wire.read (). This must be invoked in the
Wire.onReceive () handler.
Example
#include <Wire.h> //include wire library
void setup() { //this will run only once
Wire.begin(2); // join i2c bus with address #2
Wire.onReceive(receiveEvent); // call receiveEvent when the master
send any thing
Serial.begin(9600); // start serial for output to print what we receive
}
void loop() {
delay(250);
}
//-----this function will execute whenever data is received from master-----
//
void receiveEvent(int howMany) {
while (Wire.available()>1) // loop through all but the last {
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
}
Master Receiver / Slave Transmitter
Now let's see what the master receiver and slave transmitter is.
Main receiver
The master is programmed to request and then reads bytes of data 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 the slave device. The bytes can then be retrieved with
the wire.available () and wire.read () functions.
Example
#include <Wire.h> //include wire library void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(2, 1); // request 1 bytes from slave device # 2
while (Wire.available()) // slave may send less than requested {
char c = Wire.read(); // receive a byte as character
Serial.print(c); // print the character
}
delay(500);
}
Slave Transmitter
The following function is used.
Wire.onRequest(handler) − A function is called when the master
requests data from this slave device.
Example
#include <Wire.h>
void setup() {
Wire.begin(2); // join i2c bus with address #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); // respond with message of 1 bytes as expected by master
x++;
}
Serial Peripheral Interface
A Serial Peripheral Interface (SPI) bus is a serial communication system
that uses up to four conductors, usually three. One conductor is used for
data reception, one for data transmission, one for synchronization and one
alternative for selecting a device to communicate with. It is a full-duplex
connection, which means that the data is sent and received at the same
time. The maximum baud rate is higher than in the I2C system
communication.
Board SPI pins
SPI uses the following four wires -
• SCK - This is the serial clock that is controlled by the master.
• MOSI - This is the master output/slave input powered by the master.
• MISO - This is the master input/slave output powered by the master.
• SS - This is the slave selection thread.
• The following functions are used. You must have the SPI.h.
• Start SPI () - Initializes the SPI bus by setting SCK, MOSI, and SS to
outputs, pulling SCK and MOSI low and SS high.
• SPI.setClockDivider (divider) - To set SPI clock divider relative to
the system clock. AVR-based boards have available distributors 2, 4,
8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which
sets the SPI clock to a quarter of the frequency of the system clock (5
Mhz for the boards at 20 MHz).
• Divider - This can be (SPI_CLOCK_DIV2, SPI_CLOCK_DIV4,
SPI_CLOCK_DIV8, SPI_CLOCK_DIV16, SPI_CLOCK_DIV32,
SPI_CLOCK_DIV64, SPI_CLOCK_DIV128).
• SPI transfer (fall) - SPI transfer is based on the simultaneous
transmission and receipt: the received data is returned in ReceiveVal.
• SPI.beginTransaction (SPISettings (speedMaximum, dataOrder,
dataMode)) - speedMaximum is the clock, dataOrder (MSBFIRST or
LSBFIRST), dataMode (SPI_MODE0, SPI_MODE2, SPI_MODE2 or
SPI_MODE3) .
Note - Look carefully at the polarity of an LED. The shorter of the two
legs, in the direction of the flat edge of the lamp, indicates the negative
pole.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open the new sketch File by
clicking New.
Arduino Code
/*
Blin k
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); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(2, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Code to Note
pinMode (2, OUTPUT) - Before you can use one of the pins from
Arduino, you must tell Arduino Uno R3 whether it is an INPUT or
OUTPUT. We use a built-in "function" called pinMode () for this.
digitalWrite (2, HIGH) - If you use a pin as OUTPUT, you can use it as
HIGH (output 5 volts) or LOW (output 0 volts).
Output
You should see your LED on and off. If the required output is not seen,
make sure that you have correctly assembled the circuit and verified the
code and uploaded it to your board.
Fading LED
This example demonstrates the use of the analogWrite () function to fade
out an LED. AnalogWrite uses pulse width modulation (PWM), with
which a digital pin is switched on and off very quickly with different ratios
between on and off, to create a blur effect .
Required components
You need the following components -
• 1 × bread board
• 1 × Arduino Uno R3
• 1 × LED
• 1 × 330Ω resistor
• 2 × jumper
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Note - Look carefully at the polarity of an LED. The shorter of the two
legs, in the direction of the flat edge of the lamp, indicates the negative
pole.
Sketch
Open the Arduino IDE software on your computer. Encoding 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.
*/
int led = 9; // the PWM pin the LED is attached to
int brightness = 0; // how bright the LED i s
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(300);
}
Code to Note
After you have declared pin 9 as your LED pin, you do not need to do
anything in the setup () function of your code. The analogWrite () function
that you are going to use in the main loop of your code requires two
arguments: one indicates the function to which pin is to be written and the
other indicates which PWM value is to be written.
To fade the LED on and off, gradually increase the PWM values from 0
(all off) to 255 (all on) and then back to 0 to complete the cycle. In the
above sketch, the PWM value is set using a variable called brightness.
Each time through the loop, it is incremented by the value of the
fadeAmount variable .
If the brightness is extremely high (0 or 255), fadeAmount becomes
negative. In other words, if fadeAmount is 5, it is set to -5. If it is -5, it is
set to 5. The next time the loop changes, this change causes the brightness
to change direction.
analogWrite () can change the PWM value very quickly, so the delay at the
end of the sketch determines the speed of the fade. Try to change the value
of the delay and see how it changes the fading effect.
Output
You should see your LED brightness change gradually.
Read analog voltage
This example shows how you can read an analog input on analog pin 0.
This input is convert from analogRead () to the voltage and written on
serial monitor of the Arduino Software system(IDE).
Required components
You need the following components -
• 1 × breadboard
• 1 × Arduino Uno R3
• 1 × 5K variable resistance (potentiometer)
• 2 × jumper
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Potentiometer
A potentiometer (or pot) is a simple electromechanical transducer. It
converts rotary or linear movement of the input operator into a resistance
change. This change is (or can be) used to control everything from the
volume of a hi-fi system to the direction of a huge container ship.
The pot as we know it was originally known as a rheostat (essentially a
variable wire resistance). The variety of pots available is now quite
astonishing and it can be (especially) very difficult for the beginner to
determine which type is suitable for a certain task. A few different pot
types, all of which can be used for the same task, make the job more
difficult.
The image on the left side 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. Encoding in the
Arduino language will control your circuit. Open a new sketch File by
clicking New.
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.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0
- 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
Code to notice
In the program or sketch below, the first thing you do in the setup function
is to start serial communication, 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 must set a variable to store the
resistance value (which will be between 0 and 1023, perfect for an int data
type) from your potentiometer -
int sensorValue = analogRead (A0);
If you want to change the values from 0-1023 to a range that matches the
voltage, read the pin, you must create another variable, perform a float and
perform a small calculation. To scale the numbers between 0.0 and 5.0,
divide 5.0 by 1023.0 and multiply that with sensorValue -
float voltage = sensor value * (5.0 / 1023.0);
Finally, you must print this information to your series window. You can do
this with the command Serial.println () in your last code line -
Serial.println (voltage)
Now open Serial monitor in the Arduino IDE by clicking on the icon on
the right of the top green bar or pressing Ctrl + Shift + M.
Output
You will see the steady stream of numbers ranging from 0.0 - 5.0. As you
turn the pot, the values change according to the voltage on pin A0 .
LED bar chart
This example shows how to read an analog input on analog pin 0, convert
the values of analogRead () to voltage and print it to the serial monitor of
the Arduino Software (IDE).
Required components
You need the following components -
• 1 × bread board
• 1 × Arduino Uno R3
• 1 × 5k ohm variable resistor (potentiometer)
• 2 × jumper
• 8 × LED or you can use (LED bar chart display as shown in the
image below)
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch File by
clicking New.
10 Segment LED Bar Graph
These bar chart LEDs with 10 segments have many applications. With a
compact footprint, easy connection, they are easy for prototype or finished
products. In essence, they are 10 separate blue LEDs together, each with
an individual anode and cathode connection.
They are also available in yellow, red and green colors.
Note - The pin-out in these bar charts may differ from what is on the data
sheet. By turning the device 180 degrees, the change is corrected, making
pin 11 the first pin in the row.
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; // the pin that the potentiometer is attached to
const int ledCount = 8; // the number of LEDs in the bar graph
int ledPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; // an array of pin numbers to which
LEDs are attached
void setup() {
// loop over the pin array and set them all to output:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
pinMode(ledPins[thisLed], OUTPUT);
}
}
void loop() {
// read the potentiometer:
int sensorReading = analogRead(analogPin);
// map the result to a range from 0 to the number of LEDs :
int ledLevel = map(sensorReading, 0, 1023, 0, ledCount);
// loop over the LED array:
for (int thisLed = 0; thisLed < ledCount; thisLed++) {
// if the array element's index is less than ledLevel,
// turn the pin for this element on:
if (thisLed < ledLevel) {
digitalWrite(ledPins[thisLed], HIGH);
}else { // turn off all pins higher than the ledLevel:
digitalWrite(ledPins[thisLed], LOW);
}
}
}
Code to notice
The sketch works as follows: first, you read the entry. You assign the input
value to the output range, in this case, ten LEDs. You then set a for loop to
repeat the outputs. If the number of the output in the series is lower than
the assigned input range, enable it. If this is not the case, switch it off.
Output
You will see that the LED goes ON one by one as the value of the analog
measurement increases and goes OFF one by one as the value decreases.
Log out the keyboard
In this example, the keyboard library is used to log you out of your user
session on your computer when pin 2 on the ARDUINO UNO is pulled to
the ground. The sketch simulates the keystroke in order of two or three
keys simultaneously and releases them after a short delay.
Warning - When you use the Keyboard. print () command, Arduino takes
over the keyboard from your computer. To ensure that you do not lose
control of your computer while performing a sketch with this feature, you
must set up a reliable control system before calling Keyboard.print (). This
sketch is designed to only send a keyboard command after a pen has been
pulled to the ground .
Required components
You need the following components -
• 1 × breadboard
• 1 × Arduino Leonardo, Due board or Micro
• 1 × push button
• 1 × jumper
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
You must use Arduino IDE 1.6.7 for this example
Note - You must include the keyboard library in your Arduino file library.
Copy and paste the keyboard library file into the file with the name
libraries (highlighted) as shown in the following screenshot.
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);
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:
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);
}
Code to notice
Before you upload the program to your board, you must ensure that you
assign the correct operating system that you are currently using to the
platform variable.
While the sketch is in progress, pin 2 is connected to the button and the
board sends the logout procedure to the PC connected via USB.
Output
When you connect pin 2 to the ground, a logout operation is performed.
It uses the following keyboard combinations to log out -
• On Windows , CTRL-ALT-DEL followed by ALT-l
• On Ubuntu, CTRL-ALT-DEL, and ENTER
• On OSX , CMD-SHIFT-q
Keyboard message
For instance, when the button is pressed, a text string is sent to the
computer as a keyboard input. The string indicates how often the button
was pressed. After you have programmed and wired the Leonardo, open
your favorite text editor to view the results.
Warning - When you use the Keyboard. print () command, the Arduino
takes over the keyboard from your computer. To ensure that you do not
lose control of your computer while performing a sketch with this feature,
you must set up a reliable control system before calling Keyboard.print ().
This sketch contains a push button to switch the keyboard so that it only
works after the button is pressed.
Required components
You need the following components -
• 1 × breadboard
• 1 × Arduino Leonardo, Due board or Micr o
• 1 × temporary push button
• 1 × 10k ohm resistor
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Encoding 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; // input pin for pushbutton
int previousButtonState = HIGH; // for checking the state of a pushButton
int counter = 0; // button push counter
void setup() {
pinMode(buttonPin, INPUT); // make the pushButton pin an input:
Keyboard.begin(); // initialize control over the keyboard:
}
void loop() {
int buttonState = digitalRead(buttonPin); // read the pushbutton:
if ((buttonState != previousButtonState)&& (buttonState == HIGH)) //
and it's currently pressed: {
// 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 notice
Attach a push-button connection to pin 4 on Arduino. Attach the other pin
to 5V. Use the resistor as a pull-down, a reference to the earth, by
attaching it to the earth from pin 4 .
After you have programmed your board, disconnect the USB cable, open a
text editor and place the text cursor in the typing area. Reconnect the board
to your computer via USB and press the button to register the document.
Output
By using a text editor, the text sent via Arduino is displayed.
Mouse button operation
With the help of the mouse library, you can control the cursor on the
screen of a computer with an Arduino Leonardo, Micro or Due.
This specific example uses five pushbuttons to move the cursor on the
screen. Four of the buttons are directional (Left, right, up, down) and one
is for a left mouse click. The cursor movement from Arduino is always
relative. Each time an entry is read, the position of the cursor is updated
relative to the current position.
Each time one of the direction buttons is pressed, Arduino moves the
mouse and assigns a HIGH input to a range of 5 in the right direction.
The 5th button is for controlling a left mouse button with the mouse. When
the button is released, the computer recognizes the event.
Required components
You need the following components -
• 1 × breadboard
• 1 × Arduino Leonardo, Due board or micro
• 5 × 10k ohm resistor
• 5 × temporary push buttons
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
You must use Arduino IDE 1.6.7 for this example
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: 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"
// set pin numbers for the five buttons:
const int upButton = 2;
const int downButton = 3;
const int leftButton = 4;
const int rightButton = 5;
const int mouseButton = 6;
int range = 5; // output range of X or Y movement; affects movement
speed
int responseDelay = 10; // response delay of the mouse, in ms
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);
// calculate the movement distance based on the button states:
int xDistance = (leftState - rightState) * range;
int yDistance = (upState - downState) * range ;
// if X or Y is non-zero, move:
if ((xDistance != 0) || (yDistance != 0)) {
Mouse.move(xDistance, yDistance, 0);
}
// if the mouse button is pressed:
if (clickState == HIGH) {
// if the mouse is not pressed, press it:
if (!Mouse.isPressed(MOUSE_LEFT)) {
Mouse.press(MOUSE_LEFT);
}
} else { // else the mouse button is not pressed:
// if the mouse is pressed, release it:
if (Mouse.isPressed(MOUSE_LEFT)) {
Mouse.release(MOUSE_LEFT);
}
}
// a delay so the mouse does not move too fast:
delay(responseDelay);
}
Code to notice
Connect your board with your computer with a micro USB cable. The
buttons are connected to digital inputs from pin 2 to 6. Make sure you use
10k pull-down resistors.
ARDUINO SENSORS
Keyboard Serial
This example listens to a byte coming from the serial port. Upon receipt,
the board sends a keystroke back to the computer. The keystroke sent is
one higher than what was received, so if you send an "a" from the serial
monitor, you will receive an "b" from the board connected to the
computer. A "1" returns a "2" and so on.
Warning - When you use the Keyboard. print () command, the Leonardo,
Micro or Due board takes over the keyboard from your computer. To
ensure that you do not lose control of your computer while performing a
sketch with this feature, you must set up a reliable control system before
calling Keyboard.print (). This sketch is designed to send a keyboard
command only after the board has received a byte through the serial port.
Required components
You need the following components -
• 1 × Arduino Leonardo, Due board or Micro
Procedure
Simply connect your board to the computer using a USB cable.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch File by
clicking New.
Notes - You must include the keyboard library in your Arduino library
file. Copy and paste the keyboard library file into the file named 'libraries'
marked with a yellow color.
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 notice
After programming, open your serial monitor and send a byte. The board
will respond with a keystroke, which is one digit higher.
Output
The board will respond with a keystroke one digit higher on the Arduino
IDE serial monitor when you send a byte.
Humidity sensor
In this section, we learn how we can connect our Arduino board with
different sensors. We will discuss the following sensors -
• Humidity sensor (DHT22)
• Temperature sensor (LM35)
• Water detector sensor (Simple Water Trigger)
• PIR SENSOR
• ULTRASONIC SENSOR
• GPS
Humidity sensor (DHT22)
The DHT-22 (also called AM2302) is a digital output, relative humidity,
and temperature sensor. It uses a capacitive humidity sensor and a
thermistor to measure the ambient air and sends a digital signal to the data
pin .
In this Instance, you will learn how to use this sensor with Arduino UNO.
The room temperature and humidity are printed on the serial monitor.
The DHT-22 Sensor
The connections are simple. The first pin on the 3-5V power, the second
pin on the data input pin and the rightmost pin on the ground.
Technical details
• Power - 3-5V
• Max current - 2.5 mA
• Humidity - 0-100%, 2-5% accuracy
• Temperature - 40 to 80 ° C, ± 0.5 ° C accuracy
Required components
You need the following components -
• 1 × bread board
• 1 × Arduino Uno R3
• 1 × DHT22
• 1 × 10K ohm resistor
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Encoding 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 // what digital pin we're connected to
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect
pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter
to
// 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.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHTxx test!");
dht.begin();
}
void loop() {
delay(2000); // Wait a few seconds between measurements
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;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print ("Humidity: ");
Serial.print (h);
Serial.print (" %\t");
Serial.print ("Temperature: ");
Serial.print (t);
Serial.print (" *C ");
Serial.print (f);
Serial.print (" *F\t");
Serial.print ("Heat index: ");
Serial.print (hic);
Serial.print (" *C ");
Serial.print (hif);
Serial.println (" *F");
}
Code to notice
DHT22 sensor has four terminals (Vcc, DATA, NC, GND), which are
connected to the card as follows -
• DATA pin to Arduino pin number 2
• Vcc pin up to 5 volt Arduino board
• GND pin on the floor of the Arduino board
• We must connect a 10 k ohm resistor (tensile resistance) between the
DATA and the Vcc pin
After the hardware connections are completed, you must add the DHT22
library to your Arduino library file as previously described.
Output
You can see the temperature and humidity display on a serial port monitor
that is updated every 2 seconds.
Temperature sensor
The LM35 series temperature sensor is precision integrated temperature
circuits with an output voltage linearly proportional to the Celsius
temperature.
The LM35 device has Benefits over the linear temperature sensors
calibrated in Kelvin because the user does not need to subtract a large
constant voltage from the output to obtain a handy Celsius scale. The
LM35 device does not require external calibration or cropping to provide a
typical accuracy of ± ¼ ° C at room temperature and ± ¾ ° C over a full
temp range from -55 ° C to 150 ° C.
Technical specifications
• Directly calibrated in Celsius (Celsius)
• Linear scale factor + 10 mV / ° C
• 0.5 ° C assured accuracy (at 25 ° C)
• Estimated for the full range of -55 ° C to 150 ° C
• Suitable for external applications
Required components
• You need the following components -
• 1 × bread board
• 1 × Arduino Uno R3
• 1 × LM35 sensor
Procedure
Follow the circuit diagram and connect the components to the breadboard
as shown in the image below.
Sketch
Open the Arduino IDE software on your computer. Encoding 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);
// read analog volt from sensor and save to variable temp
temp = temp * 0.48828125;
// convert the analog volt to its temperature equivalent
Serial.print("TEMPERATURE = ");
Serial.print(temp); // display temperature value
Serial.print("*C");
Serial.println();
delay(1000); // update sensor reading each one second
}
Code to notice
LM35 sensor has 3 terminals - Vs, Vout and GND. We will connect the
sensor as follows -
• Connect the + Vs with + 5v on your Arduino board.
• Connect Vout to Analog0 or A0 on the Arduino board.
• Connect GND with GND on Arduino.
The analog to digital converter (ADC) converts analog values into a digital
approach based on the formula ADC Value = sample * 1024 / reference
voltage (+ 5v). So with a +5 volt reference, the digital approximation will
be the same as the input voltage * 205.
Output
You see the temperature display on the serial port monitor is updated every
second .
Water detector/sensor
Water sensor stone is designed for the detection of water, which can be
used extensively in detecting rainfall, water level, and even liquid leakage.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking 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() {
pinMode(Grove_Water_Sensor, INPUT); // The Water Sensor is an
Input
pinMode(LED, OUTPUT); // The LED is an 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 notice
Water sensor has three connections - S, Vout (+) and GND (-). Connect
the sensor as follows -
• Connect the + Vs with + 5v on your Arduino board.
• Connect S to digital pin number 8 on the Arduino board.
• Connect GND with GND on Arduino.
• Connect LED to digital pin number 9 on the Arduino board.
When the sensor detects water, pin 8 on Arduino turns LOW and the LED
on Arduino turns ON.
Output
You will see the indicator LED go ON when the sensor detects water.
PIR sensor
You can detect movement with PIR sensors. They are used to detect
whether a person has moved within or outside the range of the sensor.
They often occur in devices and gadgets that are used at home or for
companies. They are often called PIR, "passive infrared", "pyroelectric" or
"IR motion sensors".
The following are the benefits of PIR sensors -
• Small in size
• Wide lens range
• Easy to interface
• Cheap
• Low power
• •Easy to use
• Do not wear out
PIRs are made from pyroelectric sensors, a round metal can with a
rectangular crystal in the center that can detect levels of infrared radiation.
Everything radiates from a low level, and the hotter something is, the more
radiation is emitted. The sensor in a motion detector is divided into two
halves. This is to detect the motion change and not to average IR levels.
The two halves are connected so that they cancel each other out. If one
half sees more or less IR radiation than the other, the output swings high or
low.
PIRs have adjustable settings and ahead installed in the 3-pin ground /
output / power pads.
Most of 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 how many people are around or how close they are to the sensor. The
lens is often fixed remotely at a certain distance and they are sometimes
deposited by pets in the house.
Required components
You need the following components -
• 1 × bread board
• 1 × Arduino Uno R3
• 1 × PIR sensor (MQ3)
Procedure
Follow the circuit diagram and make the connections as shown in the
Figure below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
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) {
if(takeLowTime){
lowIn = millis();takeLowTime = false;
}
if(!lockLow && millis() - lowIn > pause) {
PIRValue = 0;
lockLow = true;
Serial.println("Motion ended.");
delay(50);
}
}
}
Code to notice
PIR sensor has 3 terminals - Vcc, OUT and GND. Connect the sensor as
follows -
• Connect the + Vcc with + 5v on the Arduino board.
• Connect OUT to digital pin 2 on the Arduino board.
• Connect GND with GND on Arduino.
You can adjust the sensor sensitivity and the delay time via two variable
resistors on the bottom of the sensor card.
As soon as the sensor detects a movement, Arduino sends a message
through the serial port to say that a movement has been detected. The PIR
detection movement will delay a certain time to check if there is a new
movement. If no motion is detected, Arduino sends a new message stating
that the motion has ended.
Outpu t
You will see a message on your serial port when a movement is detected
and another message when the movement stops.
Ultrasonic sensor
The HC-SR04 ultrasonic sensor uses SONAR to detect the distance of an
object, just like the bats. It offers excellent contactless range detection with
high accuracy and stable measurements in an easy-to-use package from 2
cm to 400 cm or 1 "to 13 feet.
Operation is not affected by sunlight or black material, although soft
materials such as dust may be acoustically difficult to detect. It is supplied
complete with an ultrasonic transmitter and receiver module.
Technical Specifications
Power Supply − +5V DC
Resolution − 0.3 cm
Quiescent Current − <2mA
Ranging Distance − 2cm – 400 cm/1″ – 13ft
Effectual Angle − <15°
Measuring Angle – 30°
Working Current − 15mA
Components Required
You need the following components are−
1 × Breadboard
1 × ULTRASONIC Sensor (HC-SR04)
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. Encoding 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
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);
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 notice
The ultrasonic sensor has 4 terminals - + 5V, Trigger, Echo and GND
connected as follows -
• Connect the + 5V pin with the + 5v on the Arduino board.
• Connect Trigger to digital pin 7 on the Arduino board.
• Connect Echo to digital pin 6 on the Arduino board.
• Connect GND with GND on Arduino.
In our program, we have shown the distance measured by the sensor in
inches and cm via the serial port.
Output
You can see the distance measured by the sensor in inches and cm on the
Arduino serial monitor.
Connection switch
Pushbuttons or switches connect two open terminals in a circuit. In this
example, the LED on pin 2 is turned on when you press the push button
switch connected to pin 8.
Pull-down resistance
Pull-down resistors area unit employed in the logic circuits to examine that
inputs to Arduino settle at expected logic levels once external devices area
unit disconnected or have a high impedance. Since nothing is connected to
an input pin, this does not mean that it is a logical zero. Tensile resistors
are connected between the ground and the correct pin on the device.
An Instance of the pull-down resistor in a digital circuit is shown in the
following figure. A push-button switch is connected between the power
supply and a microcontroller pin. In such a circuit, when the switch is
closed, the microcontroller input has a logic high value, but when the
switch is open, the downward resistance pulls the input voltage to the
ground (logic zero value), thereby preventing an undefined status at the
import.
The pull-down electrical device should have better resistance than the
ohmic resistance of the logic circuit, or else, it should lower the voltage an
excessive amount of and therefore the input voltage on the pin remains at a
constant logic low value regardless of the switch position.
Required components
The following components -
• 1 × Arduino UNO board
• 1 × LED
• 1 × 4.7K of ohm resistor (pull-down)
• 1 × 330 of ohm resistor
Procedure
Follow the circuit diagram and make the connections as shown in the
figure below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
Arduino Code
// constants won't change. They're used here t o
// set pin numbers:
const int buttonPin = 8; // the number of the pushbutton pin
const int ledPin = 2; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
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);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
Code to notice
When the switch is open (push button is not pressed), there is no
connection between the two terminals of the push button, so the pin is
connected to earth (via the pull-down resistor) and we read a LOW. When
the switch is closed (push button is pressed), it makes a connection
between the two terminals and connects the pin with 5 volts, so that we
read a HIGH.
Output
LED is ON when the push button is pressed and OFF when it is released.
MOTOR CONTROL
DC Motor
In this chapter we will link different types of motors to the Arduino board
(UNO) and show you how to connect the motor and drive it from your
board.
There are three different types of engines -
• DC motor
• Servo motor
• Stepper motor
A DC motor (DC motor) is the most common type of motor. DC motors
normally only have two wires, one positive and one negative. If you
connect these two wires directly to a battery, the motor will run. If you
change the cables, the motor will run in the opposite direction.
Warning - Should drive the motor directly from Arduino board pins. This
can damage the board. Use a control circuit or an IC.
We will divide this chapter into 3 parts -
• Just keep your engine running
• Engine speed control
• Check the direction of rotation of the DC motor
Required components
You need the following components -
• 1x Arduino UNO board
• 1x 1 N4001 diode
• 1x PN2222 transistor
• 1x 270 Ω resistor
• 1x small 6V DC motor
Procedure
Follow the circuit diagram and make the connections as shown in the
Figure below.
Precautionary measures
Take the following precautions when making the connections.
• First check whether the transistor is connected correctly. The flat side
of the transistor must face the Arduino board as shown in the setup.
• Secondly, the striped end of the diode should be in the direction of the
+ 5V power line according to the layout in the figure.
Spin ControlArduino Code
int motorPin = 3;
void setup() {
}
void loop() {
digitalWrite(motorPin, HIGH);
}
Code to Notice
The transistor acts as a switch and controls the current to the motor.
Arduino pin 3 is used to switch the transistor on and off and is named
'motor Pin' in the sketch.
Output
The engine runs at full speed when pin Arduino number 3 becomes high.
Engine speed control
The following is the schematic diagram of a DC motor connected to the
Arduino board.
Arduino Code
int motorPin = 9;
void setup() {
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
while (! Serial);
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 Notice
The transistor acts as a switch and controls the power of the motor.
Arduino pin 3 is used to switch the transistor on and off and is named
'motorPin' in the sketch.
When the program starts, you will be asked to provide the values to control
the speed of the motor. You must enter a value between 0 and 255 in the
serial monitor.
In the 'loop' function, the 'Serial.parseInt' command is used to read the
number entered as text in the serial monitor and convert it to an 'int'. You
can type any number here. The 'if' statement in the following line simply
writes analogously to this number, if the number is between 0 and 255.
Output
The DC motor runs at different speeds according to the value (0 to 250)
received through the serial port.
Spin Direction Control
To control the direction of rotation of the DC motor without changing the
cables, you can use a circuit called an H-bridge . An H-bridge is an
electronic circuit that drives the motor in both directions. H bridges are
used in many different applications. One of the most common applications
is controlling motors in robots. It is called an H bridge because it uses four
transistors that are connected so that the schematic diagram looks like an
"H."
We will use the L298 H-Bridge IC here. The L298 can control the
direction and speed of DC motors and stepper motors and can control two
motors simultaneously. The current power is 2A for each motor. However,
you must use heat sinks with these currents.
Components Required
You need the following components -
• 1 × L298 bridge IC
• 1 × DC motor
• 1 × Arduino UNO
• 1 × bread board
• 10 × auxiliary wires
Procedure
The following is the schematic diagram of the DC motor interface to the
Arduino Uno board.
The diagram below shows how the L298 IC must be connected 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.
Because in this example we only control one motor, 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 requires a
pulse width modulated (PWM) signal to control the motor speed.
The table shows which direction the motor will turn based on the digital
values of IN1 and IN2.
IN1 IN2 Motor Behavior
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 2 digital pins of Arduino control the direction of
the motor. The EN-A pin from IC is connected to the PWM pin 2 from
Arduino. This controls the speed of the engine .
To set up the values of Arduino pins 8 and 9, we have used the
digitalWrite () function and to set the value of pin 2 we should use the
analogWrite () function.
Connection steps
• Connect the 5V and the ground of the IC to 5V and the ground of
Arduino respectively.
• Connect the motor to pins 3 and 2 of the IC.
• Connect the IN1 of IC with pin 8 of Arduino.
• Connect the IN2 of IC to pin 9 of Arduino.
• Connect the EN1 of IC to pin 2 of Arduino.
• Connect the SENS An IC pin to the ground.
• Connect Arduino using the Arduino USB cable and upload the
program to Arduino with Arduino IDE software.
• Supply power to the Arduino board using a power supply, battery or
USB cable.
Arduino Code
const int pwm = 2 ; //initializing pin 2 as pwm
const int in_1 = 8 ;
const int in_2 = 9 ;
//For providing logic to L298 IC to choose the direction of the DC motor
void setup() {
pinMode(pwm,OUTPUT) ; //we have to set PWM pin as output
pinMode(in_1,OUTPUT) ; //Logic pins are also set as 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
highes t
value to driver the motor */
//Clockwise for 3 secs
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
//For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH
digitalWrite(in_1,LOW) ;
digitalWrite(in_2,HIGH) ;
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
}
Output
The motor will run first in the clockwise (CW) direction for 3 seconds
and then counter-clockwise (CCW) for 3 seconds.
Servo Motor
A servomotor is a small device with an shaft output . This axis can be
placed in 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 axis. If the coded signal changes, the angular
position of the axis changes. In practice, servos are used in radio-
controlled aircraft to position control surfaces such as the lifts and rudders.
They are also used in radio-control cars, dolls and robots.
Servos are extremely useful in robotics. The motors are small, have a built-
in control circuit and are extremely powerful for their size. A standard
servo such as the Futaba S-148 has a torque of 42 oz / inch, which is
strong for its size. It also draws power in proportion to the mechanical
load. A lightly charged servo therefore does not consume much energy.
The guts of a servomotor are shown in the following image. You can see
the steering circuit, the engine, a set of gears and the housing. You can
also see the three wires that connect to the outside world. One is for power
(+ 5 volts), earth and the white wire is the control wire.
Components Required
You will need the following components −
1 × Arduino UNO board
1 × Servo Motor
1 × ULN2003 of driving IC
1 × 10 KΩ of Resistor
Procedure
Follow the circuit diagram and make the connections as shown in the
figure given below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
Arduino Code
/* Controlling a servo position using a potentiometer (variable resistor) */
#include <Servo.h>
Servo myservo; // create servo object to control a serv o
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin);
// reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180);
// scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled
value
delay(15);
}
Code to notice
Servomotors have three connection terminals - power supply, ground, and
signal. The power cord is usually red and must be connected to the 5V pin
on the Arduino. The earth wire is usually black or brown and must be
connected to one ULN2003 IC connection (10-16). To protect your
Arduino board from damage, you need a driver IC to do that. Here we used
ULN2003 IC to drive the servo motor. The signal pin is usually yellow or
orange and must be connected to Arduino pin number 9.
Connect the potentiometer
A voltage divider / potential divider are resistors in a series circuit that
scales the output voltage to a certain ratio of the applied input voltage.
Following is the circuit diagram –
Output
By changing the NOP position of the pot, the servo motor changes its
angle.
Stepper Motor
A stepper motor or a stepper motor is a brushless, synchronous motor,
which divides a complete rotation into a number of steps. Unlike a
brushless DC motor, which rotates continuously when a fixed DC voltage
is applied to it, a stepper motor rotates in separate step angles.
The stepper motors are therefore manufactured with steps per revolution of
12, 24, 72, 144, 180 and 200, resulting in step angles of 30, 15, 5, 2.5, 2
and 1.8 degrees per step. The stepper motor can be controlled without or
with feedback.
Imagine an engine on an RC plane. The motor runs very quickly in one
direction or another. You can vary the speed with the amount of force that
is given to the engine, but you cannot tell the propeller to stop at a specific
position.
Now imagine a printer. There are many moving parts in a printer,
including engines. Such a motor acts as the paper feed, rotating rollers that
move the piece of paper while ink is being printed on it. This motor must
be able to move the paper over an exact distance to print the next line of
text or the next line of an image.
Another motor is attached to a threaded rod that moves the print head back
and forth. Again, that threaded rod must be exactly moved to print one
letter after the other. This is where the stepper motors come in handy.
Components Required
You need the following components -
• 1 × Arduino UNO board
• 1 × small bipolar stepper motor as shown in the image below
• 1 × LM298 moving IC
Procedure
Follow the circuit diagram and make the connections as shown in the
figure below.
Sketch
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 notice
This program controls a unipolar or bipolar stepper motor. The motor is
attached to digital pins 8 - 11 from Arduino.
Output
The motor will make a revolution in one direction and then a revolution in
the other direction.
ARDUINO AND SOUND
Tone Library
In this topic, we will use the Arduino Tone Library. It is nothing but an
Arduino library, which produces square wave waves of a certain frequency
(and 50% duty cycle) on each Arduino pin. Optionally, a duration can be
specified, otherwise, the wave continues until the stop () function is called.
The pin can be connected to a speaker or piezo buzzer to play the tones.
Warning - Do not connect the pin directly to an audio input. The voltage
is considerably greater than the standard line-level voltages and can
damage the sound card inputs, etc. You can use the voltage divider to
reduce the voltage.
Required components
You need the following components -
• 1 × 8 ohm speaker
• 1 × 1k resistor
• 1 × Arduino UNO board
Procedure
Follow the circuit diagram and make the connections as shown in the
figure below.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
To create the pitches.h file, click the button just below the serial monitor
icon and choose "New Tab" or use Ctrl + Shift + N.
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
};
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 notice
The code uses an extra file, pitches.h. This file contains all the pitch
values for the typical notes. For example, NOTE_C4 is middle C.
NOTE_FS4 is F-sharp, and so on. This note table was originally written
by the Brett Hagman, whose work was based on the tone () command.
You may find it useful when you want to create musical notes.
Output
You will hear musical notes stored in the pitches. H. the file.
Wireless Communication
The wireless receiver and transmitter modules work at 315 Mhz. This was
easily fit into a breadboard and work well with the microcontrollers to
create simple wireless data connection. With one pair of sender and
receiver, the modules only work in one way with communicating data, but
you would need two pairs (of different frequencies) to act as a
sender/receiver pair.
Note - These modules are random and receive a lot of noise. Both the
sender and the receiver work on common frequencies and have no IDs.
Sketch
Open the Arduino IDE software on your computer. Encoding in the
Arduino language will control your circuit. Open a new sketch file by
clicking New.
Note - You must include keyboard library in the Arduino library file. Copy
and paste the VirtualWire.lib file into the libraries folder as shown in the
screenshot below.
Components Required
You need the following components -
• 1 × Arduino Uno
• 1 × Adafruit CC3000 breakout board
• 1 × 5V relay
• 1 × rectifier diode
• 1 × LED
• 1 × 220 Ohm resistor
• 1 × Breadboard and a few starter wires
For this project, you only need the usual Arduino IDE, the CC3000 library
of the Adafruit and the CC3000 MDNS library. We will also 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
figure below.
The hardware configuration for this project is very easy.
• Connect the IRQ pin of the CC3000 board to pin number 3 of
Arduino board.
• VBAT to pin 5 and CS to pin 10.
• Connect the SPI pins to the Arduino board: MOSI, MISO, and CLK
to pins 11, 12 and 13, respectively.
• Vin is connected to Arduino 5V and GND to the GND.
Now let's connect the relay.
• After you have placed the relay on the breadboard, you can start by
identifying the two important parts on your relay: the coil section that
controls the relay, and the switch section where we will attach the
LED.
• First, connect pin number 8 of the Arduino board to one pin of the
coil.
• Connect the other pin to the earth of the Arduino board.
• You must also place the rectifier diode (anode connected to the
ground pin) over the pins of the coil to protect your circuit when the
relay switches.
• Connect the + 5V of the Arduino board with the common pin of the
relay switch.
• Finally, connect one of the other pins of the switch (usually the pin
that 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
GND of Arduino board.
Test individual components
You can test the relay with the following sketch −
const int relay_pin = 8; // Relay pi n
void setup() {
Serial.begin(9600);
pinMode(relay_pin,OUTPUT);
}
void loop() {
// Activate relay
digitalWrite(relay_pin, HIGH);
// Wait for 1 second
delay(1000);
// Deactivate relay
digitalWrite(relay_pin, LOW);
// Wait for 1 second
delay(1000);
}
Code to notice
The code speaks for itself. You can easily upload it to the board and the
relay switches status every second and the LED will switch ON and OFF
accordingly.
Add WiFi connectivity
Now let's control the relay wirelessly using the CC3000 WiFi chip. The
software for this project is based on the TCP protocol. For this project,
however, the Arduino board will run a small web server, so that we can
"listen" to commands coming from the computer. We will first provide the
Arduino sketch, and then we will see how we can write the server-side
code and create a nice interface.
First the Arduino sketch. The purpose here is to connect to your WiFi
network, create a web server, check for incoming TCP connections, and
then change the status of the relay accordingly.
Important Parts of the Code
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include <CC3000_MDNS.h>
#include <Ethernet.h>
#include <aREST.h >
You need to define the inside code what is specific to your configuration,
i.e. Wi-Fi password and name, and the port for TCP communications
(Here we have used 80).
// WiFi network (change with your settings!)
#define WLAN_SSID "yourNetwork" // cannot be longer than 32
characters!
#define WLAN_PASS "yourPassword"
#define WLAN_SECURITY WLAN_SEC_WPA2 // This can be
WLAN_SEC_UNSEC, WLAN_SEC_WEP,
// WLAN_SEC_WPA or WLAN_SEC_WPA2
// The port to listen for incoming TCP connections
#define LISTEN_PORT 80
We can then create the CC3000 instance, server and aREST instance −
// Server instance
Adafruit_CC3000_Server restServer(LISTEN_PORT); // DNS
responder instance
MDNSResponder mdns; // Create aREST instance
aREST rest = aREST();
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 did computer know where to send the data? One way is to run the
sketch once, then retrieve the IP address from the CC3000 card and change
the server code again. However, we can do great, 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 this name directly in
the server code.
This is done with the following piece of code –
if (!mdns.begin("arduino", cc3000)) {
while(1);
}
We also need to listen for incoming connections .
restServer.begin();
We then code the loop () function of the sketch that is executed
continuously. We must first update the mDNS server.
mdns.update();
The server running on the Arduino board waits for the incoming
connections and handles the requests.
Adafruit_CC3000_ClientRef client = restServer.available();
rest.handle(client);
It is now fairly easy to test the projects via WiFi. Make sure you have
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 find the IP address of your board.
For the rest, let's assume it is something like 192.168.1.103.
Then go to your favorite web browser and type –
192.168.1.103/digital/8/1
You should see that your relay automatically turns ON.
Building the Relay Interface
We will now encrypt the interface of the project. There are two parts here:
an HTML file with the interface and a Javascript file on the client side to
process the clicks on the interface. The interface here is based on the
aREST.js project, which is designed to easily control WiFi devices from
your computer.
First, let's look at the HTML file, interface.html. The first part consists of
importing all required libraries for the interface –
<head>
<meta charset = utf-8 />
<title> Relay Control </title>
<link rel = "stylesheet" type = "text/css "
href =
"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" type = "text/css" href = "style.css">
<script type = "text/javascript"
src = "https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type = "text/javascript"
src = "https://cdn.rawgit.com/Foliotek/AjaxQ/master/ajaxq.js">
</script>
<script type = "text/javascript"
src =
"https://cdn.rawgit.com/marcoschwartz/aREST.js/master/aREST.js">
</script>
<script type = "text/javascript"
src = "script.js"></script>
</head>
Then, we define 2 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 Javascript file on the client side to process the clicks
on the buttons. We will also create a device that we link to the mDNS
name of our Arduino device. If you have changed this in Arduino code,
you must also change it here.
// Create device
var device = new Device("arduino.local");
// Butto n
$('#on').click(function() {
device.digitalWrite(8, 1);
});
$('#off').click(function() {
device.digitalWrite(8, 0);
});
The full code for this project can be found in the GitHub repository. Go to
the interface folder and easily open the HTML file with your favourite
browser. You see something similar in your browser –
Try clicking on a button on the web interface; it should change the status
of the relay almost immediately.
If you managed to make it work, bravo! You have just built a Wi-Fi
controlled light switch. Of course, you can control more than lights with
this project. Make sure your relay supports the power needed for the
device that you want to operate and that you are ready to go .