Arduino Quick Guide123
Arduino Quick Guide123
ARDUINO OVERVIEW
Arduino is a prototype platform open source based on an easy-to-use hardware and software. It consists of a
circuit board, which can be programmed (referred to as a microcontroller) and a ready-made software
called Arduino IDE Integrated Development Environment, which is used to write and upload the
computer code to the physical board.
1.Arduino boards are able to read analog or digital input signals from different sensors and turn it into an output
such as activating a motor, turning LED on/off, connect to the cloud and many other actions.
2.You can control your board functions by sending a set of instructions to the microcontroller on the
board via Arduino IDE.
4. Arduino IDE uses a simplified version of C++, making it easier to learn to program.
5. Arduino provides a standard form factor that breaks the functions of the micro-controller into a more
accessible package.
BOARD TYPES
Various kinds of Arduino boards are available depending on different microcontrollers used. However, all Arduino
boards have one thing in common: they are programmed through the Arduino IDE.
The differences are based on the number of inputs and outputs, the number of sensors, LEDs, and buttons
you can use on a single board , speed, operating voltage etc.
(2)Power Barrel Jack: Arduino boards can be powered directly from the AC mains power supply by connecting
it to the Barrel Jack 2.
(3)Voltage Regulator: The function of the voltage regulator is to control the voltage given to the Arduino board
and stabilize the DC voltages used by the processor and other elements.
(4)Crystal Oscillator: The crystal oscillator helps Arduino in dealing with time issues. How does Arduino
calculate time? The answer is, by using the crystal oscillator. The number printed on top of the Arduino crystal is
16.000H9H. It tells us that the frequency is 16,000,000 Hertz or 16 MHz.
(5,17) Arduino Reset: You can reset your Arduino board, i.e., start your program from the beginning. You can
reset the UNO board in two ways. First, by using the reset button 17 on the board. Second, you can connect an
external reset button to the Arduino pin labelled RESET 5.
(11) Main microcontroller: Each Arduino board has its own microcontroller . It is the brain of your board. The
main IC on the Arduino is different from board to board. The microcontrollers are usually of the ATMEL
Company. You must know what IC your board has before loading up a new program from the Arduino IDE.
(12) ICSP pin: Mostly, ICSP is an AVR, a tiny programming header for the Arduino consisting of MOSI, MISO,
SCK, RESET, VCC, and GND. It is often referred to as an SPI (Serial Peripheral Interface), which could be
considered as an "expansion" of the output. Actually, you are slaving the output device to the master of the SPI
bus.
(13) Power LED indicator: This LED should light up when you plug your Arduino into a power source to indicate
that your board is powered up correctly. If this light does not turn on, then there is something wrong with the
connection.
(14) TX and RX LEDs: On your board, you will find two labels: TX (transmit) and RX (receive). They appear in
two places on the Arduino UNO board. First, at the digital pins 0 and 1, to indicate the pins responsible for serial
communication. Second, the TX and RX led (13). The TX led flashes with different speed while sending the serial
data. The speed of flashing depends on the baud rate used by the board. RX flashes during the receiving process.
(15) Digital I/O: The Arduino UNO board has 14 digital I/O pins (15) (of which 6 provide PWM (Pulse Width
Modulation) output. These pins can be configured to work as input digital pins to read logic values (0 or 1) or as
digital output pins to drive different modules like LEDs, relays, etc. The pins labeled “~” can be used to generate
PWM.
(16) AREF: AREF stands for Analog Reference. It is sometimes, used to set an external reference voltage
(between 0 and 5 Volts) as the upper limit for the analog input pins.
ARDUINO INSTALLATION
In this section, we will learn in easy steps, how to set up the Arduino IDE on our computer and prepare the board
to receive the program via USB cable.
Step 1 − First you must have your Arduino board and a USB cable. In case you use Arduino UNO, you will need
a standard USB cable (A plug to B plug).In case you use Arduino Nano, you will need an A to Mini-B cable.
Step 2 − Download Arduino IDE Software.
You can get different versions of Arduino IDE from the Download page on the Arduino Official website. You
must select your software, which is compatible with your operating system (Windows, IOS, or Linux) and install.
Step 3 − Power up your board.
The Arduino Uno automatically draw power from either, the USB connection to the computer or an external
power supply. Connect the Arduino board to your computer using the USB cable. The green power LED (labeled
PWR) should glow.
Step 4 − Launch Arduino IDE.
Double-click the arduino icon to start the IDE.
Step 5 − Open your first project.
Once the software starts, you have two options −Create a new project and Open an existing project example.
To create a new project, select File → New.
To open an existing project example, select File → Example → Basics → Blink.
Here, we are selecting just one of the examples with the name Blink. It turns the LED on and off with some time
delay. You can select any other example from the list.
Step 6 − Select your Arduino board.
To avoid any error while uploading your program to the board, you must select the correct Arduino board name,
which matches with the board connected to your computer.
Go to Tools → Board and select your board.
Step 7 − Select your serial port.
Select the serial device of the Arduino board. Go to Tools → Serial Portmenu. This is likely to be COM3 or
higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your
Arduino board and re-open the menu, the entry that disappears should be of the Arduino board. Reconnect the
board and select that serial port.
Step 8 − Upload the program to your board.
Before explaining how we can upload our program to the board, we must demonstrate the function of each
symbol appearing in the Arduino IDE toolbar.
Software structure consist of two main functions −Setup( ) function and Loop( ) function.
Void setup ( ) {
}
PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the variables, pin
modes, start using libraries, etc. The setup function will only run once, after each power up or reset of the
Arduino board.
INPUT − -
OUTPUT − -
RETURN − -
Void Loop ( ) {
}
PURPOSE − After creating a setup() function, the loop() function loops consecutively, allowing your
program to change and respond.
INPUT − -
OUTPUT − -
RETURN − -
ARDUINO DATATYPES
Data types in C refers to an extensive system used for declaring variables or functions of different types. The type
of a variable determines how much space it occupies in the storage and how the bit pattern stored is interpreted.
The following table provides all the data types that you will use during Arduino programming.
void Boolean char Unsigned char byte int Unsigned int word
long Unsigned long short float double array String-char array String-object
void
The void keyword is used only in function declarations. It indicates that the function is expected to return no
information to the function from which it was called.
Example
Void Loop ( ) {
// rest of the code
}
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable occupies one byte of memory.
Example
boolean val = false ; // declaration of variable with type boolean and initialize it with false
boolean state = true ; // declaration of variable with type boolean and initialize it with true
Char
A data type that takes up one byte of memory that stores a character value. Character literals are written in single
quotes like this: 'A' and for multiple characters, strings use double quotes: "ABC".
However, characters are stored as numbers. This means that it is possible to do arithmetic operations on
characters, in which the ASCII value of the character is used. For example, 'A' + 1 has the value 66, since the
ASCII value of the capital letter A is 65.
Example
Char chr_a = ‘a’ ;//declaration of variable with type char and initialize it with character a
Char chr_c = 97 ;//declaration of variable with type char and initialize it with character
unsigned char
Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char data type encodes
numbers from 0 to 255.
Example
Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and initialize it with character y
byte
A byte stores an 8-bit unsigned number, from 0 to 255.
Example
byte m = 25 ;//declaration of variable with type byte and initialize it with 25
int
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value. This yields a range of -
32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
The int size varies from board to board.
Example
int counter = 32 ;// declaration of variable with type int and initialize it with 32
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value. Instead of storing
negative numbers, however, they only store positive values, yielding a useful range of 0 to 65,535 (2^16) -
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.
Example
word w = 1000 ;//declaration of variable with type word and initialize it with 1000
Long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to
2,147,483,647.
Example
Long velocity = 102346 ;//declaration of variable with type Long and initialize it with 102346
unsigned long
Unsigned long variables are extended size variables for number storage and store 32 bits (4 bytes). Unlike
standard longs, unsigned longs will not store negative numbers, making their range from 0 to 4,294,967,295
(2^32 - 1).
Example
Unsigned Long velocity = 101006 ;// declaration of variable with
type Unsigned Long and initialize it with 101006
short
A short is a 16-bit data-type. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum
value of (2^15) - 1).
Example
short val = 13 ;//declaration of variable with type short and initialize it with 13
float
Data type for floating-point number is a number that has a decimal point. Floating-point numbers are often used
to approximate the analog and continuous values because they have greater resolution than integers. 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
Double precision floating-point number occupies four bytes. That is, the double implementation is exactly the
same as the float, with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit) precision.
Example
double num = 45.352 ;// declaration of variable with type double and initialize it with 45.
Variables in C programming language have a property called scope. A scope is a region of the program and there
are three places where variables can be declared. They are −
Void setup () {
Void loop () {
int x , y ;
x = 0;
y = 0; actual initialization
z = 10;
Global Variables
Global variables are defined outside of all the functions, usually at the top of the program. The global variables
will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for use throughout your
entire program after its declaration.
Int T , S ;
Void setup () {
Void loop () {
int x , y ;
x = 0;
y = 0; actual initialization
z = 10;
ARDUINO OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. The
different types of operators are
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arithmetic Operators: Assume variable A holds 10 and variable B holds 20 then
Operator name Operator Description Example
simple
A + B will
addition + Adds two operands
give 30
A - B will
subtraction - Subtracts second operand from the first
give -10
A * B will
multiplication * Multiply both operands
give 200
B / A will
division / Divide numerator by denominator
give 2
Binary Ones Complement Operator is unary and (~A ) will give -60
not ~
has the effect of 'flipping' bits. which is 1100 0011
Binary Left Shift Operator. The left operands A << 2 will give
shift left << value is moved left by the number of bits specified 240 which is 1111
by the right operand. 0000
compound A |= 2 is same as
|= bitwise inclusive OR and assignment operator
bitwise or A=A|2
If statement
2 An if statement can be followed by an optional else statement, which executes when the
expression is false.
3 The if statement can be followed by an optional else if...elsestatement, which is very useful to
test various conditions using single if...else if statement.
4 Similar to the if statements, switch...case controls the flow of programs by allowing the
programmers to specify different codes that should be executed in various conditions.
Conditional Operator ? :
5
The conditional operator ? : is the only ternary operator in C.
ARDUINO LOOPS
A loop statement allows us to execute a statement or group of statements multiple times. The general form of a
loop statement is
while loop
1
while loops will loop continuously, and infinitely, until the expression inside the parenthesis,
() becomes false. Something must change the tested variable, or the while loop will never exit.
do…while loop
2 The do…while loop is similar to the while loop. In the while loop, the loop-continuation
condition is tested at the beginning of the loop before performed the body of the loop.
for loop
3 A for loop executes statements a predetermined number of times. The control expression for
the loop is initialized, tested and manipulated entirely within the for loop parentheses.
Nested Loop
4 C language allows you to use one loop inside another loop. The following example illustrates
the concept.
Infinite loop
5
It is the loop having no terminating condition, so the loop becomes infinite.
ARDUINO FUNCTIONS
Functions allow structuring the programs in segments of code to perform individual tasks. The typical case for
creating a function is when one needs to perform the same action multiple times in a program.
advantages
Functions help the programmer stay organized.
Functions codify one action in one place.
This also reduces chances for errors in modification, if the code needs to be changed.
Functions make the whole sketch smaller and more compact.
They make it easier to reuse code in other programs.
There are two required functions in an Arduino program i.e. setup () and loop(). Other functions must be created
outside the brackets of these two functions.
syntax
Function Declaration: A function is declared outside any other functions, above or below the loop function.
We can declare the function in two different ways.
The first way is writing the part of the function called a function prototype above the loop function, which
consists of
int z = 0;
z = x+y ;
void setup () {
Void loop () {
int result = 0 ;
The second part, which is called the function definition or declaration, must be declared below the loop function,
which consists of −
void setup () {
Void loop () {
int result = 0 ;
int z = 0;
z = x+y ;
ARDUINO STRINGS
Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE Serial Monitor
window. Strings are also useful for storing the user input.
There are two types of strings in Arduino programming
Arrays of characters, which are the same as the strings used in C programming.
The Arduino String, which lets us use a string object in a sketch.
String Character Arrays
The first type of string is the string that is a series of characters of the type char. Array is a consecutive series of
the same type of variable stored in memory. A string is an array 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 of 0
(zero). This is known as a "null terminated string".
void setup() {
Serial.begin(9600);
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
Serial.println(my_str);
void loop() {
The following example shows what a string is made up of; a character array with printable characters and 0 as the
last element of the array to show that this is where the string ends. The string can be printed out to the Arduino
IDE Serial Monitor window by using Serial.println() and passing the name of the string.
void setup() {
Serial.begin(9600);
Serial.println(my_str);
void loop() {
In this sketch, the compiler calculates the size of the string array and also automatically null terminates the string
with a zero. An array that is six elements long and consists of five characters followed by a zero is created exactly
the same way as in the previous sketch.
void setup() {
Serial.begin(9600);
Serial.println(like);
// (2) delete part of the string
like[13] = 0;
Serial.println(like);
like[19] = 'e';
like[20] = 'a';
Serial.println(like);
void loop() {
Result
I like coffee and cake
I like coffee
I like coffee and tea
void setup() {
Serial.begin(9600);
Serial.println(str);
num = strlen(str);
Serial.println(num);
Serial.println(num);
strcpy(out_str, str);
Serial.println(out_str);
Serial.println(out_str);
num = strlen(out_str);
Serial.println(num);
num = sizeof(out_str);
Serial.println(num);
void loop() {
Result
This is my string
String length is: 17
Size of the array: 18
This is my string
This is my string sketch.
String length is: 25
Size of the array out_str[]: 40
Copy a String
The strcpy() function is used to copy the str[] string to the out_num[] array. The strcpy() function copies the
second string passed to it into the first string. A copy of the string now exists in the out_num[] array, but only
takes up 18 elements of the array, so we still have 22 free char elements in the array. These free elements are
found after the string in memory.
The string was copied to the array so that we would have some extra space in the array to use in the next part of
the sketch, which is adding a string to the end of a string.
Array Bounds
When working with strings and arrays, it is very important to work within the bounds of strings or arrays. In the
example sketch, an array was created, which was 40 characters long, in order to allocate the memory that could be
used to manipulate strings.
If the array was made too small and we tried to copy a string that is bigger than the array to it, the string would be
copied over the end of the array. The memory beyond the end of the array could contain other important data used
in the sketch, which would then be overwritten by our string. If the memory beyond the end of the string is
overrun, it could crash the sketch or cause unexpected behavior.
void setup() {
Serial.begin(9600);
Serial.println(my_str);
Serial.println(my_str);
Serial.println(my_str);
Serial.println(my_str);
Serial.println(my_str.length());
void loop() {
Result
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22
A string object is created and assigned a value (or string) at the top of the sketch.
String my_str = "This is my string." ;
This creates a String object with the name my_str and gives it a value of "This is my string.".
This can be compared to creating a variable and assigning a value to it such as an integer −
int my_var = 102;
The toUpperCase() function operates on the string contained in the my_strobject which is of type String and
converts the string data (or text) that the object contains to upper-case characters. A list of the functions that the
String class contains can be found in the Arduino String reference. Technically, String is called a class and is used
to create String objects.
Overwrite a String
The assignment operator is used to assign a new string to the my_str object that replaces the old string
my_str = "My new string." ;
The assignment operator cannot be used on character array strings, but works on String objects only.
Replacing a Word in the String
The replace() function is used to replace the first string passed to it by the second string passed to it. replace() is
another function that is built into the String class and so is available to use on the String object my_str.
ARDUINO TIME
Arduino provides four different time manipulation functions. They are −
delay () function
1
The way the delay() function works is pretty simple. It accepts a single integer (or number)
argument. This number represents the time (measured in milliseconds).
delayMicroseconds () function
2 The delayMicroseconds() function accepts a single integer (or number) argument. There are a
thousand microseconds in a millisecond, and a million microseconds in a second.
millis () function
3 This function is used to return the number of milliseconds at the time, the Arduino board
begins running the current program.
micros () function
The micros() function returns the number of microseconds from the time, the Arduino board
4
begins running the current program. This number overflows i.e. goes back to zero after
approximately 70 minutes.
ARDUINO ARRAYS
An array is a consecutive group of memory locations that are of the same type. To refer to a particular location or
element in the array, we specify the name of the array and the position number of the particular element in the
array.
The illustration given below shows an integer array called C that contains 11 elements. You refer to any one of
these elements by giving the array name followed by the particular element’s position number in square brackets
([]). The position number is more formally called a subscript or index (this number specifies the number of
elements from the beginning of the array). The first element has subscript 0 (zero) and is sometimes called the
zeros element.
Thus, the elements of array C are C[0] (pronounced “C sub zero”), C[1], C[2] and so on. The highest subscript in
array C is 10, which is 1 less than the number of elements in the array (11). Array names follow the same
conventions as other variable names.
A subscript must be an integer or integer expression (using any integral type). If a program uses an expression as
a subscript, then the program evaluates the expression to determine the subscript. For example, if we assume that
variable a is equal to 5 and that variable b is equal to 6, then the statement adds 2 to array element C[11].
A subscripted array name is an lvalue, it can be used on the left side of an assignment, just as non-array variable
names can.
Let us examine array C in the given figure, more closely. The name of the entire array is C. Its 11 elements are
referred to as C[0] to C[10]. The value of C[0] is -45, the value of C[1] is 6, the value of C[2] is 0, the value of
C[7] is 62, and the value of C[10] is 78.
To print the sum of the values contained in the first three elements of array C, we would write −
Serial.print (C[ 0 ] + C[ 1 ] + C[ 2 ] );
To divide the value of C[6] by 2 and assign the result to the variable x, we would write −
x = C[ 6 ] / 2;
Declaring Arrays
Arrays occupy space in memory. To specify the type of the elements and the number of elements required by an
array, use a declaration of the form −
type arrayName [ arraySize ] ;
The compiler reserves the appropriate amount of memory. (Recall that a declaration, which reserves memory is
more properly known as a definition). The arraySize must be an integer constant greater than zero. For example,
to tell the compiler to reserve 11 elements for integer array C, use the declaration −
int C[ 12 ]; // C is an array of 12 integers
Arrays can be declared to contain values of any non-reference data type. For example, an array of type string can
be used to store character strings.
void setup () {
void loop () {
Serial.print (i) ;
Serial.print (‘\r’) ;
for ( int j = 0; j < 10; ++j ) // output each array element's value {
Serial.print (n[j]) ;
Serial.print (‘\r’) ;
Result
Element Value
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
// n is an array of 10 integers
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ;
void setup () {
void loop () {
Serial.print (i) ;
Serial.print (‘\r’) ;
for ( int j = 0; j < 10; ++j ) // output each array element's value {
Serial.print (n[j]) ;
Serial.print (‘\r’) ;
Result
Element Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
int a[ arraySize ] = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;
void setup () {
void loop () {
// sum contents of array a
total += a[ i ];
Serial.print(total) ;
Result
Total of array elements: 849
To pass an array argument to a function, specify the name of the array without any brackets.
2 Multi-Dimensional Arrays
Arrays with two dimensions (i.e., subscripts) often represent tables of values consisting of
information arranged in rows and columns.
Pull-up Resistors
Pull-up resistors are often useful to steer an input pin to a known state if no input is present. This can be done by
adding a pull-up resistor (to +5V), or a pull-down resistor (resistor to ground) on the input. A 10K resistor is a
good value for a pull-up or pull-down resistor.
pinMode() Function
The pinMode() function is used to configure a specific pin to behave either as an input or an output. It is possible
to enable the internal pull-up resistors with the mode INPUT_PULLUP. Additionally, the INPUT mode explicitly
disables the internal pull-ups.
Syntax
Void setup () {
pinMode (pin , mode);
}
pin − the number of the pin whose mode you wish to set
mode − INPUT, OUTPUT, or INPUT_PULLUP.
Example
void setup () {
pinMode(button , INPUT_PULLUP);
void setup () {
digitalWrite() Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the pin has been
configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding value: 5V (or 3.3V on
3.3V boards) for HIGH, 0V (ground) for LOW. If the pin is configured as an INPUT, digitalWrite() will enable
(HIGH) or disable (LOW) the internal pullup on the input pin. It is recommended to set the pinMode() to
INPUT_PULLUP to enable the internal pull-up resistor.
If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling digitalWrite(HIGH), the
LED may appear dim. Without explicitly setting pinMode(), digitalWrite() will have enabled the internal pull-up
resistor, which acts like a large current-limiting resistor.
Syntax
Void loop() {
digitalWrite (pin ,value);
}
pin − the number of the pin whose mode you wish to set
value − HIGH, or LOW.
void setup () {
void setup () {
analogRead( ) function
There is a difference between an on/off sensor (which detects the presence of an object) and an analog sensor,
whose value continuously changes. In order to read this type of sensor, we need a different type of pin.
In the lower-right part of the Arduino board, you will see six pins marked “Analog In”. These special pins not
only tell whether there is a voltage applied to them, but also its value. By using the analogRead() function, we
can read the voltage applied to one of the pins.
This function returns a number between 0 and 1023, which represents voltages between 0 and 5 volts. For
example, if there is a voltage of 2.5 V applied to pin number 0, analogRead(0) returns 512.
Syntax
analogRead(pin);
pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini and Nano,
0 to 15 on the Mega)
void setup() {
void loop() {
Syntax
analogReference (type);
type − can use any type of the follow (DEFAULT, INTERNAL, INTERNAL1V1, INTERNAL2V56,
EXTERNAL)
Do not use anything less than 0V or more than 5V for external reference voltage on the AREF pin. If you are
using an external reference on the AREF pin, you must set the analog reference to EXTERNAL before calling
the analogRead() function. Otherwise, you will short the active reference voltage (internally generated) and the
AREF pin, possibly damaging the microcontroller on your Arduino board.
Alternatively, you can connect the external reference voltage to the AREF pin through a 5K resistor, allowing you
to switch between external and internal reference voltages.
Note that the resistor will alter the voltage that is used as the reference because there is an internal 32K resistor on
the AREF pin. The two act as a voltage divider. For example, 2.5V applied through the resistor will yield 2.5 * 32
/ (32 + 5) = ~2.2V at the AREF pin.
Example
int analogPin = 3;// potentiometer wiper (middle terminal) connected to analog pin 3
void setup() {
void loop() {
(See Appendix D, Number Systems, for a detailed explanation of binary, octal, decimal and
hexadecimal numbers.)
(' '), form feed ('\f'), carriage return ('\r'), horizontal tab ('\t'), or vertical tab ('\v')—and 0
otherwise.
Example 1
void setup () {
Serial.begin (9600);
void loop () {
Result
According to isdigit:
8 is a digit
# is not a digit
According to isalpha:
A is a letter
b is a letter
& is not a letter
4 is not a letter
According to isalnum:
A is a digit or a letter
8 is a digit or a letter
# is not a digit or a letter
According to isxdigit:
F is a hexadecimal digit
J is not a hexadecimal digit
7 is a hexadecimal digit
We use the conditional operator (?:) with each function to determine whether the string " is a " or the string " is
not a " should be printed in the output for each character tested. For example, line a indicates that if '8' is a digit—
i.e., if isdigit returns a true (nonzero) value—the string "8 is a " is printed. If '8' is not a digit (i.e., if isdigit returns
0), the string " 8 is not a " is printed.
Example 2
The following example demonstrates the use of the functions islower and isupper. The
function islower determines whether its argument is a lowercase letter (a–z). Function isupper determines
whether its argument is an uppercase letter (A–Z).
void setup () {
Serial.begin (9600);
void setup () {
Result
According to islower:
p is a lowercase letter
P is not a lowercase letter
5 is not a lowercase letter
! is not a lowercase letter
According to isupper:
D is an uppercase letter
d is not an uppercase letter
8 is not an uppercase letter
$ is not an uppercase letter
Example 3
The following example demonstrates the use of functions isspace, iscntrl, ispunct, isprint and isgraph.
The function isspace determines whether its argument is a white-space character, such as space (' '), form feed ('\f'), newline ('\n'),
carriage return ('\r'), horizontal tab ('\t') or vertical tab ('\v').
The function iscntrl determines whether its argument is a control character such as horizontal tab ('\t'), vertical tab ('\v'), form feed
('\f'), alert ('\a'), backspace ('\b'), carriage return ('\r') or newline ('\n').
The function ispunct determines whether its argument is a printing character other than a space, digit or letter, such as $, #, (, ), [, ], {,
}, ;, : or %.
The function isprint determines whether its argument is a character that can be displayed on the screen (including the space character).
The function isgraph tests for the same characters as isprint, but the space character is not included.
void setup () {
Serial.begin (9600);
void loop () {
Result
According to isspace:
Newline is a whitespace character
Horizontal tab is a whitespace character
% is not a whitespace character
According to iscntrl:
Newline is a control character
$ is not a control character
According to ispunct:
; is a punctuation character
Y is not a punctuation character
# is a punctuation character
According to isprint:
$ is a printing character
Alert is not a printing character
Space is a printing character
According to isgraph:
Q is a printing character other than a space
Space is not a printing character other than a space
Library Macros
Following are the macros defined in the header math.h −
Given below is the list of macros defined in the header math.h
Library Functions
The following functions are defined in the header math.h −
Given below is the list of functions are defined in the header math.h
Example
The following example shows how to use the most common math.h library functions −
void setup() {
Serial.begin(9600);
void loop() {
Result
cos num = 0.10
absolute value of num = 45.45
floating point modulo =15.25
sine of num = 0.99
square root of num : 6.74
tangent of num : 9.67
exponential value of num : ovf
cos num : 1.55
tangent of num : 0.59
arc tangent of num : 3.82
cos num : 1.66
logarithm of num to base 10 : inf
power of num : 2065.70
Example
double sine = sin(2); // approximately 0.90929737091
Duty Cycle − It is represented as the percentage of time signal that remains on during the period of the PWM signal.
Period
As shown in the figure, Ton denotes the on-time and Toff denotes the off-time of signal. Period is the sum of both
on and off times and is calculated as shown in the following equation −
Ttotal=Ton+ToffTtotal=Ton+Toff
Duty Cycle
Duty cycle is calculated as the on-time of the period of time. Using the period calculated above, duty cycle is
calculated as −
D=TonTon+Toff=TonTtotalD=TonTon+Toff=TonTtotal
analogWrite() Function
The analogWrite() function writes an analog value (PWM wave) to a pin. It can be used to light a LED at
varying brightness or drive a motor at various speeds. After a call of the analogWrite() function, the pin will
generate a steady square wave of the specified duty cycle until the next call to analogWrite() or a call to
digitalRead() or digitalWrite() on the same pin. The frequency of the PWM signal on most pins is approximately
490 Hz. On the Uno and similar boards, pins 5 and 6 have a frequency of approximately 980 Hz. Pins 3 and 11 on
the Leonardo also run at 980 Hz.
On most Arduino boards (those with the ATmega168 or ATmega328), this function works on pins 3, 5, 6, 9, 10,
and 11. On the Arduino Mega, it works on pins 2 - 13 and 44 - 46. Older Arduino boards with an ATmega8 only
support analogWrite() on pins 9, 10, and 11.
The Arduino Due supports analogWrite() on pins 2 through 13, and pins DAC0 and DAC1. Unlike the PWM
pins, DAC0 and DAC1 are Digital to Analog converters, and act as true analog outputs.
You do not need to call pinMode() to set the pin as an output before calling analogWrite().
value − the duty cycle: between 0 (always off) and 255 (always on).
Example
void setup() {
void loop() {
randomSeed(seed)
random()
randomSeed (seed)
The function randomSeed(seed) resets Arduino’s pseudorandom number generator. Although the distribution of
the numbers returned by random() is essentially random, the sequence is predictable. You should reset the
generator to some random value. If you have an unconnected analog pin, it might pick up random noise from the
surrounding environment. These may be radio waves, cosmic rays, electromagnetic interference from cell phones,
fluorescent lights and so on.
Example
randomSeed(analogRead(5)); // randomize using noise from analog pin 5
random( )
The random function generates pseudo-random numbers. Following is the syntax.
Example
long randNumber;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
void loop() {
Serial.print("random1=");
randNumber = random(300);
Serial.print("random2=");
Serial.println (randNumber);
delay(50);
Let us now refresh our knowledge on some of the basic concepts such as bits and bytes.
Bits
A bit is just a binary digit.
Similar to the decimal number system, in which digits of a number do not have the same value, the ‘significance’ of a bit depends on
its position in the binary number. For example, digits in the decimal number 666 are the same, but have different values.
Bytes
A byte consists of eight bits.
The leftmost bit has the greatest value called the Most Significant Bit (MSB).
The rightmost bit has the least value and is therefore, called the Least Significant Bit (LSB).
Since eight zeros and ones of one byte can be combined in 256 different ways, the largest decimal number that can be represented by
one byte is 255 (one combination represents a zero).
ARDUINO – INTERRUPTS
Interrupts stop the current work of Arduino such that some other work can be done.
Suppose you are sitting at home, chatting with someone. Suddenly the telephone rings. You stop chatting, and
pick up the telephone to speak to the caller. When you have finished your telephonic conversation, you go back to
chatting with the person before the telephone rang.
Similarly, you can think of the main routine as chatting to someone, the telephone ringing causes you to stop
chatting. The interrupt service routine is the process of talking on the telephone. When the telephone conversation
ends, you then go back to your main routine of chatting. This example explains exactly how an interrupt causes a
processor to act.
The main program is running and performing some function in a circuit. However, when an interrupt occurs the
main program halts while another routine is carried out. When this routine finishes, the processor goes back to the
main routine again.
Important features
Here are some important features about interrupts −
Interrupts can come from various sources. In this case, we are using a hardware interrupt that is triggered by a state change on one of
the digital pins.
Most Arduino designs have two hardware interrupts (referred to as "interrupt0" and "interrupt1") hard-wired to digital I/O pins 2 and 3,
respectively.
The Arduino Mega has six hardware interrupts including the additional interrupts ("interrupt2" through "interrupt5") on pins 21, 20, 19,
and 18.
You can define a routine using a special function called as “Interrupt Service Routine” (usually known as ISR).
You can define the routine and specify conditions at the rising edge, falling edge or both. At these specific conditions, the interrupt
would be serviced.
It is possible to have that function executed automatically, each time an event happens on an input pin.
Types of Interrupts
There are two types of interrupts −
Hardware Interrupts − They occur in response to an external event, such as an external interrupt pin going high or low.
Software Interrupts − They occur in response to an instruction sent in software. The only type of interrupt that the “Arduino
language” supports is the attachInterrupt() function.
Example
volatile int state = LOW; // To make sure variables shared between an ISR
void setup() {
void loop() {
void blink() {
//ISR function
ARDUINO – COMMUNICATION
Hundreds of communication protocols have been defined to achieve this data exchange. Each protocol can be
categorized into one of the two categories: parallel or serial.
Parallel Communication
Parallel connection between the Arduino and peripherals via input/output ports is the ideal solution for shorter
distances up to several meters. However, in other cases when it is necessary to establish communication between
two devices for longer distances it is not possible to use parallel connection. Parallel interfaces transfer multiple
bits at the same time. They usually require buses of data - transmitting across eight, sixteen, or more wires. Data
is transferred in huge, crashing waves of 1’s and 0’s.
Advantages and Drawbacks of Parallel Communication
Parallel communication certainly has its advantages. It is faster than serial, straightforward, and relatively easy to
implement. However, it requires many input/output (I/O) ports and lines. If you have ever had to move a project
from a basic Arduino Uno to a Mega, you know that the I/O lines on a microprocessor can be precious and few.
Therefore, we prefer serial communication, sacrificing potential speed for pin real estate.
One of the most important things concerning serial communication is the Protocol, which should be strictly
observed. It is a set of rules, which must be applied such that the devices can correctly interpret data they
mutually exchange. Fortunately, Arduino automatically takes care of this, so that the work of the
programmer/user is reduced to simple write (data to be sent) and read (received data).
Synchronous − Devices that are synchronized use the same clock and their timing is in synchronization with each other.
Asynchronous − Devices that are asynchronous have their own clocks and are triggered by the output of the previous state.
It is easy to find out if a device is synchronous or not. If the same clock is given to all the connected devices, then
they are synchronous. If there is no clock line, it is asynchronous.
For example, UART (Universal Asynchronous Receiver Transmitter) module is asynchronous.
The asynchronous serial protocol has a number of built-in rules. These rules are nothing but mechanisms that help
ensure robust and error-free data transfers. These mechanisms, which we get for eschewing the external clock
signal, are −
Synchronization bits
Data bits
Parity bits
Baud rate
Synchronization Bits
The synchronization bits are two or three special bits transferred with each packet of data. They are the start bit
and the stop bit(s). True to their name, these bits mark the beginning and the end of a packet respectively.
There is always only one start bit, but the number of stop bits is configurable to either one or two (though it is
normally left at one).
The start bit is always indicated by an idle data line going from 1 to 0, while the stop bit(s) will transition back to
the idle state by holding the line at 1.
Data Bits
The amount of data in each packet can be set to any size from 5 to 9 bits. Certainly, the standard data size is your
basic 8-bit byte, but other sizes have their uses. A 7-bit data packet can be more efficient than 8, especially if you
are just transferring 7-bit ASCII characters.
Parity Bits
The user can select whether there should be a parity bit or not, and if yes, whether the parity should be odd or
even. The parity bit is 0 if the number of 1’s among the data bits is even. Odd parity is just the opposite.
Baud Rate
The term baud rate is used to denote the number of bits transferred per second [bps]. Note that it refers to bits, not
bytes. It is usually required by the protocol that each byte is transferred along with several control bits. It means
that one byte in serial data stream may consist of 11 bits. For example, if the baud rate is 300 bps then maximum
37 and minimum 27 bytes may be transferred per second.
Arduino UART
The following code will make Arduino send hello world when it starts up.
void setup() {
void loop() {
After the Arduino sketch has been uploaded to Arduino, open the Serial monitor at the top right section of
Arduino IDE.
Type anything into the top box of the Serial Monitor and press send or enter on your keyboard. This will send a
series of bytes to the Arduino.
The following code returns whatever it receives as an input.
The following code will make Arduino deliver output depending on the input provided.
void setup() {
void loop() {
serial port
Notice that Serial.print and Serial.println will send back the actual ASCII code, whereas Serial.write will send
back the actual text. See ASCII codes for more information.
Master Transmitter
The following functions are used to initialize the Wire library and join the I2C bus as a master or slave. This is
normally called only once.
Wire.begin(address) − Address is the 7-bit slave address in our case as the master is not specified and it will join the bus as a master.
Wire.beginTransmission(address) − Begin a transmission to the I2C slave device with the given address.
Wire.write(value) − Queues bytes for transmission from a master to slave device (in-between calls to beginTransmission() and
endTransmission()).
Wire.endTransmission() − Ends a transmission to a slave device that was begun by beginTransmission() and transmits the bytes that
were queued by wire.write().
Example
short age = 0;
void loop() {
Wire.beginTransmission(2);
// transmit to device #2
Wire.write("age is = ");
delay(1000);
Slave Receiver
The following functions are used −
Wire.onReceive(received data handler) − Function to be called when a slave device receives data from the master.
Wire.available() − Returns the number of bytes available for retrieval with Wire.read().This should be called inside the
Wire.onReceive() handler.
Example
void loop() {
delay(250);
Master Receiver
The Master, is programmed to request, and then read bytes of data that are sent from the uniquely addressed Slave
Arduino.
The following function is used −
Wire.requestFrom(address,number of bytes) − Used by the master to request bytes from a slave device. The
bytes may then be retrieved with the functions wire.available() and wire.read() functions.
Example
}
void loop() {
delay(500);
Slave Transmitter
The following function is used.
Wire.onRequest(handler) − A function is called when a master requests data from this slave device.
Example
#include <Wire.h>
void setup() {
Byte x = 0;
void loop() {
delay(100);
void requestEvent() {
x++;
MOSI − This is the master output / slave input driven by the master.
MISO − This is the master input / slave output driven by the master.
The following functions are used. You have to include the SPI.h.
SPI.begin() − 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 the SPI clock divider relative to the system clock. On AVR based boards, the dividers
available are 2, 4, 8, 16, 32, 64 or 128. The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to one-quarter of the
frequency of the system clock (5 Mhz for the boards at 20 MHz).
SPI.transfer(val) − SPI transfer is based on a simultaneous send and receive: the received data is returned in receivedVal.
Mode 0 (the default) − Clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge)
(CPHA = 0).
Mode 1 − Clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1).
Mode 2 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0).
Mode 3 − Clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1).
SPI.attachInterrupt(handler) − Function to be called when a slave device receives data from the master.
Now, we will connect two Arduino UNO boards together; one as a master and the other as a slave.
(SS) : pin 10
(MOSI) : pin 11
(MISO) : pin 12
(SCK) : pin 13
The ground is common. Following is the diagrammatic representation of the connection between both the boards
−
Let us see examples of SPI as Master and SPI as Slave.
SPI as MASTER
Example
#include <SPI.h>
SPI.begin ();
char c;
SPI.transfer (c);
Serial.print(c);
delay(2000);
SPI as SLAVE
Example
#include <SPI.h>
Serial.begin (115200);
process = false;
buff [indx++] = c; // save data in the next index in the array buff
process = true;
if (process) {