0% found this document useful (0 votes)
21 views282 pages

Arduino UNO Board

Uploaded by

geletabejiga8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views282 pages

Arduino UNO Board

Uploaded by

geletabejiga8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arduino UNO board

AD

Unit: 1
The Arduino UNO is a standard board of Arduino. Arduino UNO is based on
an ATmega328P Microcontroller. It is easy to use compared to other boards, such as the
Arduino Mega board, etc. The components on the Arduino board are ATmega328P
Microcontroller, ICSP pin, power LED indicator, Digital I/O pins, Analog pins, AREF pin, 16
MHz crystal oscillator, GND pins, Vin pin, voltage regulator, Tx and Rx LED, USB, and a
reset button.

The Arduino board is shown below:

Breadboard

Unit: 1 (400 points)


A breadboard is defined as a rectangular shape board, which is made of plastic. It has tiny holes on it that are
used to insert the wires of the electronic components, such as LED, resistor, etc.
It does not require any soldering to attach the electronic components to the board. We need to join the
components using wire to allow electricity to move from one component to another.

Bright white LED


AD

Unit: 1
LED stands for Light Emitting Diode, which is defined as a semiconductor light source. The bright white
LED produces the white light, while other white lights produce a yellow hue.

When electrons combine with holes in the semiconductor, energy is released in the form of photons, which
produces light.

Green LED

Unit: 8
The Green LED (Light Emitting Diode) produces the green light when electricity is passed through its
terminals. The process is called electroluminescence.
Red LED

Unit: 8
The Red LED produces the red light when electricity is passed through its terminals.

Yellow LED

Unit: 8
The Yellow LED produces the yellow light when electricity is passed through its terminals.
Blue LED

Unit: 3
The Blue LED produces blue light when electricity is passed through its terminals.

RGB LED

Unit: 1
The RGB LED uses the combination of three colors (Red, Green, and Blue) to produce the light. The millions
of hue of lights can be created from the combination of these three universal colors.

AD
The colors are generated by adjusting the brightness of each of the three colors by using the PWM pin.

LCD Alphanumeric

Unit: 1
The LCD (Liquid Crystal Display) is a digital display, which gives information in the form of letters or
numbers. It is the basic component in a kit.

The configuration of the LCD display can vary from 16 x 2, 40 x 4, and 8 x 1.

Here, 8 x 1 signifies 8 characters in a row.

Wooden base that can be easily assembled

Unit: 1
The wooden base is a compatible base that is used to assemble the Arduino board and Breadboard on its base.

AD

Solid core jump wires


Unit: 70
These are the most common wires used in the Breadboard. The wires vary in different lengths and colors.
These wires are cheap and come in the form of the spool. We need to cut the wire according to the required
length.

Stranded Jump wires of RED color

Unit: 1
The stranded jump wires have solid tips.

The RED color stranded jump wire is shown below:

Stranded Jump wires of BLACK color

Unit: 1
The BLACK color stranded jump wire is shown below:
9V Battery

Unit: 1
It is a standard-sized battery used for different purposes. A polarized snap is connected at the top of the
rectangle-shaped battery.

Resistors of 220 Ohms, 560 Ohms, 1kOhms, 4.7kOhms, 10kOhms,


1MOhms, and 10MOhms
Unit: 20 (220 Ohms), 5 (560 Ohms), 5 (1kOhms), 5 (4.7kOhms), 20 (10kOhms), 5 (1MOhms), 5 (10MOhms)

A resistor is a two-terminal component having a particular electrical resistance.

The function of the resistor is to manage the current flow. It controls the current flowing to the other
components. The other functions are dividing voltages, adjusting the signal levels, etc.

The resistors with resistance value are shown below:


Small DC Motor of 6/9V

Unit: 1
It is a small motor whose voltage ranges from 6V to 9V.

(40 x 1) Male Strip pins

Unit: 1
The standard pitch for the 40 x 1 connector pin is 2.54mm. It is a single row male pin consisting of 40 pin
headers connected to it.

It is shown below:

Red, Blue, and Green Transparent Gels

Unit: 3
The colored gels act as a filter for the sensors, which allows the specific colored light to pass through that gel.

Diodes (1N4007)

Unit: 5
A diode conducts the current in one direction. The diode is an electronic component that has two terminals.
The diodes can be used as the signal modulators, and demodulators, switches, voltage regulators, etc.

The Capacitors of 100uF

Unit: 5
The capacitor is a device that stores electrical energy. The energy is stored between the plates of the capacitor
in the form of an electrostatic field.

The image of 100uF/450V is shown below:

The capacitors like 100uF/25V, 100uF/50V, etc., are also available.

Optocouplers

Unit: 1
The noise from the electrical signals is removed by the Optocouplers. It is also used to separate the low power
circuits from the high-power circuits and transfers the electrical signals between these separated circuits.

Small servo motor

Unit: 1
The servo motor is used to control the position, liner speed, and rotational speed. The advantageous features of
servo motor are high efficiency, high precision, low heat generation, etc.

The servometer will look like the below image:

Piezo Capsule

Unit: 1
The piezo in Arduino is defined as an electronic device, which produces a voltage when deformed by some
mechanical strain, sound wave, or a vibration.

Push Buttons

Unit: 10
The push buttons are used as a switch. We can power ON the board supply or the connection by pressing the
push button.
Tilt Sensor

Unit: 1
The tilt sensor is used to measure the tilt with respect to the reference plain. It is also used to detect the
inclination of the plane.

Potentiometer (10kOhms)

Unit: 3
The potentiometer acts as a knob, which is used to provide variable resistance. It can also be used to alter its
resistance. The amount of resistance is measured as an analog value.

Phototransistor
Unit: 6
The phototransistor uses the NPN transistors to sense the light level and convert it into the current.

Temperature Sensor

Unit: 1
The temperature sensors are used to record the surrounding temperature. It converts the input data to the
electronic data.

Mosfet Transistors

Unit: 2
We can control the high voltage Arduino projects using the Mosfet Transistors. One terminal is used as a
power source, and the other two terminals are used onboard.

H-bridge Motor Driver [L293D]


Unit: 1
These motors are capable of driving the DC motors. We can turn the motor in both directions with the help of
an H-bridge motor driver.

USB Cable

Unit: 1
The Universal Serial Bus (USB) is a cable that is used to connect the Arduino board with the computer. We
can further program the Arduino board through the Arduino IDE on our computer.

AD

Arduino Boards
Arduino is an easy-to-use open platform to create electronics projects. Arduino boards play
a vital role in creating different projects. It makes electronics accessible to non-engineers,
hobbyists, etc.

The various components present on the Arduino boards are Microcontroller, Digital
Input/output pins, USB Interface and Connector, Analog Pins, Reset Button, Power
button, LED's, Crystal Oscillator, and Voltage Regulator. Some components may differ
depending on the type of board.

The most standard and popular board used over time is Arduino UNO. The ATmega328
Microcontroller present on the UNO board makes it rather powerful than other boards.
There are various types of Arduino boards used for different purposes and projects.
The Arduino Boards are organized using the Arduino (IDE), which can run on various
platforms. Here, IDE stands for Integrated Development Environment.

Let's discuss some common and best Arduino boards.


Types of Arduino Boards
o Arduino UNO
Arduino UNO is based on an ATmega328P microcontroller. It is easy to use compared to
other boards, such as the Arduino Mega board, etc. The Arduino UNO includes 6 analog pin
inputs, 14 digital pins, a USB connector, a power jack, and an ICSP (In-Circuit Serial
Programming) header.

It is the most used and of standard form from the list of all available Arduino Boards. It is
also recommended for beginners as it is easy to use.

o Arduino Nano
AD

The Arduino Nano is a small Arduino board based on ATmega328P or ATmega628


Microcontroller. The connectivity is the same as the Arduino UNO board.

The Nano board is defined as a sustainable, small, consistent, and flexible microcontroller
board. It is small in size compared to the UNO board. The devices required to start our
projects using the Arduino Nano board are Arduino IDE and mini USB.

The Arduino Nano includes an I/O pin set of 14 digital pins and 8 analog pins. It also
includes 6 Power pins and 2 Reset pins.
o Arduino Mega
The Arduino Mega is based on ATmega2560 Microcontroller. The ATmega2560 is an 8-bit
microcontroller. We need a simple USB cable to connect to the computer and the AC to DC
adapter or battery to get started with it. It has the advantage of working with more memory
space.

The Arduino Mega includes 54 I/O digital pins and 16 Analog Input/Output (I/O), ICSP
header, a reset button, 4 UART (Universal Asynchronous Reciever/Transmitter) ports, USB
connection, and a power jack.

o Arduino Micro
The Arduino Micro is based on the ATmega32U4 Microcontroller. It consists of 20 sets of
pins. The 7 pins from the set are PWM (Pulse Width Modulation) pins, while 12 pins are
analog input pins. The other components on board are reset button, 16MHz crystal
oscillator, ICSP header, and a micro USB connection.

The USB is inbuilt in the Arduino Micro board.


The Arduino Micro is also called as the shrunk version of Arduino Leonardo.

o Arduino Leonardo
The basic specification of the Arduino Leonardo is the same as the Arduino Micro. It is also
based on ATmega32U4 Microcontroller. The components present on the board are 20
analog and digital pins, reset button, 16MHz crystal oscillator, ICSP header, and a micro
USB connection.

o Arduino Due
The Arduino Due is based on the 32- bit ARM core. It is the first Arduino board that has
developed based on the ARM Microcontroller. It consists of 54 Digital Input/Output pins and
12 Analog pins. The Microcontroller present on the board is the Atmel SAM3X8E ARM
Cortex-M3 CPU.
It has two ports, namely, native USB port and Programming port. The micro side of the USB
cable should be attached to the programming port.

AD

o Arduino Shields
The Arduino shields are the boards, which can be plugged on the top of the PCB. The
shields further extend the potential of the PCB's. The production of shields is cheap. It is
also easy to use. There are various types of Arduino shields that can be used for different
purposes. For example, the Xbee shield.

The Xbee shield can be used for wireless communication between multiple Arduino boards
over distances upto 300 feet using the Zigbee Module.

o Arduino Lilypad
The Arduino LilyPad was initially created for wearable projects and e-textiles. It is based on
the ATmega168 Microcontroller. The functionality of Lilypad is the same as other Arduino
Boards. It is a round, light-weight board with a minimal number of components to keep the
size of board small.

The Arduino Lilypad board was designed by Sparkfun and Leah. It was developed by Leah
Buechley. It has 9 digital I/O pins.

o Arduino Bluetooth
The Arduino Bluetooth board is based on ATmega168 Microcontroller. It is also named
as Arduino BT board. The components present on the board are 16 digital pins, 6 analog
pins, reset button, 16MHz crystal oscillator, ICSP header, and screw terminals. The screw
terminals are used for power.

AD

The Arduino Bluetooth Microcontroller board can be programmed over the Bluetooth as a
wireless connection.
o Arduino Diecimila
The Arduino Diecimila is also based on ATmeg628 Microcontroller. The board consists of 6
analog pin inputs, 14 digital Input/Output pins, a USB connector, a power jack, an ICSP (In-
Circuit Serial Programming) header, and a reset button.

We can connect the board to the computer using the USB, and can power-on the board with
the help of AC to DC adapter. The Diecimila was initially developed to mark the 10000
delivered boards of Arduino. Here, Diecimila means 10,000 in Italian.

o Arduino Robot
The Arduino Robot is called as the tiny computer. It is widely used in robotics. The board
comprises of the speaker, five-button, color screen, two motors, an SD card reader, a digital
compass, two potentiometers, and five floor sensors.

The Robot Library can be used to control the actuators and the sensors.

o Arduino Ethernet
The Arduino Ethernet is based on the ATmega328 Microcontroller. The board consists of 6
analog pins, 14 digital I/O pins, crystal oscillator, reset button, ICSP header, a power jack,
and an RJ45 connection.

With the help of the Ethernet shield, we can connect our Arduino board to the internet.

o Arduino Zero
The Arduino Zero is generally called as the 32-bit extension of the Arduino UNO. It is based
on ATmel's SAM21 MCU. The board consists of 6 analog pin inputs, 14 digital Input/Output
pins, a USB connector, a power jack, and an ICSP (In-Circuit Serial Programming) header,
UART port pins, a power header, and AREF button.

The Embedded debugger of Atmel is also supported by the Arduino Zero. The function of
Debugger is to provide a full debug interface, which does not require additional hardware.

o Arduino Esplora
The Arduino Esplora boards allow easy interfacing of sensors and actuators. The outputs
and inputs connected on the Esplora board make it unique from other types of Arduino
boards. The board includes outputs, inputs, a small microcontroller, a microphone, a
sensor, a joystick, an accelerometer, a temperature sensor, four buttons, and a slider.

o Arduino Pro Micro


The structure of Arduino Pro Micro is similar to the Arduino Mini board, except the
Microcontroller ATmega32U4. The board consists of 12 digital Input/output pins, 5 PWM
(Pulse Width Modulation) pins, Tx and Rx serial connections, and 10-bit ADC (Analog to
Digital Converter).

List of available boards in Arduino software


The list of boards that we can see in the Arduino software is shown below:

Arduino UNO
The Arduino UNO is a standard board of Arduino. Here UNO means 'one' in Italian. It was
named as UNO to label the first release of Arduino Software. It was also the first USB board
released by Arduino. It is considered as the powerful board used in various projects.
Arduino.cc developed the Arduino UNO board.

Arduino UNO is based on an ATmega328P microcontroller. It is easy to use compared to


other boards, such as the Arduino Mega board, etc. The board consists of digital and
analog Input/Output pins (I/O), shields, and other circuits.
The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a power
jack, and an ICSP (In-Circuit Serial Programming) header. It is programmed based on IDE,
which stands for Integrated Development Environment. It can run on both online and offline
platforms.

The IDE is common to all available boards of Arduino.

The Arduino board is shown below:

The components of Arduino UNO board are shown below:


Let's discuss each component in detail.

o ATmega328 Microcontroller- It is a single chip Microcontroller of the ATmel family. The


processor code inside it is of 8-bit. It combines Memory (SRAM, EEPROM, and Flash),
Analog to Digital Converter, SPI serial ports, I/O lines, registers, timer, external
and internal interrupts, and oscillator.
o ICSP pin - The In-Circuit Serial Programming pin allows the user to program using the
firmware of the Arduino board.
o Power LED Indicator- The ON status of LED shows the power is activated. When the
power is OFF, the LED will not light up.
o Digital I/O pins- The digital pins have the value HIGH or LOW. The pins numbered from
D0 to D13 are digital pins.
o TX and RX LED's- The successful flow of data is represented by the lighting of these
LED's.
o AREF- The Analog Reference (AREF) pin is used to feed a reference voltage to the
Arduino UNO board from the external power supply.
o Reset button- It is used to add a Reset button to the connection.
o USB- It allows the board to connect to the computer. It is essential for the programming
of the Arduino UNO board.
o Crystal Oscillator- The Crystal oscillator has a frequency of 16MHz, which makes the
Arduino UNO a powerful board.
o Voltage Regulator- The voltage regulator converts the input voltage to 5V.
o GND- Ground pins. The ground pin acts as a pin with zero voltage.
o Vin- It is the input voltage.
o Analog Pins- The pins numbered from A0 to A5 are analog pins. The function of Analog
pins is to read the analog sensor used in the connection. It can also act as GPIO
(General Purpose Input Output) pins.

Why is Arduino recommended over other boards for beginners?


The USB port in the Arduino board is used to connect the board to the computer using the
USB cable. The cable acts as a serial port and as the power supply to interface the board.
Such dual functioning makes it unique to recommend and easy to use for beginners.

AD

What is the main difference between Arduino UNO and Arduino


Nano?
The Arduino Nano has a compact size and mini USB cable than the Arduino UNO.

What is the main difference between Arduino UNO and Arduino


Mega?
The Arduino UNO is a standard board recommended to beginners, while Arduino Mega is
used for complex projects due to its greater memory space.

Memory
The memory structure is shown in the below image:
The preinstalled flash has a bootloader, which takes the memory of 0.5 Kb.

Here, SRAM stands for Static Random Access Memory, and EEPROM stands for
Electrically Erasable Programmable Read-Only Memory.

Technical Specifications of Arduino UNO


The technical specifications of the Arduino UNO are listed below:

o There are 20 Input/Output pins present on the Arduino UNO board. These 20 pis include
6 PWM pins, 6 analog pins, and 8 digital I/O pins.
o The PWM pins are Pulse Width Modulation capable pins.
o The crystal oscillator present in Arduino UNO comes with a frequency of 16MHz.
o It also has a Arduino integrated WiFi module. Such Arduino UNO board is based on the
Integrated WiFi ESP8266 Module and ATmega328P microcontroller.
o The input voltage of the UNO board varies from 7V to 20V.
o Arduino UNO automatically draws power from the external power supply. It can also
draw power from the USB.
AD

How to get started with Arduino UNO?


We can program the Arduino UNO using the Arduino IDE. The Arduino IDE is the Integral
Development program, which is common to all the boards.

We can also use Arduino Web Editor, which allows us to upload sketches and write the
code from our web browser (Google Chrome recommended) to any Arduino Board. It is an
online platform.

The USB connection is essential to connect the computer with the board. After the
connection, the PWR pins will light in green. It is a green power LED.

AD

The steps to get started with Arduino UNO are listed below:

o Install the drivers of the board.


As soon we connect the board to the computer, Windows from XP to 10 will automatically
install the board drivers.

But, if you have expanded or downloaded the zip package, follow the below steps:

1. Click on Start -> Control Panel -> System and Security.


2. Click on System -> Device Manager -> Ports (COM &LPT) -> Arduino UNO (COMxx). If
the COM &LPT is absent, look Other Devices -> Unknown Device.
3. Right-click to Arduino UNO (COmxx) -> Update Driver Software -> Browse my computer
for driver software.
4. Select the file "inf" to navigate else, select "ArduinoUNO.inf" .
5. Installation Finished.
o Open the code or sketch written in the Arduino software.
o Select the type of board.
Click on 'Tools' and select Board, as shown below:
o
o

o
o
o
o Select the port. Click on the Tools -> Port (select the port). The port likely will
be COM3 or higher. For example, COM6, etc. The COM1 and COM2 ports will not
appear, because these two ports are reserved for the hardware serial ports.
o Now, upload and run the written code or sketch.
To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:

Within the few seconds after the compile and run of code or sketch, the RX and TX light
present on the Arduino board will flash.

AD

The 'Done Uploading' message will appear after the code is successfully uploaded. The
message will be visible in the status bar.

Arduino UNO Pinout


The Arduino UNO is a standard board of Arduino, which is based on
an ATmega328P microcontroller. It is easier to use than other types of Arduino Boards.

The Arduino UNO Board, with the specification of pins, is shown below:
Let's discuss each pin in detail.

o ATmega328 Microcontroller- It is a single chip Microcontroller of the ATmel family. The


processor core inside it is of 8-bit. It is a low-cost, low powered, and a simple
microcontroller. The Arduino UNO and Nano models are based on the ATmega328
Microcontroller.
o Voltage Regulator
The voltage regulator converts the input voltage to 5V. The primary function of voltage
regulator is to regulate the voltage level in the Arduino board. For any changes in the input
voltage of the regulator, the output voltage is constant and steady.

o GND - Ground pins. The ground pins are used to ground the circuit.
o TXD and RXD
AD
TXD and RXD pins are used for serial communication. The TXD is used for transmitting the
data, and RXD is used for receiving the data. It also represents the successful flow of data.

o USB Interface
The USB Interface is used to plug-in the USB cable. It allows the board to connect to the
computer. It is essential for the programming of the Arduino UNO board.

o RESET
It is used to add a Reset button to the connection.

o SCK
It stands for Serial Clock. These are the clock pulses, which are used to synchronize the
transmission of data.

o MISO
It stands for Master Input/ Slave Output. The save line in the MISO pin is used to send the
data to the master.

o VCC
It is the modulated DC supply voltage, which is used to regulate the IC's used in the
connection. It is also called as the primary voltage for IC's present on the Arduino board.
The Vcc voltage value can be negative or positive with respect to the GND pin.

o Crystal Oscillator- The Crystal oscillator has a frequency of 16MHz, which makes the
Arduino UNO a powerful board.
o ICSP
It stands for In-Circuit Serial Programming. The users can program the Arduino board's
firmware using the ICSP pins.

The program or firmware with the advanced functionalities is received by microcontroller


with the help of the ICSP header.

The ICSP header consists of 6 pins.

The structure of the ICSP header is shown below:


It is the top view of the ICSP header.

o SDA
It stands for Serial Data. It is a line used by the slave and master to send and receive data.
It is called as a data line, while SCL is called as a clock line.

o SCL
It stands for Serial Clock. It is defined as the line that carries the clock data. It is used to
synchronize the transfer of data between the two devices. The Serial Clock is generated by
the device and it is called as master.

AD

o SPI
It stands for Serial Peripheral Interface. It is popularly used by the microcontrollers to
communicate with one or more peripheral devices quickly. It uses conductors for data
receiving, data sending, synchronization, and device selection (for communication).

o MOSI
It stands for Master Output/ Slave Input.

The MOSI and SCK are driven by the Master.

o SS
It stands for Slave Select. It is the Slave Select line, which is used by the master. It acts as
the enable line.

o I2C
It is the two-wire serial communication protocol. It stands for Inter Integrated Circuits. The
I2C is a serial communication protocol that uses SCL (Serial Clock) and SDA (Serial Data)
to receive and send data between two devices.
AD

3.3V and 5V are the operating voltages of the board.

Arduino Simulator
The Arduino simulator is a virtual portrayal of the circuits of Arduino in the real world.
We can create many projects using a simulator without the need for any hardware.

The Simulator helps beginner and professional designers to learn, program, and create their
projects without wasting time on collecting hardware equipments.

Advantages of using Simulator


There are various advantages of using simulator, which are listed below:

o It saves money, because there is no need to buy hardware equipments to make a


project.
o The task to create and learn Arduino is easy for beginners.
o We need not to worry about the damage of board and related equipments.
o No messy wire structure required.
o It helps students to eliminate their mistakes and errors using simulator.
o It supports line to line debugging, and helps to find out the errors easily.
o We can learn the code and build projects anywhere with our computer and internet
connection.
o We can also share our design with others.

Types of Simulator
There are various simulators available. Some are available for free, while some require a
license to access the simulators.

Some types of simulators are listed below:

o Autodesk Tinkercad
o Emulator Arduino Simulator
o Autodesk Eagle
o Proteus Simulator
o Virtronics Arduino Simulator
o ArduinoSim
AD

Autodesk Eagle is an advanced simulator, which is used to design 2D and 3D models of


PCB, modular designs, multi-sheet schematics, real-time synchronization, etc.
AD

How to access simulator?


Here, we are using the Autodesk Tinkercad Simulator.

The steps to access the TINKERCAD are listed below:

1. Open the official website of tinkercad. URL: https://www.tinkercad.com/

A window will appear, as shown below:

2. Click on the three horizontal lines present on the upper right corner.

3. Click on the 'Sign in' option, if you have an account in Autodesk. Otherwise, click on
the 'JOIN NOW' option if you don't have an account, as shown below:
The SIGN IN window will appear as:
We can select any sign-in method. Specify the username and password.

We already have an account in Autodesk, so we will sign-in directly with the username and
password.

The JOIN window will appear as:


Select the preference according to the requirements and sign-in using Gmail, etc.

AD

4. Now, a window will appear, as shown below:


5. Click on the 'Create new circuit' option to start designing the Arduino circuit, as shown
above.

The 'Circuits' option will also show the previous circuits created by user. The design option
is used for creating the 3D design, which is of no use in Arduino.

6. We are now ready to start with the Autodesk Tinkercad. We can start creating our
projects.

Autodesk Tinkercad Simulator


It is also a simulator that is used to design virtual circuits.

AD

Features of Tinkercad

The features of Tinkercad are listed below:

o Glow and move circuit assembly. It means we can use the components of a circuit
according to the project requirement. Glow here signifies the glowing of LED.
o Integrated product design. It means the electronic components used in the circuitry
are real.
o Arduino Programming. We can directly write the program or code in the editor of the
simulator.
o We can also consider some ready-made examples provided by the tinkercad for better
understanding.
o Realtime simulation. We can prototype our designs within the browser before
implementing them in real-time.

How to use a simulator?


Sign-in on the Autodesk Tinkercad, as explained above. Now, follow the below steps:

o Click on 'Create new circuit' option, as shown below:

o A window will appear. We need to drag and drop the desired components in the project
screen. It is shown below:
o Click on the drop list of components and select the 'All' option.
The drop list will appear as:
The selected option 'All' will display all the components and starter examples when we
scroll down a little, as shown below:

Code example to blink an LED


Let's understand with an example to blink an LED. We can use both ( blinking an LED in
basic projects and the one specified below) methods to blink an LED.

The steps are listed below:

o Search UNO R3 and drag-drop the board on the project screen. We can select any
board according to the requirements.
o Search a LED, and 1 resistor of 220 ohms and drag-drop them on the project screen.
After selecting the resistor, a box to set the resistance will appear, as shown below:
Here, we have selected the red color for LED. We can also choose other colors.

After selecting the LED, a box to set the color will appear, as shown below:

o Now, connect the wires. For wiring, just select the point on the board to the terminal of
the component. We are not required to search for wires in the search box.
o The circuit will now appear as:
o Select the 'Text' instead of block view, as shown below:

o Click on the code button to write the code, as shown below:

o The coding screen will appear as:


It also displays the error in the code, if any.

o Click on 'Start Simulation' to upload the code on the board.


The LED will light up for 1 second and dim for 1 second.

The lighting LED is shown below:


Click on 'Stop Simulation' to stop the blinking of an LED, as shown below:

Serial Monitor

The serial monitor is present on the bottom of the coding screen.

It will look like the below image:

Arduino Coding Basics


We have already discussed the popular Arduino Boards, Arduino IDEs, and Installation
process of the Arduino software. We learned that Arduino IDE (Integrated Development
Environment) allows us to draw the sketch and upload it to the various Arduino
boards using code. The code is written in a simple programming language similar
to C and C++.

The initial step to start with Arduino is the IDE download and installation.

Let's discuss the basics to start with Arduino programming.

Brackets
There are two types of brackets used in the Arduino coding, which are listed below:

o Parentheses ( )
o Curly Brackets { }
Parentheses ( )

The parentheses brackets are the group of the arguments, such as method, function, or a
code statement. These are also used to group the math equations.

Curly Brackets { }

The statements in the code are enclosed in the curly brackets. We always require closed
curly brackets to match the open curly bracket in the code or sketch.

Open curly bracket- ' { '

Closed curly bracket - ' } '

AD

Line Comment
There are two types of line comments, which are listed below:

o Single line comment


o Multi-line comment
AD

// Single line comment

The text that is written after the two forward slashes are considered as a single line
comment. The compiler ignores the code written after the two forward slashes. The
comment will not be displayed in the output. Such text is specified for a better
understanding of the code or for the explanation of any code statement.

The // (two forward slashes) are also used to ignore some extra lines of code without
deleting it.

/ * Multi - line comment */

The Multi-line comment is written to group the information for clear understanding. It starts
with the single forward slash and an asterisk symbol (/ *). It also ends with the / *. It is
commonly used to write the larger text. It is a comment, which is also ignored by the
compiler.

Coding Screen
The coding screen is divided into two blocks. The setup is considered as the preparation
block, while the loop is considered as the execution block. It is shown below:

AD
The set of statements in the setup and loop blocks are enclosed with the curly brackets. We
can write multiple statements depending on the coding requirements for a particular project.

For example:

1. void setup ( )
2. {
3. Coding statement 1;
4. Coding statement 2;
5. .
6. .
7. .
8. Coding statement n;
9. }
10. void loop ( )
11. {
12. Coding statement 1;
13. Coding statement 2;
14. .
15. .
16. .
17. Coding statement n;
18. }
What is Setup? What type of code is written in the setup block?
It contains an initial part of the code to be executed. The pin modes, libraries, variables,
etc., are initialized in the setup section. It is executed only once during the uploading of the
program and after reset or power up of the Arduino board.

Zero setup () resides at the top of each sketch. As soon as the program starts running, the
code inside the curly bracket is executed in the setup and it executes only once.

AD

What is Loop? What type of code is written in the Loop block?

The loop contains statements that are executed repeatedly. The section of code inside the
curly brackets is repeated depending on the value of variables.

Time in Arduino
The time in Arduino programming is measured in a millisecond.

Where, 1 sec = 1000 milliseconds

We can adjust the timing according to the milliseconds.

For example, for a 5-second delay, the time displayed will be 5000 milliseconds.

Example:

Let's consider a simple LED blink example.

The steps to open such example are:

1. Click on the File button, which is present on the menu bar.


2. Click on the Examples.
3. Click on the Basics option and click on the Blink

The example will reopen in a new window, as shown below:


o The void setup () would include pinMode as the main function.

pinMode ( )
The specific pin number is set as the INPUT or OUTPUT in the pinMode () function.

The Syntax is: pinMode (pin, mode)

Where,

pin: It is the pin number. We can select the pin number according to the requirements.

Mode: We can set the mode as INPUT or OUTPUT according to the corresponding pin
number.

Let' understand the pinMode with an example.

Example: We want to set the 12 pin number as the output pin.

Code:

1. pinMode (12, OUTPUT);


Why is it recommended to set the mode of pins as OUTPUT?

The OUTPUT mode of a specific pin number provides a considerable amount of current to
other circuits, which is enough to run a sensor or to light the LED brightly. The output state
of a pin is considered as the low-impedance state.

The high current and short circuit of a pin can damage the ATmel chip. So, it is
recommended to set the mode as OUTPUT.
Can we set the pinMode as INPUT?

The digitalWrite () will disable the LOW during the INPUT mode. The output pin will be
considered as HIGH.

We can use the INPUT mode to use the external pull-down resistor. We are required to set
the pinMode as INPUT_PULLUP. It is used to reverse the nature of the INPUT mode.

The sufficient amount of current is provided by the pull-up mode to dimly light an LED,
which is connected to the pin in the INPUT mode. If the LED is working dimly, it means this
condition is working out.

Due to this, it is recommended to set the pin in OUTPUT mode.

o The void loop () would include digitalWrite( ) and delay ( ) as the main function.
AD

digitalWrite( )
The digitalWrite ( ) function is used to set the value of a pin as HIGH or LOW.

Where,

HIGH: It sets the value of the voltage. For the 5V board, it will set the value of 5V, while for
3.3V, it will set the value of 3.3V.

LOW: It sets the value = 0 (GND).

If we do not set the pinMode as OUTPUT, the LED may light dim.

The syntax is: digitalWrite( pin, value HIGH/LOW)

pin: We can specify the pin number or the declared variable.

Let's understand with an example.

Example:

1. digitalWrite (13, HIGH);


2. digitalWrite (13, LOW);
The HIGH will ON the LED and LOW will OFF the LED connected to pin number 13.

What is the difference between digitalRead () and digitalWrite ()?

The digitalRead () function will read the HIGH/LOW value from the digital pin, and the
digitalWrite () function is used to set the HIGH/LOW value of the digital pin.
delay ( )
The delay () function is a blocking function to pause a program from doing a task during the
specified duration in milliseconds.

For example, - delay (2000)

Where, 1 sec = 1000millisecond

Hence, it will provide a delay of 2 seconds.

Code:

1. digitalWrite (13, HIGH);


2. delay (2000);
3. digitalWrite (13, LOW);
4. delay (1000);
Here, the LED connected to pin number 13 will be ON for 2 seconds and OFF for 1 second.
The task will repeatedly execute as it is in the void loop ().

We can set the duration according to our choice or project requirements.

Example: To light the LED connected to pin number 13. We want to ON the LED for 4
seconds and OFF the LED for 1.5 seconds.

Code:

1. void setup ()
2. {
3. pinMode ( 13, OUTPUT); // to set the OUTPUT mode of pin number 13.
4. }
5. void loop ()
6. {
7. digitalWrite (13, HIGH);
8. delay (4000); // 4 seconds = 4 x 1000 milliseconds
9. digitalWrite (13, LOW);
10. delay (1500); // 1.5 seconds = 1.5 x 1000 milliseconds
11. }
Arduino Syntax and Program Flow
Syntax
Syntax in Arduino signifies the rules need to be followed for the successful uploading of the
Arduino program to the board. The syntax of Arduino is similar to the grammar in English. It
means that the rules must be followed in order to compile and run our code successfully. If
we break those rules, our computer program may compile and run, but with some bugs.

Let's understand with an example.

As we open the Arduino IDE, the display will look like the below image:

The two functions that encapsulate the pieces of code in the Arduino program are shown
below:

1. void setup ( )
2. void loop ( )

Functions
o The functions in Arduino combine many pieces of lines of code into one.
o The functions usually return a value after finishing execution. But here, the function does
not return any value due to the presence of void.
o The setup and loop function have void keyword present in front of their function name.
o The multiple lines of code that a function encapsulates are written inside curly brackets.
o Every closing curly bracket ' } ' must match the opening curly bracket '{ ' in the code.
o We can also write our own functions, which will be discussed later in this tutorial.
AD
Spaces
o Arduino ignores the white spaces and tabs before the coding statements.
o The coding statements in the code are intent (empty spacing at the starting) for the easy
reading.
o In the function definition, loop, and conditional statements, 1 intent = 2 spaces.
o The compiler of Arduino also ignores the spaces in the parentheses, commas, blank
lines, etc.
AD

Tools Tab
o The verify icon present on the tool tab only compiles the code. It is a quick method to
check that whether the syntax of our program is correct or not.
o To compile, run, and upload the code to the board, we need to click on the Upload
button.

Uses of Parentheses ( )
o It denotes the function like void setup ( ) and void loop ( ).
o The parameter's inputs to the function are enclosed within the parentheses.
o It is also used to change the order of operations in mathematical operations.

Semicolon ;
o It is the statement terminator in the C as well as C++.
o A statement is a command given to the Arduino, which instructs it to take some kind of
action. Hence, the terminator is essential to signify the end of a statement.
o We can write one or more statements in a single line, but with semicolon indicating the
end of each statement.
o The compiler will indicate an error if a semicolon is absent in any of the statements.
o It is recommended to write each statement with semicolon in a different line, which
makes the code easier to read.
o We are not required to place a semicolon after the curly braces of the setup and loop
function.
Arduino processes each statement sequentially. It executes one statement at a time before
moving to the next statement.

Program Flow
The program flow in Arduino is similar to the flowcharts. It represents the execution of a
program in order.

We recommend to draw the flowchart before writing the code. It helps us to understand the
concept of code, which makes it the coding simpler and easier.

AD
Flow Charts
A flowchart uses shapes and arrows to represent the information or sequence of actions.

An oval ellipse shows the Start of the sequence, and a square shows the action or
processes that need to be performed.

The Arduino coding process in the form of the flowchart is shown below:

Here, the processor enters our code, and the execution of code begins. After the setup, the
execution of the statement in the loop begins.

The example of the flowchart in Arduino is shown below:


Arduino Serial |Serial.begin()
Serial Communication
The serial communication is a simple scheme that uses the UART (Universal Asynchronous
Receiver/Transmitter) on the Microcontroller. It uses,

o 5V for logic 1 (high)


o 0V for logic 0 (low)
For a 3.3V board, it uses

o 3V for logic 1 (high)


o 0V for logic 0 (low)
AD

Every message sent on the UART is in the form of 8 bits or 1 byte, where 1 byte = 8 bits.

The messages sent to the computer from Arduino are sent from PIN 1 of the Arduino
board, called Tx (Transmitter). The messages being sent to the Arduino from the
computer are received on PIN 0, called Rx (Receiver).

These two pins on the Arduino UNO board look like the below image:

When we initialize the pins for serial communication in our code, we cannot use these two
pins (Rx and Tx) for any purpose. The Tx and Rx pins are also connected directly to the
computer.

The pins are connected to the serial Tx and Rx chip, which acts as a serial
to USB translator. It acts as a medium for the computer to talk to the Microcontroller.
The chip on the board looks like the below image:

The object can include any number of data members (information) and member functions
(to call actions).

The Serial.begin( ) is a part of the serial object in the Arduino. It tells the serial object to
perform initialization steps to send and receive data on the Rx and Tx (pins 1 and 0).

Let's discuss Serial.begin( ) in detail.

Arduino Mega has four serial ports. The Tx pins on the Mega board are listed below:

o 1 (TX)
o 18 (TX)
o 16 (TX)
o 14 (TX)
The Rx pins on the Mega port are listed below:

o 0 (RX)
o 19 (RX)
o 17 (RX)
o 15 (RX)
The communication with the Tx and Rx pins would cause interference and failed uploads to
the particular board.

If we require a serial port for communication, we need to use a USB-to serial adapter. It is
a mini USB connector, which converts the USB connection to the Serial RX and TX. We can
directly connect the adapter to the board.

There are five pins present on the USB-to serial adapter, including RX, TX, reset button,
and GND (Ground).

Serial.begin ( )
The serial.begin( ) sets the baud rate for serial data communication. The baud rate signifies
the data rate in bits per second.
AD

The default baud rate in Arduino is 9600 bps (bits per second). We can specify other baud
rates as well, such as 4800, 14400, 38400, 28800, etc.

The Serial.begin( ) is declared in two formats, which are shown below:

o begin( speed )
o begin( speed, config)
Where,

serial: It signifies the serial port object.

speed: It signifies the baud rate or bps (bits per second) rate. It allows long data types.

AD

config: It sets the stop, parity, and data bits.

Example 1:

1. void setup ( )
2. {
3. Serial.begin(4800);
4. }
5. void loop ( )
6. {
7. }
The serial.begin (4800 ) open the serial port and set the bits per rate to 4800. The
messages in Arduino are interchanged with the serial monitor at a rate of 4800 bits per
second.

Let's consider another example.

Example 2:

It is shown below:
Arduino Serial.print ( )
The serial.print ( ) in Arduino prints the data to the serial port. The printed data is stored in
the ASCII (American Standard Code for Information Interchange) format, which is a human-
readable text.

Each digit of a number is printed using the ASCII characters.

The printed data will be visible in the serial monitor, which is present on the right corner on
the toolbar.

The Serial.print( ) is declared in two formats, which are shown below:

o print( value )
o print( value, format)
Note: In Serial.print( ), S must be written in uppercase.

Where,

serial: It signifies the serial port object.

print: The print ( ) returns the specified number of bytes written.

value: It signifies the value to print, which includes any data type value.

format: It consists of number base, such as OCT (Octal), BIN (Binary), HEX (Hexadecimal),
etc. for the integral data types. It also specifies the number of decimal places.

Serial.print( value )
The serial.print ( ) accepts the number using the ASCII character per digit and value upto
two decimal places for floating point numbers.

Example 1:

1. Serial.print(15.452732)
Output:

15.45

It sends bytes to the printer as a single character. In Arduino, the strings and characters
using the Serial.print( ) are sent as it is.

Example 2:

1. Serial.print("Hello Arduino")
Output:

"Hello Arduino"
AD

AD

Serial.print( value, format )


It specifies the base format and gives the output according to the specified format. It
includes the formats Octal -OCT (base 8), Binary-BIN (base 2), Decimal-DEC (base 10),
and Hexadecimal-HEX (base 16).

Let's understand by few examples.

Example 1:

1. Serial.print(25, BIN)
Output:

11001

AD

It converts the decimal number 25 to binary number 11001.

Example 2:

1. Serial.print(58, HEX)
Output:

3A

It converts the decimal number 58 to hexadecimal number 3A.

Example 3:

1. Serial.print(58, OCT)
Output:

72

It converts the decimal number 58 to octal number 72.

Example 4:

1. Serial.print(25, DEC)
Output:

25
The conversion is from decimal to decimal. So, the output will be the same.

Flash Memory based strings

If we want to pass the flash memory in Serial.print ( ) based on string, we need to wrap the
function statement with F.

For example,

Serial.print( F ( "Hello Arduino") ).

Printing a Tab space

We can also print the tab in the output.

Let's consider the code below:

1. void setup ( )
2. {
3. Serial.begin ( 4800);
4. }
5. void loop ( )
6. {
7. Serial.print(" Hello Arduino" );
8. Serial.print(" \ t '');
9. }
Here, Serial.print(" \ t '') is used to print the tab in the output program.

Serial.println ( )
The Serial.println ( ) means print line, which sends the string followed by the carriage return
('\r' or ASCII 13) and newline ('\n' or ASCII 10) characters. It has a similar effect as pressing
the Enter or Return key on the keyboard when typing with the Text Editor.

The Serial.println( ) is also declared in two formats, which are shown below:

o println( value )
o println( value, format)
AD

What is the difference between Serial.print( ) and Serial.println( )?

The text written inside the open and closed parentheses in the Serial.println( ) moves in a
new line. With the help of Serial.print( ) and Serial.println( ), we can figure the order and
execution of certain things in our code.

Let's understand with an example:


Consider the below code.

1. void setup ( )
2. {
3. Serial.begin ( 4800);
4. }
5. void loop ( )
6. {
7. Serial.print(" Hello");
8. delay(1000);
9. Serial.println("Arduino"); // It will print Arduino followed by a new line.
10. delay ( 1500); // delay of 1.5 seconds between each printed line.
11. }
Click on the Upload button-> Serial monitor for the output.

In the output, the word Hello will appear followed by the word Arduino 1 second later. After
1.5 second, another line will be printed.

Output

1. Hello Arduino
2. Hello Arduino // The next line will be printed after the specified duration.
3. .
4. .
5. .
6. .
7. The output will be printed repeatedly.
Arduino Mega

The Arduino Mega board (type of Arduino board) has four serial ports. While programming
the Mega, we need to declare all the four serial ports. The baud rates of all the four serial
ports should be different.

It is shown below:

1. void setup() {
2. Serial.begin(4800);
3. Serial1.begin(28800);
4. Serial2.begin(38400);
5. Serial3.begin(9600);
6.
7. Serial.println("Serial port");
8. Serial1.println("Serial port 1");
9. Serial2.println("Serial port 2");
10. Serial3.println("Serial port 3");
11. }
12. void loop()
13. {
14. }
Serial.available( )
The Serial.available( ) function in Arduino gets the stored bytes from the serial port that are
available for reading. It is the data, which is already stored and arrived in the serial buffer.
The serial buffer in Arduino holds the 64 bytes.

Serial.available( ) function inherits from the utility class called stream. The stream is only
invoked when the function relying on it is called. The stream class is considered as the base
class for binary and character-based streams.

Let's understand with an example.

Consider the below code.

1. int arrivingdatabyte = 0; // initializing the incoming serial byte


2. void setup( )
3. {
4. Serial.begin(9600); // 9600 is the data rate in bps (bits per second).
5. }
6. void loop( ) // loop function that executes repeatedly
7. {
8. if(Serial.available( ) > 0) // It will only send data when the received data is greater than 0.
9. {
10. arrivingdatabyte = Serial.read( ); // It will read the incoming or arriving data byte
11. Serial.print("data byte received:");
12. Serial.println(arrivingdatabyte, DEC); // here, DEC means Decimal
13. }
14. }
In case of the Arduino Mega, the ports available are:

Serial1.available( )
Serial2.available( )

Serial3.available( )

Let's understand the concept of Mega with an example.

In this example, the data will be read and sent from one port to another.

It will read data from port 0 and will then send the data to port 1.

Consider the below code.

1. void setup( )
2. {
3. Serial.begin(4800);
4. Serial1.begin(4800);
5. }
6. // two if conditions will be used.
7. //In first, if the data is available in the port 0, it will send to the port 1. In second, if the data is ava
ilable in the port 1, it will send to the port 0.
8. void loop( )
9. {
10. // Now,the data will be read from port 0 and will be sent to the port 1.
11. if( Serial.available( ) )
12. {
13. int incomingdatabyte = Serial.read( );
14. Serial1.print('incomingdatabyte, byte');
15. }
16. // Now,the data will be read from port 1 and will be sent to the port 0.
17. if( Serial1.available( ) )
18. {
19. int incomingdatabyte = Serial1.read( );
20. Serial.print('incomingdatabyte, byte');
21. }
22. }
We can also check the errors in our code by compiling. For that, click on the Verify button.

The Arduino screen will look like the below image:


The Done Compiling will signify the successful compiling of the code.

Note: With the help of the Arduino board, we cannot connect the serial device to
our computer.

Arduino Serial.read( ) and Serial.write( )


Arduino Serial.read( )
The Serial.read( ) in Arduino reads the incoming serial data in the Arduino. The int data
type is used here. It returns the first data byte of the arriving serial data. It also returns -1
when no data is available on the serial port.
The syntax used in the Arduino programming is Serial.read( ),

Where,

serial: It signifies the serial port object.

The data is stored in the form of bytes, where 1 byte = 8 bits.

Let's understand with an example.

Consider the below code.

1. int arrivingdatabyte;
2. void setup( )
3. {
4. Serial.begin(9600);
5. }
6. void loop( )
7. {
8. if(Serial.available( ) > 0)
9. {
10. arrivingdatabyte = Serial.read( ); // It will read the incoming or arriving data byte
11. Serial.print("data byte received:");
12. Serial.println(arrivingdatabyte);
13. }
14. }
The above code clearly explains that the Serial.available( ) is used to get the available
number of bytes if it is greater than 0. The Serial.read( ) function will read the data from the
data byte and print a message if the data is received. The data is sent from the serial
monitor to the Arduino.

Serial.readString( )
It reads the incoming serial data from the serial buffer in the string. The String data type is
used here.
Let's understand with an example.

Consider the below code.

1. String b;
2. void setup( )
3. {
4. Serial.begin(4800);
5. }
6. void loop( )
7. {
8. while( Serial.available( ) )
9. {
10. b = Serial.readString( );
11. Serial.println(b);
12. }
13. }
The above code clearly explains that the Serial.readString( ) is used to read the serial data
into the string. The string specified here is b.

The data in the Serial function is read as a string in the above code.

How serial data is read by Serial.readString( ) and Serial.read( )?

The Serial.read( ) function reads the data in terms of bytes, while the Serial.readString( )
reads the data in the term of string.

Serial.write( )
It sends the binary data to the serial port in Arduino. The data through Serial.write is sent as
a series of bytes or a single byte. The data type is size_t.

The Serial.write( ) function will return the number of written bytes.

AD

If we want to send the digits of numbers represented by the characters, we need to use the
Serial.print( ) function instead of Serial.write( ).
The Serial.write( ) is declared in three formats, which are shown below:

o write( str )
o write( value )
o write( buffer, len)
Where,

Serial: It signifies the serial port object.

str: The str means string, which sends the data as a series of bytes.

AD

buffer: It is an array that is used to send the data as a series of bytes.

value: It sends the data to the Arduino as a single byte.

len: It signifies the number of bytes, which can be sent from the array.

Let's understand with a simple example.

Consider the below code.

1. void setup( )
2. {
3. Serial.begin(14400);
4. }
5. void loop( )
6. {
7. Serial.write(55); // the specified value is 55.
8. // Serial.write( ) send the data as a byte with this value (55).
9. int Bytestosend = Serial.write( " Arduino" );
10. // It sends the Arduino string.
11. //The length of the string is a return parameter in this function.
12. }
Arduino analogRead ( )
The analogRead( ) function reads the value from the specified analog pin present on the
particular Arduino board.

The ADC (Analog to Digital Converter) on the Arduino board is a multichannel converter. It
maps the input voltage and the operating voltage between the values 0 and 1023. The
operating voltage can be 5V or 3.3V.

The values from 0 to 1023 are the integer values. It can also be written as 0 to (2^10) -1.

The time duration to read an analog input signal on the boards (UNO, Mega, Mini, and
Nano) is about 100 microseconds or 0.0001 seconds.

Hence, the maximum reading rate of analog input is about 10000 times per second.

Let's discuss operating voltage and resolution of some Arduino boards.

o The Operating voltage of Arduino UNO, Mini, Mega, Nano, Leonardo, and Micro
is 5V, and resolution is 10 bits.
o The Operating voltage of MKR family boards, Arduino Due, and Zero is 3 V, and
resolution is 12 bits.

Changing the input voltage and resolution


o On a particular board, we can change the input voltage using the analogReference( )
function.
AD

analogReference( )

The reference voltage used for the analog input is configured by the analogReference( ).

The syntax is:

1. analogReference (type)
Note: The external reference voltage on the AREF pin should not exceed greater
than 5V or less than 0V. We need to set the analog Reference as External while
working on the AREF pin.
Otherwise, it can damage the microcontroller present on the Arduino board.

o We can change the resolution only for the MKR Family, Zero, and Due board using the
analogReadResolution( ) function.
analogReadResolution( )

The MKR Family, Zero, and Due have the ADC resolution of 12 bits.

The analogReadResolution( ) will return the integer values between 0 and 4095 from the
analogRead( ) function.

The syntax is:

1. analogReadResolution (bits)
where,

bits: It signifies the resolution bits returned by the analogRead( ) function. We can set the
value of bits between 1 and 32.

Note: If the resolution bits higher than the board capabilities are specified, the
Arduino will pad the extra bits with zeroes.
For example, analogReadResolution (14)
The above function will give a 14-bit approximated number with the first two 12
bits (that includes ADC reading) and the last two padded bits.
AD

Syntax of analogRead ( )
The syntax is:

1. analogRead(pin)
where,

AD

pin: It includes the name of the particular analog pin to read from.

The data type is int.


A not-connected analog pin can also return some value. Such value depends on the
position of our hand on the board and other nearby analog inputs.

Code Example
Let's understand the concept of analogRead with an example.

Consider the below code:

AD

1. // Below is an example for the better understanding of the analogRead( ) function


2. int AnaPin = A3; // Analog pin A3 is specified here
3. int value = 0; // variable declared to store the value read
4. void setup()
5. {
6. Serial.begin(9600); // It sets the serial rate at bps
7. }
8. void loop()
9. {
10. value = analogRead(AnaPin); // It reads the input pin
11. Serial.println(value);
12. }
The above code reads the voltage from the specified analog pin (AnaPin) and displays it.

Arduino Functions
The functions allow a programmer to divide a specific code into various sections, and each
section performs a particular task. The functions are created to perform a task multiple
times in a program.

The function is a type of procedure that returns the area of code from which it is called.

For example, to repeat a task multiple times in code, we can use the same set of
statements every time the task is performed.

Advantages of using Functions


Let's discuss some advantages of using functions in programming, which are listed below:

o It increases the readability of the code.


o It conceives and organizes the program.
o It reduces the chances of errors.
o It makes the program compact and small.
o It avoids the repetition of the set of statements or codes.
o It allows us to divide a complex code or program into a simpler one.
o The modification becomes easier with the help of functions in a program.
The Arduino has two common functions setup() and loop(), which are called automatically
in the background. The code to be executed is written inside the curly braces within these
functions.

void setup() - It includes the initial part of the code, which is executed only once. It is called
as the preparation block.

void loop() - It includes the statements, which are executed repeatedly. It is called
the execution block.

But sometimes, we need to write our own functions.

Let's start writing the functions.

AD

Function Declaration
The method to declare a function is listed below:

o Function return type


AD

We need a return type for a function. For example, we can store the return value of a
function in a variable.

We can use any data type as a return type, such as float, char, etc.

o Function name
It consists of a name specified to the function. It represents the real body of the function.

o Function parameter
It includes the parameters passed to the function. The parameters are defined as the
special variables, which are used to pass data to a function.

The function must be followed by parentheses ( ) and the semicolon ;

The actual data passed to the function is termed as an argument.

Let's understand with some examples.

AD
Example 1:
Consider the below image:

Example 2: Here, we will add two numbers.


Consider the below code:

1. void setup()
2. {
3. Serial.begin(9600);
4. }
5. void loop() {
6. int a = 5; // initialization of values to the variables a and b
7. int b = 4;
8. int c;
9. c = myAddfunction(a, b); // c will now contains the value 9
10. Serial.println(c); // to print the resulted value
11. delay(1000); // time delay of 1 second or 1000 milliseconds
12. }
13. int myAddfunction(int i, int j)
14. {
15. int sum;
16. sum = i + j;
17. return sum;
18. }
Similarly, we can perform arithmetic operations using the above concept.
Example 3:
Here, we will create a function that determines if a number is even or odd.

Consider the below code.

AD

1. int a= 0;
2. int b;
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. b = Evenfunction(a); // we can store the function return value in variable b
10. Serial.print(a);
11. Serial.print(" : "); // to separate even or odd text
12. if (b==1)
13. {
14. Serial.println( " Number is even");
15. }
16. else
17. {
18. Serial.println("Number is odd");
19. }
20.
21. a++; // the function will increment and will again run
22. delay(1000);
23. }
24.
25. int Evenfunction(int d)
26. {
27. if (d% 2==0)
28. {
29. return 1;
30. }
31. else
32. {
33. return 0;
34. }
35. }
Output:

The output is shown below:


Arduino Data Types
The data types are used to identify the types of data and the associated functions for
handling the data. It is used for declaring functions and variables, which determines the bit
pattern and the storage space.

The data types that we will use in the Arduino are listed below:

o void Data Type


o int Data Type
o Char Data Type
o Float Data Type
o Double Data Type
o Unsigned int Data Type
o short Data Type
o long Data Type
o Unsigned long Data Type
o byte data type
o word data type
void Data Type
The void data type specifies the empty set of values and only used to declare the functions.
It is used as the return type for the functions that do not return any value.

Let's understand with an example in Arduino.

Consider the below code.

1. int a = 3;
2. void setup( )
3. {
4. . //
5. }
6. void loop ( )
7. {
8. .
9. .
10. }

Int Data Type


The integer data types are the whole numbers like 5, -6, 10, -123, etc. They do not have
any fractional part. The integer data types are represented by int. It is considered as the
primary data type to store the numbers.

The size of int is 2 bytes ( 16 bits).

Minimal range: -32768 to 32767 or - (2^ 15) to ((2 ^ 15) - 1)

In the ATmega and Arduino UNO boards, the int data types store the value of 2 bytes.

On the boards like Arduino Zero and MKR1000 (SAMD boards), and Arduino Due, the int
data type stores the value of 4 bytes or 32 bits. The Minimal range in such case would be -
(2^ 31) to ((2 ^ 31) - 1) or -2,147,483,648 to 2,147,483,647.

The negative numbers are stored in the form of 2's complement, where the sign bit or the
highest bit is flagged as the negative number.

The syntax is used as:

1. int var = val;


where,

var= variable

value = the value assigned to the variable

For example,
1. int a;
2. int b = 3;
Any variable or identifier becomes an integer variable and can hold only integer values.

AD

Let's understand with an example in Arduino.

Consider the below code.

1. int Sum = 0;
2. void setup( )
3. {
4. Serial.begin(9600);
5. }
6. void loop ( )
7. {
8. Sum++; // on every loop, it adds 1 to the Sum int
9. Serial.println ( Sum); // it prints the current state of the Sum variable
10. delay(1500); // delay of 1.5 seconds
11. }
AD

Char Data Type


The char datatype can store any number of character set. An identifier declared as the char
becomes a character variable. The literals are written inside a single quote.

The char type is often said to be an integer type. It is because, symbols, letters, etc., are
represented in memory by associated number codes and that are only integers.

The size of character data type is minimum of 8 bits. We can use the byte data type for an
unsigned char data type of 8 bits or 1 byte.

AD

For example, character ' A ' has the ASCII value of 65.

If we specify, ' A ' + 2, it will have the ASCII value of 67.

The syntax is:

1. char var = val;


where,

var= variable

val = The value assigned to the variable.

Let's understand with an example.


Consider the below code.

1. char myvariable = ' B ';


2. char myvariable = 66 ; // both the value are equivalent
The ASCII table is shown below:

Float Data Type


A number having the fractional part and a decimal part is considered as a floating-point
number. For example, 4.567 is a floating-point number. The number 13 is an integer, while
13.0 is a floating-point number. Due to their greater resolution, fractional numbers are used
to approximate the contiguous and analog values.

Floating point numbers can also be written in the exponent form. The numbers can be as
large as 3.4028235E+38 and as small as -3.4028235E+38. The size of float data types is 4
bytes or 32 bits.

The syntax is:


1. float var = val;
where,

var= variable

val = The value assigned to the variable

Let's understand with an example.

Consider the below code.

1. int a ;
2. int b ;
3. float c ;
4. void setup ( )
5. {
6. Serial.begin (9600);
7. }
8. void loop ( )
9. {
10. a = 3 ;
11. b = a/2 ; // b is an integer. It cannot hold fractions. The output will be 1.
12. c = (float) a / 2.0 ; // c now contains 1.5.
13. // Here, we have to use 2.0 instead of 2.
14. }

Note: We need to add a decimal point to a number. Otherwise, it will be


considered as an integer. For example, 14.0 is considered as a float number, while
14 is an integer.
The floating-point numbers can also be converted to integers. For example,

1. float a = 3.6 ;
2. int b = a + 0.6 ; // output = 4

Double Data Type


The double data type is also used for handling the decimal or floating-point numbers. It
occupies twice as much memory as float. It stores floating point numbers with larger
precision and range. It stands for double precision floating point numbers.

It occupies 4 bytes in ATmega and UNO boards, while 8 bytes on Arduino Due.

The syntax is:

1. double var = val;


where,
var= variable

val = The value assigned to the variable

AD

Unsigned int Data Type


The unsigned int stores the value upto 2 bytes or 16 bits. It stores only positive values. The
range of unsigned int data type is from 0 to 65,535 or 0 to ((2 ^ 16) - 1).

Arduino Due stores the unsigned data value of 4 bytes or 32-bits.

The difference between Unsigned and signed data type is the sign bit. The int type in
Arduino is the signed int. In a 16-bit number, 15 bits are interpreted with the 2's
complement, while the high bit is interpreted as the positive or negative number. If the high
bit is '1', it is considered as a negative number.

The syntax is:

1. unsigned int var = val;


where,

var= variable

val = The value assigned to the variable

For example,

1. unsigned int pinofLED = 8;


AD

short Data Type


The short is an integer data type that stores two bytes or 16-bit of data.

The range of short data types is from -32768 to 32767 or - (2^ 15) to ((2 ^ 15) - 1). The ARM
and ATmega based Arduino's usually stores the data value of 2 bytes.

The syntax is:

1. short var = val;


where,

var= variable

val = the value assigned to the variable

For example,
1. short pinofLED = 8 ;
AD

long Data Type


The long data types are considered as the extended size variables, which store 4 bytes (32
-bits). The size ranges from -2,147,483,648 to 2,147,483,647.

While using integer numbers, at least one of the numbers should be followed by L, which
forces the number to be a long data type.

The syntax is:

1. long var = val;


where,

var= variable

val = The value assigned to the variable

For example,

1. long speed = 186000L;

Unsigned long Data Type


The unsigned long data types are also considered as the extended size variables, which
store 4 bytes (32 -bits). It does not store negative numbers like other unsigned data types,
which makes their size ranges from 0 to 4,294,967,295 or (2^32 - 1).

The syntax is:

1. unsigned long var = val;


where,

var= variable

val = The value assigned to the variable

For example

1. unsigned long currenTtime;


AD

byte
1 byte = 8 bits.

It is considered as an unsigned number, which stores values from 0 to 255.


The syntax is:

1. byte var = val;


where,

var= variable

value = the value assigned to the variable

For example,

1. byte c = 20;

word
It is considered as an unsigned number of 16 bits or 2 bytes, which stores values from 0 to
65535.

The syntax is:

1. word var = val;


where,

var= variable

val = The value assigned to the variable

For example,

1. word c = 2000;

Arduino Variables
The variables are defined as the place to store the data and values. It consists of a name,
value, and type.

The variables can belong to any data type such as int, float, char, etc. Consider the url -
Arduino data types for detailed information.

Consider the below example:

1. int pin = 8;
Here, the int data type is used to create a variable named pin that stores the value 8. It also
means that value 8 is initialized to the variable pin.

We can modify the name of the variable according to our choice. For example,

The above example can also be written as:

1. int LEDpin = 8;
Here, the variable name is LEDpin.

We can refer the declared variable further in our program or code.

For example,

1. pinMode(LEDpin, OUTPUT);
Here, the value stored (8) in the declared variable (LEDpin) will be passed to the pinMode()
function.

If we have not declared the variable, the value can also be directly passed to the function.

For example:

1. pinMode( 8, OUTPUT);

Advantages of Variables
The advantages of the variables are listed below:

o We can use a variable many times in a program.


o The variables can represent integers, strings, characters, etc.
o It increases the flexibility of the program.
o We can easily modify the variables. For example, if we want to change the value of
variable LEDpin from 8 to 13, we need to change the only point in the code.
o We can specify any name for a variable. For example, greenpin, bluePIN, REDpin, etc.
AD

How can we change the value of a variable in Arduino?


The value of a variable can be changed using the assignment operator ( equal = sign). But
we need to declare a variable before assigning the value.

If we directly specify the value as:

1. pin = 7;
We will get an error that pin has not declared.

We can easily change the variables by copying its value to another variable.

AD

For example,

1. int LEDpin = 7;
2. int pin1 = LEDpin;
3. LEDpin = 13;
The LEDpin now contains the value 13 instead of 7. But, value of pin1 is still 7.

Let's understand with an example.

Consider the below code.

1. void setup()
2. {
3. Serial.begin(9600);
4. int pinLED = 7;
5. Serial.println(pinLED); // value 7 will be printed
6. int pin1 = pinLED;
7. pinLED = 13;
8. Serial.println(pinLED); // value is now changed
9. // now, value 13 will be printed
10. }
11. void loop()
12. {
13. }
Output:

AD

We can notice in the output that the value of LEDpin is changed from 7 to 13. Similarly, we
can change the values of variables.
Variables Scope
It means that in how many ways the variables can be declared.

The variables can be declared in two ways in Arduino, which are listed below:

o Local variables
o Global variables
AD

Local Variables
The local variables are declared within the function. The variables have scope only within
the function. These variables can be used only by the statements that lie within that
function.

For example,

1. void setup()
2. {
3. Serial.begin(9600);
4. }
5. void loop()
6. {
7. int x = 3;
8. int b = 4;
9. int sum = 0;
10. sum = x + b;
11. Serial.println(sum);
12. }

Global Variables
The global variables can be accessed anywhere in the program. The global variable is
declared outside the setup() and loop() function.

For example,

Consider the below code.

1. int LEDpin = 8;
2. void setup()
3. {
4. pinMode(LEDpin, OUTPUT);
5. }
6. void loop()
7. {
8. digitalWrite(LEDpin, HIGH);
9. }
We can notice that the LEDpin is used both in the loop() and setup() functions.

The value is used in both functions, so, changing the value in one function will reflect in the
other. For example,

1. int LEDpin = 8;
2. void setup()
3. {
4. LEDpin = 13;
5. pinMode(LEDpin, OUTPUT);
6. }
7. void loop()
8. {
9. digitalWrite(LEDpin, HIGH);
10. }
Here, the value 13 will be passed to the digitalWrite() function.

What are constants?


The constants in Arduino are defined as the predefined expressions. It makes the code
easy to read.

The constants in Arduino are defined as:

Logical level Constants


The logical level constants are true or false.

The value of true and false are defined as 1 and 0. Any non-zero integer is determined as
true in terms of Boolean language. The true and false constants are type in lowercase
rather than uppercase (such as HIGH, LOW, etc.).

AD

Pin level Constants


The digital pins can take two value HIGH or LOW.

In Arduino, the pin is configured as INPUT or OUTPUT using the pinMode() function. The
pin is further made HIGH or LOW using the digitalWrite() function.

HIGH
The board includes two types of voltage pins to provide HIGH value, which are listed below:

o 5V
o 3V
Some boards include only 5V pins, while some include 3.3V.

Some boards consist of both 5V and 3.3V pins. For example, Arduino UNO R3.

The pin configured as HIGH is set at either 5V or 3.3V.

The pins are configured at the 5V or 3.3V depending on:

o for voltage > 3.0V (presented at 5V pin)


o for voltage > 2.0V (presented at 3.3V pin)
AD

LOW
The pin configured as LOW is set at 0 Volts.

The pins are configured at the 5V or 3.3V depending on:

o for voltage < 1.5V (presented at 5V pin)


o for voltage < 1V (presented at 3.3V pin)

LED_BUILTIN Constant
The Arduino boards have built-in LED connected in series with the resistor. The particular
pin number is defined with the constant name called LED_BUILTIN.

Most Arduino boards have the LED_BUILTIN connected to Pin number 13.

Constant Keyword
The name const represents the constant keyword. It modifies the behavior of the variables
in our program. It further makes the variable as 'read-only'.

The variable will remain the same as other variables, but its value cannot be changed.

AD

It means we cannot modify the constant. For example,

1. const int a =2;


2. //....
3. a = 7; // illegal - we cannot write to or modify a constant
The const keyword is considered superior compared to the #define keyword because it
obeys the rules of the variable scope.

For example,

Consider the below code:

1. const float x = 5.68;


2. float y;
3. void setup()
4. {
5. Serial.begin(9600);
6. y = x * 2; // we can also use constants in math
7. Serial.println(y);
8. }
9. void loop()
10. {
11. // ....
Output: 11.36

AD

Note: We can either use const or #define in the case of strings and numeric
constants. But we can only use const for arrays.

#define
The #define in Arduino is used to give a name to the constant value. It does not take any
memory space on the chip.

At the compile time, the compiler will replace the predefined value in the program to the
constants with the defined value.

The syntax is:

1. #define nameOFconstant value


where,

nameOFconstant: It is the name of the macro or constant to define

value: It includes the value assigned to the constant or macro.

For example,

1. #define LEDpin 12
2. // It is the correct representation of #define
Note: The #define does not require any semicolon. Hence, we do not need to
specify any semicolon after the #define. Otherwise, the compiler will show errors.
The incorrect declarations of #define can be:

1. #define LEDpin = 12
2. #define LEDpin 12;
3. // both of the above statements are incorrect

Arduino Operators
The operators are widely used in Arduino programming from basics to advanced levels. It
plays a crucial role in every programming concept like C, C++, Java, etc.

The operators are used to solve logical and mathematical problems. For example, to
calculate the temperature given by the sensor based on some analog voltage.

The types of Operators classified in Arduino are:

1. Arithmetic Operators
2. Compound Operators
3. Boolean Operators
4. Comparison Operators
5. Bitwise Operators

Arithmetic Operators
There are six basic operators responsible for performing mathematical operations in
Arduino, which are listed below:

o Assignment Operator ( = )
The Assignment operator in Arduino is used to set the variable's value. It is quite different
from the equal symbol (=) normally used in mathematics.

o Addition ( + )
AD

The addition operator is used for the addition of two numbers. For example, P + Q.

o Subtraction ( - )
Subtraction is used to subtract one value from the another. For example, P - Q.
o Multiplication ( * )
The multiplication is used to multiply two numbers. For example, P * Q.

o Division ( / )
The division is used to determine the result of one number divided with another. For
example, P/Q.

o Modulo ( % )
The Modulo operator is used to calculate the remainder after the division of one number by
another number.

Most of the operators are similar to the usual operator used in mathematics.

Let's understand the operators with the help of two examples.

Example 1:

Consider the below code.

1. int b;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. b = 5 + 2;
9. Serial.println(b);
10. }
In the above code, we have assigned the result of the addition of two numbers to b before
printing it to the console.

For output, click on the Upload and Serial Monitor button present on the toolbar.

Output: 7

AD

Example 2:

Consider the below code:

1. int d;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. d = 5 - 2;
9. Serial.println(d);
10. d = d + 3;
11. Serial.println(d);
12. }
Here, d= d +3 is not operated as a usual mathematical operation. It is the assignment
operator where right of the function is evaluated first and is assigned to the left of the equal
sign.

Let's consider the below image for better understanding.

Output:

AD

3
6
Similarly, we can perform multiplication, modulo, and division. The int variable will store the
integer values. For example, 20/3 = 6.

If we want decimal values to be printed, we need to use the float instead of int.

For example,

Consider the below code:

1. int b;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. b = 20.0 / 3; // decimal value is used to force the compiler to print decimal value.
9. Serial.println(b);
10. }
Output: 6.66

AD

Order of mathematical operations


Let's understand the order of operations considered by the Arduino while performing
calculation:

1. Parentheses ( )
2. Multiplication, division, and modulo
3. Addition and subtraction

If there are multiple operations next to each other, they will be computed from left to right.

Let's understand with an example.

Consider the below code:

1. int c;
2. void setup ( )
3. {
4. Serial.begin( 9600 );
5. }
6. void loop ( )
7. {
8. c = 2 * 3 / (2 + 1) + 4;
9. Serial.println(c);
10. }
Output:

6
Let's understand how the above output occurred. Consider the below image:
Compound Operators
The compound operators perform two or more calculations at once.

The result of the right operand is assigned to the left operand, as already discussed above.
The same condition will apply to all the compound operators, which are listed below:

Let's consider a variable b.

o b++
Here, b = b + 1. It is called the increment operator.

o b+=
For example, b + = 4. It means, b = b+ 4.

o b--
Here, b = b - 1. It is called as the decrement operator.

o b-=
For example, b - = 3. It means, b = b - 3.

o b*=
For example, b * = 6. It means, b = b * 6.
o b/=
For example, b / = 5. It means, b = b / 5.

o b%=
For example, b % = 2. It means, b = b % 2.

Now, let's use the above operators with two variables, b and c.

o b + = c ( b = b + c)
o b - = c ( b = b - c)
o b * = c ( b = b * c)
o b / = c ( b = b / c)
o b % = c ( b = b % c)
We can specify any variable instead of b and c.

Boolean Operators
The Boolean Operators are NOT ( ! ), Logical AND ( & & ), and Logical OR ( | | ).

Let's discuss the above operators in detail.

o Logical AND ( & & )


The result of the condition is true if both the operands in the condition are true.

Consider the below example:

1. if ( a = = b & & b = = c )
Above statement is true if both conditions are true. If any of the conditions is false, the
statement will be false.

o Logical OR ( | | )
The result of the condition is true, if either of the variables in the condition is true.

Consider the below example.

1. if ( a > 0 | | b > 0 )
The above statement is true, if either of the above condition ( a> 0 or b > 0 ) is true.

o NOT ( ! )
It is used to reverse the logical state of the operand.

For example, a ! = 2.

The NOT operator returns the value 1 or TRUE when the specified operand is FALSE. It
also reverses the value of the specified expression.
Comparison Operators
The comparison operators are used to compare the value of one variable with the other.

The comparison operators are listed below:

o less than ( < )


The less than operator checks that the value of the left operand is less than the right
operand. The statement is true if the condition is satisfied.

Consider the below code.

1. int b;
2. int c ;
3. void setup ( )
4. {
5. Serial.begin( 9600 );
6. }
7. void loop ( )
8. {
9. b = 3;
10. c = 5;
11. if ( b < 4 )
12. Serial.println(b);
13. if ( c < 4)
14. Serial.println( c);
15. }
Output: 3

In the above code, if any of the two statement is correct, the corresponding value of the
variable will be printed. Here, only first condition is correct. Hence, the value of b will be
printed.

o greater than ( > )


The less than operator checks that the value of the left side of a statement is greater than
the right side. The statement is true if the condition is satisfied.

For example, a > b.

If a is greater than b, the condition is true, else false.

o equal to ( = = )
It checks the value of two operands. If the values are equal, the condition is satisfied.

For example, a = = b.

The above statement is used to check if the value of a is equal to b or not.


o not equal to ( ! = )
It checks the value of two specified variables. If the values are not equal, the condition will
be correct and satisfied.

For example, a ! = b.

o less than or equal to ( < = )


The less or equal than operator checks that the value of left side of a statement is less or
equal to the value on right side. The statement is true if either of the condition is satisfied.

For example, a < = b

It checks the value of a is less or equal than b.

o greater than or equal to ( > = )


The greater or equal than operator checks that the value of the left side of a statement is
greater or equal to the value on the right side of that statement. The statement is true if the
condition is satisfied.

For example, a > = b

It checks the value of a is greater or equal than b. If either of the condition satisfies, the
statement is true.

Bitwise Operators
The Bitwise operators operate at the binary level. These operators are quite easy to use.

There are various bitwise operators. Some of the popular operators are listed below:

o bitwise NOT ( ~ )
The bitwise NOT operator acts as a complement for reversing the bits.

For example, if b = 1, the NOT operator will make the value of b = 0.

Let's understand with another example.

1. 0 0 1 1 // Input or operand 1 ( decimal value 3)


2. 1 1 0 0 // Output ( reverses the input bits ) decimal value is 12

o bitwise XOR ( ^ )
The output is 0 if both the inputs are same, and it is 1 if the two input bits are different.

For example,

For example,
1. 1 0 0 1 // input 1 or operand 1
2. 0 1 0 1 // input 2
3. 1 1 0 0 // Output ( resultant - XOR)

o bitwise OR ( | )
The output is 0 if both of the inputs in the OR operation are 0. Otherwise, the output is 1.
The two input patterns are of 4 bits.

For example,

1. 1 1 0 0 // input 1 or operand 1
2. 0 0 0 1 // input 2
3. 1 1 0 1 // Output ( resultant - OR)

o bitwise AND ( & )


The output is 1 if both the inputs in the AND operation are 1. Otherwise, the output is 0. The
two input patterns are of 4 bits.

For example,

1. 1 1 0 0 // input 1 or operand 1
2. 0 1 0 1 // input 2
3. 0 1 0 0 // Output ( resultant - AND)

o bitwise left shift ( < < )


The left operator is shifted by the number of bits defined by the right operator.

o bitwise right shift ( > > )


The right operator is shifted by the number of bits defined by the left operator.

Arduino Array
What are Arrays?
The arrays are defined as the data structures that allow multiple values to be grouped
together in a simple way. This is an easily access method.

The array is normally built from the data types like integer, reals, characters, and
boolean. It refers to a named list of finite number (n) of similar data elements.
The set of consecutive numbers usually represent the elements in the array, which are 0, 1,
2, 3, 4, 5, 6,.......n.

For example, if the name of an array of 5 elements is AR, the elements will be referenced
as shown below:

1. AR[0], AR[1], AR[2], AR[3], and AR[4]

Arrays in Arduino
The array in Arduino is declared with the integer data type.

It is also defined as the collection of variables, which is acquired with an index number.

The array is represented as:

We can specify any name according to our choice. The array name is the individual name of
an element.

AD

Array Declaration
There are different methods to declare an array in Arduino, which are listed below:

o We can declare the array without specifying the size.


For example,

1. int myarray[ ] = { 1, 4, 6, 7 } ;

o We can declare the array without initializing its elements.


AD

For example,

1. int myarray[ 5];


o We can declare the array by initializing the size and elements.
1. int myarray[ 8] = { 1, 4, 7, 9, 3, 2 , 4};
Features of Array

o The elements of the array can be characters, negative numbers, etc.


For example,

1. int myarray[ 4 ] = { 1, -3, 4};


2. char myarray[ 6] = " Hi " ;

o The size of the array should not be less than the number of elements. For example,
int myarray[5 ] = { 1, 4, 6, 7 } ; can be written as int myarray[8 ] = { 1, 4, 6, 7 } ;

But, it cannot be written as int myarray[ 2] = { 1, 4, 6, 7 } ;

Let's understand with an example.

Consider the below code in Arduino IDE.

AD

Let's specify the array as: int myarray[5 ] = { 1, 4, 6, 7 } ;

The code will successfully compile, as shown below:

Now, if we specify the array as: int myarray[ 2] = { 1, 4, 6, 7 } ;

The code will display errors, as shown below:


o The total elements, while specifying the char type should be (n - 1), where n is the size
of the array. It is because one element is required to hold the null character in the array.
For example,

AD

Let's specify the array as char abc[8 ] = " Arduino";


Access of array in Arduino
The array in Arduino has zero index. It means that the first element of the array is indexed
as 0. For example,

1. myvalue[0] = = 1, myvalue[1] = = 2, . . . .
Example 1:

Let's take an array (ARarduino) of 6 elements. The elements of the array are shown below:

ARarduino[0], ARarduino[1], ARarduino[2], ARarduino[3], ARarduino[4],

and ARarduino[5].

The last element of the array is ARarduino[5].

The last element of the array will be n-1, where n is the declared size of an array.

Consider the below code.

1. ARarduino[6] = { 1, 4, 7, 6, 11, 15};


2. // ARarduino[4] contains value 11
3. // ARarduino[5] contains value 15
4. //ARarduino[6] is invalid

Arithmetic operations on Array


Let's understand the operations carried on the array.

Example 1: Sum

We can also calculate the sum of elements within an array.

Let's consider an array (AR) with 4 elements. The elements are: AR[0], AR[1],
AR[2], and AR[3].

To calculate the sum of the first two elements:

1. Serial.print( AR[0] + AR[1] );


The sum of values assigned to the elements within an array will be printed.

Example 2: Division

We will divide the value assigned to the element AR[4] with 2. The resulting value will be
assigned to the variable 'z.' Consider the below code:

1. z = AR[4] / 2;
2. Serial.println ( x );
The result will be printed.

We need to be careful while assigning value to the array. The index number greater than
the size of the array may yield invalid data. Such data is saved to random memory
locations, which can cause the program malfunction or a difficult bug to find.

Note: C++ does not check the legally bound size of the declared array, while
JAVA and BASIC do check.
The syntax to assign a value to an array is specified as:

1. myArray[0] = 5;
2. // we can assign any value depending on the requirements.
The syntax to retrieve a value from an array is specified as:

Example of project: We will also discuss a project to light LED using arrays in the Basic
projects -> Blinking various LEDs using Arrays.

Loop Arrays
We can also use arrays inside the loop. For each element of an array, the loop counter acts
as an index element for that array.

Let's understand with an example.

In this example, the element over the serial port will be printed.

The code is given below:

1. for (byte i = 0; i < 6; i = i + +) // here, i++ can also be written as i+1


2. {
3. Serial.println(myArray[i]);
4. }
AD

Code Examples
Let's understand arrays with some examples.

Example 1: Printing the sum of all elements


Consider the below code:

1. const int sizeOFarray = 5; // constant variable indicating size of array


2. int b[sizeOFarray] = {10, 20, 30, 40, 50}; // five values initialized to five elements of an array
3. int sum = 0;
4.
5. void setup ()
6. {
7. Serial.begin(9600);
8. }
9. void loop ()
10. {
11. // sum of array b
12. for ( int i = 0; i < sizeOFarray; i++ )
13. sum += b[ i ]; // here, sum = sum + b[i]
14. Serial.print('Sum of total elements of an array:') ;
15. Serial.print(sum) ; // It will print the sum of all elements of an array
16. }
Output

Sum of total elements of an array: 150


In the above code, we have used the const variable. The compiler reserves the memory
in Arduino. We need to use the const integer greater than zero. For detail- go to the
URL Arduino Variables.

AD

Example 1: Average of the elements of an array


Consider the below code:

1. const int sizeOFarray = 5; // constant variable indicating size of array


2. int b[sizeOFarray] = {10, 30, 40, 55, 65}; // five values initialized to five elements of an array
3. int sum = 0;
4. int average = 0;
5.
6. void setup ()
7. {
8. Serial.begin(9600);
9. }
10. void loop () {
11. // sum of array b
12. for ( int i = 0; i < sizeOFarray; i++ )
13. sum += b[ i ]; // here, sum = sum + b[i]
14. average = sum/5;
15. Serial.print('Average of the elements of the array:') ;
16. Serial.println(average) ; // It will print the average of all elements of an array
17. // there are 5 elements. So, the average will be divided by 5.
18. }
Output

Average of the elements of the array:


40
Arduino Delay
Here, Arduino Delay specifies the delay( ) function used in the Arduino programming. Let's
discuss the delay( ) function in detail.

delay( ) function
The delay( ) function pauses the program or task for a specified duration of time. The time is
specified inside the open and closed parentheses in milliseconds.

Where,

1 second = 1000 milliseconds

Example 1:

delay(500)

Here, the specified time is 0.5 seconds.

It is shown below:

The program waits for a specified duration before proceeding onto the next line of the code.
The delay( ) function allows the unsigned long data type in the code.

We can create many sketches using the short and long delays depending on the
requirements in the project. It does not disable any interrupts. But, the delay( ) function has
some drawbacks.

The Drawback of using delay( ) in the sketch


The delay( ) cease (stops) the other activities, such as manipulation of pins on the board,
mathematical calculations, reading of other sensors during the delay function. The
programmers usually avoid delay( ) of more than 10 seconds in the sketch.

Let's understand the delay() function with the help of two examples.

Example 1:

Consider the below code.

1. int LEDlightPin = 8; // PIN 8 of the Arduino board initialized to the LED


2. // We can specify the variable according to our choice.
3. // For example, int PINonboard= 8
4. void setup( )
5. {
6. pinMode( LEDlightPin, OUTPUT) // the digital pin on board is set as the Output.
7. }
8. void loop( )
9. {
10. digitalWrite(LEDlightPin, HIGH);
11. delay(1500); // The LED will light/ON for 1.5 seconds = 1500 milliseconds
12. digitalWrite(LEDlightPin, LOW);
13. delay(500); // The LED will dim/OFF for 0.5 seconds = 0.5x1000 = 500 milliseconds
14. //We can modify the time duration accoordingly.
15. }
Example 2:

Consider the below code:

1. void setup ( )
2. {
3. Serial.begin ( 4800); //opens the serial port and set the bits per rate to 4800
4. }
5. void loop ( )
6. {
7. Serial.print(" Welcome");
8. delay(1000);
9. Serial.println("to delay"); // It will print 'to delay' followed by a new line.
10. delay ( 500); // delay of 0.5 seconds between each printed line.
11. }
In the output, the word Welcome will appear followed by the word to delay 1 second later.
After 0.5 seconds, another line will be printed.

AD

Output:

Welcome to delay
Welcome to delay

The output will be printed repeatedly.

Arduino If statement
The if ( ) statement is the conditional statement, which is the basis for all types of
programming languages.

If the condition in the code is true, the corresponding task or function is performed
accordingly. It returns one value if the condition in a program is true. It further returns
another value if the condition is false.

It means that if ( ) statement checks for the condition and then executes a statement or a
set of statements.

Let's understand the concept with the help of a flow chart.


It clearly explains the process of execution of a statement. If the condition is False, it comes
out of the if ( ) statement. If the condition is true, the function is performed.

The if ( ) statement is written as:

1. if ( condition)
2. {
3. // include statements
4. // if the condition is true
5. // then performs the function or task specified inside the curly braces
6. }
Here,

condition = It includes the boolean expressions, that can be true or false.

We can also use one or more operators inside the parentheses.

The comparison operators that can be used as a condition inside the parentheses are listed
below:

o a ! = b ( a not equal to b )
o a < b ( a less than b )
o a > b ( a greater than b )
o a = = b ( a equal to b )
o a < = b ( a less than or equal to b )
o a > = b ( a greater than or equal to b )
where,
a and b are the variables.

Code Examples
Let's understand with the help of two coding examples.

Example 1:

Consider the below code.

1. int a = 6; // initiaization of values to variables a and b


2. int b = 4;
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. if (a > b )
10. {
11. Serial.println( " a is greater than b ");
12. }
13. if (b > a )
14. {
15. Serial.println( " b is greater than a ");
16. }
17. }
Output: a is greater than b

The code shows the initialization of values to the two variables a and b. In this example, the
first condition is True. Hence the corresponding information is printed.

AD

Example 2:

Consider the below code.

1. const int LED1 = 2;


2. const int LED2 = 13;
3. int x = 80 ;
4. void setup ( )
5. {
6. Serial.begin( 9600 );
7. pinMode ( LED1, OUTPUT);
8. pinMode ( LED2, OUTPUT);
9. }
10. void loop ( )
11. {
12. if ( x > 100 )
13. {
14. digitalWrite(LED1, HIGH);
15. delay (500);
16. }
17. if ( x < 100 )
18. {
19. digitalWrite(LED2, HIGH);
20. delay (500);
21. }
22. }
The example is of two LEDs.

In the above example, we have initialized the value of x. Since the value of x is less than
100, the second condition is true. Hence, LED2 will light up.

If the value of x is greater than 100, LED1 will light.

AD

Similarly, we can use the if statement according to our requirements.

Note: We should be careful while using the = (equal) sign.


For example, x = 5. It is the assignment operator, where value 5 will be assigned
to the variable x. Instead, we need to use x = = 5, as it is a comparison operator.

Arduino if-else and else-if


The else and else-if both are used after specifying the if statement. It allows multiple
conditions to be grouped.

If else
The if-else condition includes if ( ) statement and else ( ) statement. The condition in the
else statement is executed if the result of the If ( ) statement is false.

The flowchart is shown below:


Let's understand with an example.

1. if (condition)
2. {
3. // statements
4. }
5. else
6. {
7. //statements
8. }
The else( ) statement can also include other if statements. Due to this, we can run multiple
statements in a single program.

The flowchart is shown below:


The statements will be executed one by one until the true statement is found. When the true
statement is found, it will skip all other if and else statements in the code and runs the
associated blocks of code.

Code Example
Let's understand if else statement with the help of two examples.

Example 1:

Consider the below code.

1. int a = 5;
2. int b= 6;
3. void setup ( )
4. {
5. Serial.begin ( 9600 );
6. }
7. void loop ( )
8. {
9. if ( a > b )
10. {
11. Serial.println ( " a is greater " );
12. }
13. else
14. {
15. Serial.println ( " a is smaller " );
16. }
17. }
In the above example, the values are initialized to the variables a and b. The message
concerning the satisfied condition will be printed.

Example 2:

Consider the below code.

1. const int LED1 = 4;


2. int x = 150 ;
3. void setup ( )
4. {
5. Serial.begin( 9600 );
6. pinMode ( LED1, OUTPUT);
7. }
8. void loop ( )
9. {
10. if ( x > 100 )
11. {
12. digitalWrite(LED1, HIGH);
13. Serial.println ( " LED1 will light +++");
14. delay (500);
15. }
16. else
17. {
18. Serial.println ( "LED1 will not light");
19. }
20. }
Output: LED1 will light +++

If the initialized value of x is less than 100, the message ' LED1 will not light ' will be printed
in the output.
Else if
The else if statement can be used with or without the else ( ) statement. We can include
multiple else if statements in a program.

Let's understand with an example.

AD

1. if (condition)
2. {
3. // statements
4. }
5. else if ( condition)
6. {
7. // statements
8. // only if the first condition is false and the second is true
9. }
10. else
11. {
12. //statements
13. }
AD

Code Example
Let's understand else-if statement with the help of an example.

Example 1:

Consider the below code.

1. int i = 2;
2. int j = 3;
3. void setup ( )
4. {
5. Serial.begin(9600);
6. }
7. void loop ( )
8. {
9. if ( i > j )
10. {
11. Serial.println( " I is greater ");
12. }
13. else if ( i < j )
14. {
15. Serial.println( " J is greater " );
16. }
17. else
18. {
19. Serial.println( " Both are equal " );
20. }
21. }
Output: J is greater

The else if ( ) statement will stop the flow once its execution is true.

AD

What is the difference between Else and Else If?


The Else ( ) part is executed if one or all the If ( ) conditions present in the code comes out
to be false.

The else if ( ) will stop the program flow if it becomes true.

Arduino for Loop


The statements inside the curly brackets under for loop are executed repeatedly according
to the specified condition. An increment counter in the for loop is used to increment or
decrement the loop repetitions.

The for statement is commonly used for repetitive task or operation or to operate on the
group of data/pins in combination with arrays.

The syntax is:

1. for (initialization; condition; increment)


2. {
3. \\ statements
4. }
where,

o initialization: It is defined as the initialization of the variable.


o condition: The condition is tested on every execution. If the condition is true, it will
execute the given task. The loop ends only when the condition becomes false.
o increment: It includes the increment operator, such as i + +, i - - , i + 1, etc. It is
incremented each time until the condition remains true.
For example,

1. for ( i = 0 ; i < 5 ; i + +)
The above statement will execute the loop for five times. The values of i will be from 0 to 4.

If the statement is:


1. for ( i = 0 ; i < = 5 ; i + +)
The above statement will execute the loop six times. The values of i will be from 0 to 5.

Note: If we do not want to execute the for loop again and again. Then, we can
insert the for loop in the void setup( ) function.

Example 1:
To print a message 'Arduino' 15 times.
To print a message 15 times or more is quite complicated using Serial.println ( ), as the
code will become too lengthy.

To overcome this, programmers prefer to use for loop to execute a task multiple times,
while using a single statement.

Let's consider the below code.

1. int i;
2. void setup ( )
3. {
4. Serial.begin(9600);
5. for ( i = 0 ; i < 15 ; i ++ )
6. {
7. Serial.println( "Arduino");
8. }
9. }
10. void loop ( ) {
11. }
Output:

AD
Example 2:
To use a multiplication increment

The multiplication increment in the for loop will generate a logarithmic progression.

Consider the below code:

1. int x;
2. void setup ( )
3. {
4. Serial.begin(9600);
5. for (x = 2; x < 100; x = x * 2)
6. {
7. Serial.println(x);
8. }
9. }
10. void loop ( ) {
11. }
Output:

We can also declare the int data type directly in the for loop.

AD

For example,

1. for (int x = 2; x < 100; x = x * 2)

Example 3: To fade an LED


Here, fade and LED means that LED will faint slowly.

Consider the below code:

1. const int pinPWM = 11; // here, we have initialized the PWM pin.
2. void setup ( )
3. {
4. Serial.begin(9600);
5. }
6. void loop ( )
7. {
8. int x = 1;
9. for (int i = 0; i > -1; i = i + x)
10. {
11. analogWrite(pinPWM, i);
12. if (i == 255)
13. {
14. x = -1; // It will switch the direction at peak
15. }
16. delay(10); // It is delay time of 10 milliseconds
17. // the lesser the time, the more fading effect can be seen clearly
18. }
19. }
For the connection, we will connect the positive terminal of the LED in series with the
resistor to PIN 11 (PWM pin), and the negative terminal of the LED to GND.

Note: The for loops in C++ programming language is much more flexible than
other types of programming languages.

Example 4:
Consider the below code:

AD

1. void setup ( )
2. {
3. int i;
4. Serial.begin(9600);
5. for (i = 0; i < 4; i = i + 1)
6. {
7. Serial.println( "Hello Arduino" );
8. }
9. Serial.println( " DONE");
10. }
11. void loop ( )
12. {
13. }
The above code will print 'Hello Arduino' four times. After that the condition becomes false,
control comes out of the loop, and 'DONE' is printed.

Output:
Similarly, we can create any program using for loop accordingly.

Arduino while loop


The while loop() is the conditional loop that continues to execute the code inside the
parentheses until the specified condition becomes false.

The while loop will never exit until the tested condition is changed or made to stop. The
common use of a while loop in Arduino includes sensor testing, calibration (calibrating
the input of sensor), variable increment, etc.

The syntax is:

1. while (condition)
2. {
3. // code or set of statements
4. }
where,

condition: It specifies the boolean expression, which determines the condition to be true or
false.

For example,

1. variable = 0;
2. while (variable < 100) {
3. // performs the specified task 100 times repeatedly
4. variable++ ; // increments after every execution
5. }
The above code inside the curly braces in while loop will execute continuously and
repeatedly as long as the variable is less than 100.

Flowchart
The flowchart is shown below:

AD

Code Example
In order to change the flow of the program, we need to change the specified condition inside
the parentheses of while loop. The process is much like the if statement.

Let's understand the concept of while loop with two examples.

Example 1:

Consider the below code:

1. int a = 0;
2. void setup()
3. {
4. Serial.begin(9600);
5. while( a < 5)
6. {
7. Serial.println("Welcome to Arduino");
8. a = a + 1;
9. }
10. }
11. void loop()
12. {
13. }
Output:

The message inside the loop will be printed five times, as shown below:

Let's look at the code.

Explanation: At first, we have defined the variable a as 0, and initialized the serial monitor
as usual (means Serial.begin()). The loop first checks the condition specified within the
parentheses. At first, a =0. The condition is true (0 < 5). The code inside the curly braces
will execute, and the message is printed.

Now, the value of a is incremented (added 1 to a), and the loop executes again.

AD

Similarly, five times the condition remains true. When a =5, the condition becomes false,
and the loop exits and drops. The code outside the loop is executed.

Let's consider another example.

Example 2:

The code is similar to the above example. We will only add some statements outside the
loop.

Consider the below code:

AD

1. int a = 0;
2. void setup()
3. {
4. Serial.begin(9600);
5. while( a < 5)
6. {
7. Serial.println("Welcome to Arduino");
8. a = a + 1;
9. }
10. Serial.println("DONE");
11. Serial.println("Welcome to the code outside the loop");
12. }
13. void loop()
14. {
15. }
Output:

We can notice that as soon as the condition in the loop becomes false, the message
specified outside the loop is printed.

do...while
The working of the do-while loop is similar to the while loop. The condition inside the do-
while will execute at least once. It is because the condition is tested at the end of the loop
instead of the beginning.

The syntax is:

1. do
2. {
3. // code or set of statements
4. } while (condition);
where,

condition: It specifies the boolean expression, which determines the condition to be true or
false.

For example,

1. int b = 0;
2. do {
3. delay(100); // wait for stabilization of the sensors
4. b = readSensors(); // It checks the sensors
5. } while (x < 100); // specified condition

Flowchart
The flowchart is shown below:
Code Example
Let's understand the concept of the do-while loop with an example.

Example 1:

Consider the below code:

1. int a = 0;
2. void setup()
3. {
4. Serial.begin(9600);
5. do
6. {
7. Serial.println("Welcome to the do while loop");
8. a = a + 1;
9. } while( a < 3);
10. }
11. void loop()
12. {
13. }
Output:
Arduino switch case
The switch case controls the flow of the program by executing the code in various cases. A
switch statement compares a particular value of a variable with statements in other cases.
When the statements in a case matches the value of a variable, the code associated with
that case executes.

The break keyword is used at the end of each case. For example, if there are five cases,
the break statements will also be five. The break statement exits the switch case.

The switch statement without a break will continue to execute all the cases until the end.
Hence, it is essential to include a break statement at the end of each case.

Let's understand with an example.

1. switch(variable)
2. {
3. case 1:
4. // statements related to case1
5. break;
6. case 2:
7. // statements related to case2
8. break;
9. .
10. .
11. case n:
12. // statements related to case n
13. break;
14. default:
15. // it contains the optional code
16. //if nothing matches in the above cases, the default statement runs
17. break;
18. }
where,

variable: It includes the variables whose value will be compared with the multiple cases

value: It consists of a value to compare. These values are constants. The allowed data
types are int and char.
Flowchart of the switch case
Consider the below flowchart:

Can we use the if statement instead of a switch case?

Yes.
But for some cases, implementing a switch case is somewhat easier than if statements.

It is recommended to use switch cases instead of if statement when multiple conditions of a


non-trivial expression are being compared.

The if statement allows us to choose between the two options, TRUE or FALSE. We can
also use multiple if statements for more than two cases. The switch case allows us to
choose between various discrete options.

AD

Code Example
We will include the switch case in the setup() function, as we do not require the repeated
execution.

Consider the below code:

1. // switch case example


2. void setup()
3. {
4. Serial.begin(9600);
5. int a = 1;
6. switch(a) // the case matching the value in the declared variable will run
7. {
8. case 1:
9. Serial.println(" Case 1 matches");
10. // the value of variable matches with the value in case 1.
11. // The message associated with case 1 will be printed
12. break;
13. case 2:
14. Serial.println(" Case 2 matches");
15. break;
16. case 3:
17. Serial.println(" Case 3 matches");
18. break;
19. default:
20. Serial.println(" default matches");
21. break;
22. }
23. }
24. void loop()
25. {
26. }
Output:
Arduino String
The string is a data type that stores text rather than the integer values. It is similar to other
data types such as integer, float, etc., in Arduino.

The string is an array of characters or a set of characters that consists of numbers,


spaces, and special characters from the ASCII table.

The string can be declared in the following ways:

o char StrA[10];
o char StringA[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e'};
We can also add an explicit null character

o char StringB[8] = {'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};
AD

We can also declare an array with extra space for a string constant StrA.

o char StrA[10]; = "Hello";


o char StrD[6]; = "Hello";
o char StrD[]; = "Welcome";
The data type is char. Each character is an element in string. For
example, Arduino contains seven characters. So, we need to declare an array atleast of
size 8 (1 extra to store the null character at the end of the string).

Consider the below example:

1. char myString[len] = "text";


The above declared string will be stored as:
When we create a string using the double quotes like the word "text" specified above, the
compiler automatically creates an element out of each character. It further appends the null
character to the end.

The null character has the value 0 in the ASCII table. It is defined using two characters ( \
and \0). The backslash (\) represents the special character when used in conjunction with
other characters. The backslash is also known as an escape character. The null character
is added by the compiler to terminate the string.

Note: Strings are always declared inside the double quotes, while characters are
declared inside single quotes.

How Serial.print() and Serial.println() works with strings?


It is interesting to know how print() and println() function works with the strings.

Let's start.

Serial.print() with string


Let's understand with a coding example.

1. const int length = 20;


2. char myString[length] = "Hello Arduino";
3. // we can also specify as char myString[20] = "Hello Arduino";
4. void setup()
5. {
6. Serial.begin(9600);
7. }
8. void loop()
9. {
10. for( int i=0; i<length; i = i+1)
11. {
12. if(myString[i]== '\0')
13. // it will stop printing when it sees a null character
14. {
15. break; //
16. }
17. Serial.print(myString[i]);
18. }
19. Serial.println();
20. delay(500);
21. }
The code will print Hello Arduino multiple times, as shown below:
AD

Serial.println() with string


In the case of println() function, we need not require any for loop or condition to print.

It is an easier way to print strings.

The println() function will work the same as the above.

AD

Consider the below example.

1. const int length = 15;


2. char myString[length] = "Hello Arduino";
3. void setup()
4. {
5. Serial.begin(9600);
6. }
7. void loop()
8. {
9. Serial.println(myString);
10. delay(500);
11. }
Output:

The output will be the same as the above.

Array of Strings
We can specify the array of strings while working with large projects, such as LCD display,
etc.

The array names are also considered as pointers. The data type marked with an asterisk is
defined as pointers.

AD
For example, char*. To define an array of arrays, we actually need pointers.

Let's understand with an example.

Consider the below code:

1. char *StrAB[] = {"Welcome to string A to G in Arduino", "Here is string A", "Here is string B", "H
ere is string C", "Here is string D", "Here is string E",
2. "Here is string F", "Here is string G" };
3. void setup() {
4. Serial.begin(9600);
5. }
6. void loop() {
7. for (int i = 0; i < 8; i++)
8. {
9. Serial.println(StrAB[i]);
10. delay(1000);
11. }
12. }
Output:

Arduino String Object


What are objects in Arduino?
An object is like a variable, which points to a memory location that holds some data.
The functions associated with the object are called member functions. As a result, we can
make the objects to perform some actions.

For example,

The begin(), print(), and println() are the functions that are declared using the serial
object. The period after the Serial (print(), etc.) specifies that we are accessing some
members within the serial object. The members can be either a function or a variable.
The parentheses after the print() and println() function determines the function being called
in the serial. These functions cannot be declared alone in the global scope in the code.
Thus, they are declared with the serial object as Serial.print() and Serial.println().

String Object
The String object allows us to store and perform actions on an array of characters. The
String object takes more memory than the regular String.

The String object is always displayed with the uppercase 'S'. It produces an instance of the
String class.

It can be constructed from different data types, which are listed below:

o a constant integer using a specific base


o a long integer using a particular base
o an instance of a String object
o a constant character enclosed within a single-quotes
o A constant string of characters enclosed within the double-quotes.
o float and double
The specified number in a string has a default base of 10. For example,

1. String myString = String(15);


It creates a string that consists of the ASCII representation of the number 15.

To specify a number with base other than 10, the String can be created as:

1. String myString = String(15, HEX);


It will give us the String ''F''. It signifies the hexadecimal conversion of the decimal number
15.

We can also represent a String in BIN. For example,

1. String myString = String(15, BIN);


It will give us the String ''1111''. It signifies the hexadecimal conversion of the decimal
number 15.

The syntax is:

1. String(value)
2. String(value, base)
3. String(value, PlacesofaDecimal)
where,

value: It signifies the value needed to format or represent a string.

The data types are byte, unsigned int, char, float, double, unsigned long, long, int, and
string.
AD

base: It signifies the base, which is required to format the integer value. For example, HEX,
BIN, etc.

The base is optional to include.

PlacesofaDecimal: It specifies the desired decimal places, which is only needed if the
value is double or float.

Functions with String Object


We can use various functions with the String.

o charAT()
AD

It is used to access a specific character.

AD

The syntax is:

1. thisString.charAT(n)
where,

thisString is the declared variable

n is also a variable

The data type allowed is unsigned int.

The above syntax will return the nth character of the specified string.

o compareTo()
It is used to compare the two Strings. The specified Strings are compared using the ASCII
values of the characters.

The syntax is:

1. thisString.compareTo(myString)
where,

thisString and myString are the declared variable

The above syntax will return a negative number if thisString comes before myString.

It will return a positive number if thisString comes after myString.


o endsWith()
It tests that if a String ends with the characters of other String or not.

The syntax is:

1. thisString.endsWith(myString)
where,

thisString and myString are the declared variable

It will return true if thisString ends with the characters of myString. Otherwise, it will
return false.

o startsWith()
It tests that if a String starts with the characters of other String or not.

The syntax is:

1. thisString.startsWith(myString)
where,

thisString and myString are the declared variable

It will return true if thisString starts with the characters of myString. Otherwise, it will
return false.

o toLowerCase()
It gets a lowercase version of the specified String.

The syntax is:

1. thisString.toLowerCase()
where,

thisString is the declared variable

o toUpperCase()
It gets an uppercase version of the specified String.

The syntax is:

1. thisString.toUpperCase()
where,

thisString is the declared variable


o equals()
It compares the equality of the Two Strings. The comparison is quite sensitive, where String
"Arduino" is not equal to the String "ARDUINO".

The syntax is:

1. thisString.equals(myString)
where,

thisString and myString are the variables

It will return true if thisString equals to myString. Otherwise, it will return false.

o getBytes()
It copies the characters of the String to the supplied buffer.

The syntax is:

1. thisString.getBytes(buffer, length)
where,

thisString is the declared variable

buffer: The characters are copied into the buffer. The required data type is the byte.

length: It signifies the size of the buffer. The required data type is unsigned int.

o lastIndexOf()
It locates a String or character within the other String.

The syntax is:

1. thisString.lastIndexOf(value)
2. thisString.lastIndexOf(value, from)
where,

thisString is the declared variable

value: It includes the particular value to search for. The required data types
are String and char.

from: It is defined as the index to work backward from

o substring()
It is declared to get the substring of a specific String.
The syntax is:

1. thisString.substring(from)
2. thisString.substring(from, to)
where,

thisString is the declared variable

from: It is defined as the index, from where the substring will start

to: It is also the index to end the substring before. It is optional.

o toInt()
It converts a valid String in Arduino to the integer type.

The syntax is:

1. thisString.toInt()
where,

thisString is the variable

The required data type is long. It returns zero if the conversation is invalid or a String does
not start with an integer number.

o toFloat()
It converts a valid String in Arduino to the float.

For example, String "150" will be converted to "150.00"

The syntax is:

1. thisString.toFloat()
where,

thisString is the variable

The required data type is float. It returns zero if the conversation is invalid or a String does
not start with a digit.

o trim()
It modifies the String by removing the extra whitespaces.

The syntax is:


1. thisString.trim()
where,

thisString is the variable

AD

Code Example
Let's understand the String Object with two examples.

Example 1:

Let's use the charAt() function.

Consider the below code:

1. void setup()
2. {
3. Serial.begin(9600);
4. String thisString = "Welcome to Arduino";
5. Serial.println(thisString.charAt(8));
6. }
7. void loop()
8. {
9. }
Output: t

The t is the character at index 8, which is declared in the charAt() function.

Example 2:

Let's use the concat function.

concat() - The concat() function is used to combine the Strings.

Consider the below code:

1. void setup()
2. {
3. Serial.begin(9600);
4. String thisString = "Welcome to Arduino";
5.
6. thisString.concat("String Object");
7.
8. Serial.println(thisString);
9. }
10. void loop()
11. {
12. }
Output

Similarly, we can use other String object functions as well.

Blinking an LED
It is the simple basic project created using Arduino. LED (Light Emitting Diode) is an
electronic device, which emits light when the current passes through its terminals. LED's
are used in various applications. It is also used as an ON/OFF indicator in different
electronic devices.

In this project, we will connect the LED to the digital pin on the Arduino board. The LED will
work as a simple light that can be turned ON and OFF for a specified duration.

Structure of LED
An LED is a two-terminal device. The two terminals are called as Cathode and Anode.

It is shown below:

The long terminal is called Anode, and the shorter terminal is called Cathode. Here, cathode
is the negative terminal and anode is the positive terminal.
AD

Components of the project


The components used in the blinking of an LED are listed below:

1. 1 x Arduino UNO board.


We can use any version of the UNO board, such as UNO R3, etc. We can also use other
types of Arduino boards, such as Arduino Zero, Arduino Micro, etc.
2. 1 x Breadboard
3. 2 x Jump wires
4. 1 x LED
5. 1 x Resistor of 220 Ohm.

We can use a resistor of any value upto 470 Ohms. We can use other value of resistors as
well, depending on our circuit requirements. Usually, the value should not exceed the
allowable forward current.

Structure of the project


The structure clearly shows the pinout of the UNO board. It also displays the LED and
resistance connected to the board.

It is shown below:
Sketch
We need to install the Arduino IDE, to begin with the coding, which is already discussed.

Open the IDE and start with the coding, which is given below:

1. void setup ()
2. {
3. pinMode ( 8, OUTPUT); // to set the OUTPUT mode of pin number 8.
4. }
5. void loop ()
6. {
7. digitalWrite (8, HIGH);
8. delay(1000); // 1 second = 1 x 1000 milliseconds
9. digitalWrite (8, LOW);
10. delay(500); // 0.5 second = 0.5 x 1000 milliseconds
11. }
We can modify the delay duration according to our choice or as per the requirements.

Every statement of coding is explained in Arduino coding basics. You can open the URL for
clear understanding.

Note: Make sure the code is free of errors.


The sketch will be uploaded to the board after the correct compiling, as shown below:

We are required to click on the Verify button to compile the code.

The RX and TX LED on the board will light up after the successful uploading of the code.

Procedure
The procedure to join the components of the project is shown below:

AD

o Attach an LED on the breadboard. We need to plug-in the two terminals of an LED into
the holes of the breadboard.
We can plug-in the LED anywhere on the breadboard.

o Connect the resistor in series with the LED, as shown below:


AD

o Connect the left leg of the resistor (connected in series with red LED) to the digital output
pin of the UNO board, i.e., PIN 8.
o Connect the negative/shorter terminal (Cathode) of the LED to the GND pin of the UNO
board using the wire, as shown below:

Here, the orange wire is connected to the PIN 8, and the blue wire is connected to the GND.

The shorter terminal indicates the negative. So, we will connect the shorter terminal to the
Ground (GND).

o Connect the USB cable.


o Select the board and serial port in the Arduino IDE.
o Upload the sketch or code on the board.
o The LED will dim and light for the specified duration.
Important points

The important points to be considered in this project are listed below:

AD

o The resistor must be connected in series with the LED.


The resistor prevents the excess current from reaching the LED. The excess current in the
connection can burn the LED. Hence, a resistor in series with the LED is used in the
connection.

o We can use any pin as the OUTPUT pin. For example, 8, 13, 7, 4, and 3. The other pins
are PWM and analog pins.
o One terminal of the LED is connected to the Ground while the other terminal is
connected to the digital pin. The digital pin has only two values 0 or 1.
o HIGH = 1
o LOW = 0
o Arduino UNO board is recommended for all basic projects because it is easy to
understand and implement. It is also the standard Arduino board from all types of boards
used. It supplies power and also acts as a serial port.

Blinking Two LED


We have already discussed a project of blinking an LED. Here, we will discuss a project of
blinking two LED's.

The concept of blinking two LED's is similar to the blinking of a single LED. As we know, we
can use the resistance of any value, so let's take the resistors of 470 Ohms. The resistors
reduce the amount of current reaching the LED, which saves the LED from being burnt.

We can also use other resistors depending on the circuit limit and requirements.

Let's start with the project.

Structure of two LED's


The structure of red and green LED is shown below:
The long terminal is called Anode (positive charged), and the short terminal is called
Cathode (negative charged).

AD

Components
The components used in the project are listed below:

1. 1 x Arduino UNO board.


We can also use other types of Arduino boards, such as Arduino Mega, Arduino Micro, etc.
2. 1 x Breadboard
3. 4 x Jump wires
4. 1 x Red LED
5. 1 x Green LED
We need to take 2 LEDs of any color. Here, we will use the red and green color LED.
6. 2 x Resistor of 470 Ohm.

Structure of the project


Here, we will use the digital output pin number 13 and 7. The positive terminal of the red
LED is connected to the PIN 13, and the negative terminal (anode) is connected to the
ground.

Similarly, the positive terminal (cathode) of the green LED is connected to PIN 7 and the
negative terminal is connected to the ground.

As mentioned, two resistors each of 470 Ohms, will be connected in series to the two LEDs
in the project.

The structure will represent the pinout diagram of the project. It is shown below:
Sketch
Open the Arduino IDE (Integrated Development Environment) and start with the coding,
which is given below:

1. void setup ()
2. {
3. pinMode ( 13, OUTPUT); // to set the OUTPUT mode of pin number 13.
4. pinMode ( 7, OUTPUT); // to set the OUTPUT mode of pin number 7.
5. }
6. void loop ()
7. {
8. digitalWrite (13, HIGH);
9. digitalWrite (7, LOW);
10. delay(1500); // 1.5 second = 1.5 x 1000 milliseconds
11. digitalWrite (13, LOW);
12. digitalWrite (7, HIGH);
13. delay(1000); // 1 second = 1 x 1000 milliseconds
14. }
We can modify the delay duration according to our choice or as per the requirements.

The sketch will be uploaded to the board after the correct compiling, as shown below:

Click on the Verify button present on the toolbar to compile the code.

The RX and TX LED on the board will light up after the successful uploading of the code.

Procedure
The procedure to join the components of the project is shown below:

AD

o Plug-in the two LED adjacent to each other on the breadboard.


o Now, plug-in the resistors of 470 Ohm in series with the two LED, as shown below:
We need to check that the plug-in is performed correctly, as shown above. For any
confusion, check the pin diagram shown above in the heading- Structure of project.

o Connect the left leg of the resistor (connected in series with red LED) to the digital
output pin of the UNO board, i.e., PIN 13.
o Connect the left leg of the resistor (connected in series with green LED) to the digital
output pin of the UNO board, i.e., PIN 7.
o Connect the negative/shorter terminal (Cathode) of the red and green LED to
the GND pin of the UNO board using the wire, as shown below:
AD

Here, the red wire is connected to the PIN 13, and the blue wire is connected to the GND.

Similarly, the green wire is connected to the PIN 7, and the orange wire is connected to the
GND.
Note: The different colors of wire are used only for a better understanding.
The shorter terminal indicates the ground. So, we will connect the shorter terminal to the
Ground (GND).

o Connect the USB cable.


o Select the board and serial port in the Arduino IDE.
o Upload the sketch or code on the board.
o The LED will dim and light for the specified duration. Here, the green and red LED will
light alternatively.
It means when the red LED will be ON, the green LED will be OFF and vice versa.

AD

Blinking various LEDs using Arrays


We have already discussed how to blink a single LED, two LEDs, and LEDs using a loop, in
previous topics.

Here, we will discuss a project to blink five LEDs using array. All the five LEDs will light one
after the other.

Hardware Required
The components required for the project are listed below:

o 5 x red LED
o 5 x 220 Ohm Resistors
o Arduino UNO R3 board
o Jump wires
We can use any color LED as per our choice.

AD

Principle
We will connect the five LEDs to pins 13, 12, 8, 4, and 2 of the Arduino board. The required
resistance of the resistors is enough to light up an LED without damaging the board and
other components.

The LED arranged one after another will light up. We can also change or rearrange the
LEDs connected to the specified pin number on the board.

Structure of the project


The structure clearly shows the UNO board's pinout, and the five LEDs with resistors in
series are connected to the board.

It is shown below:

Connection
The connection of the above project is discussed below:

o Connect the resistor of 220 Ohm in series with the five LEDs. Now connect it to the pin
number 13, 12, 8, 4, and 2 of the Arduino board.
o Connect the negative terminal of the five LEDs to the GND (Ground).
AD

Sketch
The code to light the five LEDs is given below:

1. int timer = 500;


2. int LEDPins[] = {13, 12, 8, 4, 2}; // an array of declared pin numbers on the board
3. int countOFpin = 6; // the number of arrays
4. void setup()
5. {
6. // we have declared an array to intialize the LED pins as OUTPUT
7. for (int PIN = 0; PIN < countOFpin; PIN= PIN + 1)
8. {
9. pinMode(LEDPins[PIN], OUTPUT);
10. }
11. }
12. void loop()
13. {
14. // loop starting from the lowest pin in the array to the highest:
15. for (int PIN = 0; PIN < countOFpin; PIN++) {
16. // turns the pin ON:
17. digitalWrite(LEDPins[PIN], HIGH);
18. delay(timer);
19. // turnS the pin OFF:
20. digitalWrite(LEDPins[PIN], LOW);
21. }
22. // loop from the highest pin in the array to the lowest:
23. // It means the LEDs will light in the reverse direction as used above
24. for (int PIN = countOFpin - 1; PIN >= 0; PIN- -)
25. {
26. digitalWrite(LEDPins[PIN], HIGH);
27. delay(timer);
28. digitalWrite(LEDPins[PIN], LOW);
29. // We can also specify the time inside the delay( ) instead of the delcaring the timer
30. }
31. }
AD

Connection Diagram
We will show the connection using the Simulator because the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


Blinking multiple LEDs using the loop
We have already discussed the method to blink a single LED and two LEDs.

In this project, we will discuss the process to blink three LEDs using for loop. The three
LEDs will light up one after the other.

Let's start the process.

Hardware Required
The components required for the project are listed below:

o 3 x red LED
o 3 x 220 Ohm Resistors
o Arduino UNO R3 board
o Jump wires
We can use any color LED as per our choice.

AD

Principle
We will connect the three LEDs to pins 13, 8, and 4 of the Arduino board. The limiting value
of resistance should be between 220 and 330 ohms to set the optimal current through the
LEDs.

The required resistance is enough to light up an LED without damaging the board and
the LED. We will turn the LED ON/OFF individually.

Structure of the project


The structure clearly shows the pinout of the UNO board, and the three LEDs with resistors
in series are connected to the board.

It is shown below:
Procedure
The connection of the above project is discussed below:

o Connect the resistor of 220 Ohm in series with the three LEDs. Now connect it to the pin
number 13, 8, and 4 of the Arduino board.
o Connect the negative terminal of the three LEDs to the GND (Ground).
AD

Sketch
Open the Arduino IDE and start with the coding, which is given below:

1. /*
2. This program blinks LED connection to the pin number 13, 8, and 4
3. */
4. void setup()
5. {
6. pinMode(13, OUTPUT);
7. pinMode(8, OUTPUT);
8. pinMode(4, OUTPUT);
9. }
10. void loop()
11. {
12. // the first LED is made to blink one time
13. digitalWrite(13, HIGH);
14. delay(1000); // delay time in milliseconds
15. digitalWrite(13, LOW);
16. delay(1000);
17. // the second LED will blink two times
18. digitalWrite(8, HIGH);
19. delay(500); // the duration is 0.5 seconds
20. digitalWrite(8, LOW);
21. delay(500);
22. digitalWrite(8, HIGH);
23. delay(500);
24. digitalWrite(8, LOW);
25. delay(500);
26. // the third LED will blink three times
27. for( int i = 0; i < 3; i = i +1 )
28. {
29. digitalWrite(4, HIGH);
30. delay(500);
31. digitalWrite(4, LOW);
32. delay(500);
33. // We can adjust the delay time accordingly
34. }
35. }
AD

Connection Diagram
We will show the connection using the Simulator because the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


Blinking multiple LEDs using switch case
Here, we will discuss a project to turn ON one led from multiple LEDs based on the value in
the variable.

Let's start with the project.

Hardware Required
The components required for the project are listed below:

o 4 x red LED
o 4 x 220 Ohm Resistors
o Arduino UNO R3 board
o Jump wires
We can use any color LED as per our choice.

AD

Principle
We will connect the four LEDs to pins 12, 11, 8, and 6 of the Arduino board. The resistors of
220 Ohm are connected in series with the LEDs.
The switch statement will compare the declared value of a variable with statements in other
cases. The code associated with the matching case will run.

We will also change or rearrange the LEDs connected to the specified pin number on the
board.

Structure of the project


The structure clearly shows the UNO board's pinout, and the four LEDs with resistors in
series are connected to the board.

It is shown below:

Connection
The connection of the above project is discussed below:
o Connect the resistor of 220 Ohm in series with the four LEDs. Now connect it to the pin
number 12, 11, 8, and 6 of the Arduino board.
o Connect the negative terminal of the five LEDs to the GND (Ground).
AD

Sketch
Consider the below code:

1. void setup()
2. {
3. // initialize serial communication:
4. Serial.begin(9600);
5. // initializing the LED pins:
6. for (int LEDpin = 6; LEDpin <13 ; LEDpin++) {
7. pinMode(LEDpin, OUTPUT);
8. // here, we have used for loop for initialization
9. }
10. }
11. void loop()
12. {
13. int a = 3; // we can specify any variable name
14. switch (a)
15. {
16. case 1:
17. digitalWrite(6, HIGH);
18. break;
19. case 2:
20. digitalWrite(8, HIGH);
21. break;
22. case 3:
23. digitalWrite(11, HIGH);
24. break;
25. case 4:
26. digitalWrite(12, HIGH);
27. break;
28. default:
29. // turn all the LEDs off if all the above cases does not matches:
30. for (int LEDpin = 6; LEDpin <13; LEDpin++)
31. {
32. digitalWrite(LEDpin, LOW);
33. }
34. }
35. }
In the above code, the specified value of variable matches with case 3. Hence, the LED
connected to pin number 11 will light up.

AD
Connection Diagram
We will show the connection using the Simulator because the connections become clearer
and more precise.

We can make the same connection using the hardware devices.

Output

The LED connected to the PIN 11 will light up, as shown below:
Arduino Switch
Switches are used to turn ON/OFF devices and to connect different parts of a circuit. The
slide-switch in Arduino moves the slider of the switch from the open position (ON) to the
closed position (OFF).

It allows the flow of current in the circuit without the need for splice wire. The slide switches
are widely used in small circuits applications.

There are two types of circuits, which are shown below:

o Closed circuits
The closed circuits have closed loop. Electrons can easily flow in a closed circuit and light
up an LED.
o Open circuits
AD

The open circuits have open ends, due to which electrons cannot flow through the circuit.

We can use an electronic component switch, to open and close circuits without the need to
disconnect the wires by hand again and again.

Types of Switches
There are major four types of switches in Arduino, which are listed below:

o SPST (Single Pole Single Throw) Switch


It is a switch that has one input and one output. The circuit is ON when the switch is closed
and vice versa.
o SPDT (Single Pole Double Throw) Switch
It is a three-terminal switch. It has a single input, which can switch between two outputs.

o SP3T (Single Pole Three Throw) Switch


It is a switch with one input and three outputs, where each input corresponds to any of the
output in a circuit.

o DPDT (Double Pole Double Throw) Switch


It is a switch with two inputs and four outputs. Each input of a switch in Arduino can be
connected to either of the two outputs.
where,

Pole: It signifies the number of circuits the switch can control.

Throw: It signifies the number of positions in which each pole of the switch can connect to
it.

Code Example
Let's discuss an example to light an LED using a Switch. Here, we will use the SPDT
(Single Pole Double Throw) Switch.

If we leave one side of the switch, it can work as SPST (Single Pole Single Throw) switch.

Components Required

AD

The required components are listed below:

o Arduino UNO board. Here, we have used UNO R3.


o 1 x 220 ohm resistor
o Jump wires
o 1 x Slide switch
o 1 x green LED (we can take LED of any color)
o 1 x Breadboard
The steps for such an example are listed below:
1. Attach the green LED on the breadboard.

2. Connect a resistor in series with the LED.

3. Attach Slide switch on the breadboard, as shown below:

AD

4. Connect the negative pin of the LED to the Ground.

5. Connect the positive terminal of LED in series with the resistor to PIN 8.

6. Connect the common terminal or the middle terminal to pin number 3. It is because the
middle terminal is the input terminal.

7. Connect one end of slide switch to Ground and another end to 5V.

The circuit is shown below:


Now, we need to write the code on the coding screen.

The code is given below:

1. const int pinOFswitch = 3;


2. const int LED = 8;
3. void setup( ) {
4. pinMode(pinOFswitch, INPUT);
5. pinMode(LED, OUTPUT);
6. }
7. void loop( )
8. {
9. int ValueOFswitch;
10. ValueOFswitch = digitalRead(pinOFswitch);
11. if (ValueOFswitch == HIGH)
12. {
13. digitalWrite(LED, HIGH);
14. delay(500);
15. }
16.
17. else
18. {
19. digitalWrite(LED, LOW);
20. delay(500);
21. }
22. }

Arduino button
The buttons are similar to switches that create and break electrical connections in the
circuits. The button plays a transition between ON and OFF state. A single press turns the
state ON, while another press turns the state OFF. It means that the button connects the
two points in a circuit when we press them.

There are two types of button, which are listed below:

o NO (Normally Open)
We mostly use NO types of buttons. In such type, the state of the button is in rest. It means
that a terminal in such a condition is not connected.

It is shown below:

When we push the button, the terminals become electrically connected.

o NC (Normally Closed)
AD

It is defined as the working state of the button. It connects the terminals of the circuit and
allows current to flow through the load.

It is shown below:
NC and NO are also defined as the momentary type of switches.

Let's understand NO and NC with the help of a circuit.

The NO state of a circuit is shown below:

Due to the open ends of the circuit, the current cannot flow through it. The state of the
circuit is in rest.

The NC state of a circuit is shown below:


The current can easily flow through the circuit due to its connected ends. The LED will be
ON until we push the button again.

Another type of button is pushbutton, which is widely used in projects and circuits.

Structure of pushbutton
Let's understand the structure of pushbutton.

The pushbutton is a square shape button with four terminals, as shown below:

The two pins are next to each other on one side and another two pins on the other side. The
pins across to each other are connected. The pins next to each other can only be
connected, when we press the button.

AD

We can also connect two opposite terminals of the pushbutton, as shown below:
Let's understand buttons with an example.

Code Example
Here, we will light an LED by pressing the pushbutton. When we press the push button, it
turns ON the LED connected to the PIN 13 on the Arduino UNO board.

Components Required

The required components are listed below:

AD

o Arduino UNO board. Here, we are using UNO R3.


o 1 x 220 ohm resistor
o 1 x 10 Kohm resistor
o Jump wires
o 1 x pushbutton
o 1 x red LED (we can take LED of any color)
o 1 x Breadboard
The steps for such an example are listed below:

1. Attach the red LED on the breadboard board.


2. Connect a resistor in series with the LED and connect it to PIN 2 of the breadboard.
3. Connect the negative terminal of the LED to the GND pin.
4. Attach the pushbutton on the breadboard.
5. Connect a 10 kohm resistor in series with the lower right corner of the pushbutton and
connect it to the GND pin.
6. Connect the upper right corner of the pushbutton to PIN 4.
7. Connect lower left corner of the pushbutton to 5V.

The circuit is shown below:


AD

Code
The code for the upper circuit is shown below:

1. const int ledpin = 2; // initializing pin number 2 to the LED


2. const int buttonpin = 4; // initializing pin number 4 to the button
3. int buttonState = 0;
4. void setup()
5. {
6. Serial.begin(9600);
7. pinMode(buttonpin, INPUT);
8. pinMode(ledpin, OUTPUT);
9. }
10. void loop()
11. {
12. // read the state of the pushbutton value
13. buttonState = digitalRead(buttonpin);
14. // check if pushbutton is pressed. if it is, the
15. // buttonState is HIGH
16. if (buttonState == HIGH) {
17. // turn LED on
18. digitalWrite(ledpin, HIGH);
19. Serial.println("LED is ON");
20. //When we press the button, it will print LED is ON.
21. delay ( 500);
22. }
23. else
24. {
25. // turn LED off
26. digitalWrite(ledpin, LOW);
27. Serial.println("LED is OFF"); // When we press the button, it will print LED is OFF.
28. }
29. delay ( 500);
30. }
Output

The LED will light be OFF at the initial state.

When we continuously press the button, LED will light. The message 'LED is ON' will print
on the Serial Monitor after every 500 milliseconds.

Let's watch the output on the serial monitor.

When LED is OFF, the output appears as:

When LED is ON, the output appears as:


Arduino Library
The Library is considered as the advanced feature, which extends the capabilities of the
Arduino IDE. It means that the libraries provide extra functionality to the programming
platform of Arduino.

The libraries in Arduino are written in C or C++ (.cpp). These libraries allow us to
manipulate data and work with the hardware.

To implement any Library in the Arduino IDE, go to the Sketch -> Import Library.

There are several libraries available for download. We can also create our own library.

Let's discuss some of the libraries.

Standard Libraries
The standard libraries are listed below:

EEPROM
It stands for Electronic Erasable Programmable Read Only Memory. The EEPROM is
associated with the microcontroller present on the AVR or Arduino Boards. The EEPROM
library allows us to read the bytes stored in the memory when the power of the board is off.

The size of EEPROM varies in different boards, such as 1KB or 1024 bytes on the
ATmega328P. It can also be of 4KB or 4096 bytes on the Microcontroller ATmega2560, etc.

The library is declared as:

1. #include <EEPROM.h>
For example, EEPROM Read, EEPROM Clear, EEPROM Write, EEPROM Get, EEPROM
Update, EEPROM Put, EEPROM Iteration, etc.

AD

Ethernet Library
The Ethernet library works with the Arduino Ethernet shield and other related devices. The
Ethernet library allows us to connect the Arduino board to the Internet.

The SPI bus acts as an intermediate between the board and the shield.

The associated library is:

1. #include <Ethernet.h>
2. #include <SPI.h>
For example, TelnetClient, WebServer, WebClientRepeating, WebClient, ChatServer,
DnsWebClient, UdpNtpClient, UdpSendReceiveString, etc.

Firmata Library
For the programming environment, we can create custom firmware without producing our
own objects and protocols.

It is used to implement the firmware protocol, which communicates with the software on the
host computer.

The associated library is:

AD

1. #include <Firmata.h>

GSM Library
The GSM library exists on the IDE version 1.0.4 and up.

The GSM library allows us to perform the operations on the Arduino board similar to the
GSM phone, such as internet connection, send and receive messages, and to place voice
calls.

The library is declared as:

1. #include <GSM.h>

Liquid Crystal Library


It is a library that permits Arduino to communicate with LCDs, which are based on a
compatible chipset called Hitachi HD44780. Such chipsets are found on most types of text-
based LCDs. It works with either an 8-bit mode or 4-bit mode. Here, the bit mode signifies
the data lines in addition to the enable, rs, and rw control lines (optional).

The library is declared as:

AD

1. #include <LiquidCrystal.h>
The examples are Hello World, Cursor, Blink, etc.

AD

SD Library
It allows writing to or reading from SD cards. For example, Arduino Ethernet Shield. The file
names include the paths separated by the forward slashes, which are passed to the SD
Library. But, SPI is used for the communication between the SD card and the Arduino.

The library is declared as:

1. #include <SPI.h>
2. #include <SD.h>
The examples are Dump files, List Files, Read Write, etc.

Servo Library
The Servo library permits Arduino to work with servo motors. It allows controlling the
integrated shaft and gears. We can also position shaft at different angles between 0 and
180 degrees. The servo library on Arduino boards can support upto 12 motors, while
on Arduino Mega board, it can support upto 48 motors.

The library is declared as:

1. #include <Servo.h>

SPI Library
The SPI (Serial Peripheral Interface) is a serial data protocol. The microcontrollers use the
serial protocol to communicate over short distances with one or more peripheral devices
quickly.

The required connection of SPI is a full-duplex that allows devices to simultaneously sent
and receive data.

The library is declared as:

1. #include <SPI.h>
The examples are Dump files, List Files, Read Write, etc.

Stepper Library
The Stepper library in Arduino permits to control of bipolar or unipolar stepper motors.

The library is declared as:

1. #include <Stepper.h>
The Stepper includes stepper speed control, stepper one revolution, etc.

Software Serial Library


The Software Serial Library permits serial communication over digital Input/output pins. The
0 and 1 pins are inbuilt on Arduino for the serial interface. We can include multiple serial
ports in our code that can operate with speed upto 115200 bps (bits per second).

The library is declared as:

1. #include <SoftwareSerial.h>

TFT LCD Library


The TFT LCD library is included in the IDE version 1.0.5 and later. It allows the Arduino to
communicate with the TFT LCD screen. It further helps to draw images, shapes, lines, and
text to the screen.

The SD card slot present on the onboard screen can be used by implementing the SD
library.

The TFT library for communication depends on the SPI library with the SD card and screen.

The library is declared as:

1. #include <SPI.h>
2. #include <TFT.h>

WiFi Library
The WiFi library permits Arduino to establish a connection with the internet. It can either be
a server to receive the incoming connections or a client to perform outgoing connections.

The personal encryptions supported by the WiFi library are WPA2 and WEP except for
WPA2 Enterprise. Arduino uses the SPI bus to communicate with the WiFi shield.

The library is declared as:

1. #include <WiFi.h>
The examples include WiFiWebClient, WiFiWebServer, etc.

Audio Library
The Audio library is compatible with the Arduino Due board only. It enables the board to
playback .wav files from the specific storage devices, such as the SD card.

It plays sounds by using the DAC0 and DAC1 pins.

The library is declared as:


1. #include <Audio.h>
The example is a Simple Audio Player.

Audio Zero Library


It enables the board (Arduino Zero, MKR1000, and MKRZero) to playback .wav files from
the storage devices, such as the SD card.

Arduino Zero and MKR1000 board play sound by using the DAC0 pin.

The library is declared as:

1. #include <AudioZero.h>
The example is the Simple Audio Player Zero.

Arduino Sound Library


The Arduino Sound Library permits the board to analyze and play audio data, which is
provided by Arduino on SAMD21 based board using the I2S bus. The SAMD21 based
boards are Arduino Zero, MKR1000, MKRZero, or Genuino Zero.

The library is declared as:

1. #include <AudioSound.h>
The examples include WavePlayBack, ClapDetector, WhistleDetector, etc.

Now, let's discuss the process to install the library in Arduino.

How to install a library in Arduino?


The steps are listed below:

Arduino Library Manager


o We need to open the library manager to install a new library in Arduino. Click on Sketch
-> Include Library -> Manage Libraries, as shown below:
o A dialog box containing various libraries will appear, as shown below:
AD
o A list of libraries will appear that are ready to install. We need to select the specific
library -> select the version -> click on Install button, as shown below:
Sometimes there is only one version available for download. In such case, the dropbox of
the version will not appear. Hence, it's normal.

We need to wait for the library to download. The downloading will depend on the connection
speed.

The 'INSTALLED' tag will appear in front of the library that is already installed on our
computer.

Importing a .zip Library


If we want to add our own library, we can select the desired folder from our computer. The
particular zip file containing the library can be imported in the Arduino.

It is shown below:
We can also recheck from the option Sketch -> Include library to see that the added
libraries are present or not on the list.

We are not required to unzip the downloaded library. The file will remain in the .zip format.

We can download the 3rd party libraries starting with the Arduino IDE version 1.0.5.

Arduino LCD Display


The LCD (Liquid Crystal Display) is a type of display that uses the liquid crystals for its
operation.

Here, we will accept the serial input from the computer and upload the sketch to
the Arduino. The characters will be displayed on the LCD.
The library that allows us to control the LCD display is called Liquid Crystal Library, which
is discussed below:

The library is declared as:

1. #include <LiquidCrystal.h>
The library is based on a compatible chipset called Hitachi HD44780. It is found on most of
the LCDs that are based on text. It works with either an 8-bit mode or 4-bit mode. Here, the
bit mode signifies the data lines in addition to the enable, rs, and rw control lines (optional).

LCD Structure
The LCD display has a 16-pin interface.

The structure of the LCD is shown below:

The Liquid Crystal Display has a parallel interface. It means that the microcontroller
operates several pins at once to control the LCD display.

The 16-pins present on the LCD display are discussed below:

o RS
The Register Select (RS) pin controls the memory of the LCD in which we write the data.
We can select either the data register or the instruction register. The LCD looks for the
upcoming instruction, which is present in the instruction register.
o R/W
AD

The Read/Write pin selects the reading or writing mode.

o E
The Enable (E) mode is used to enable the writing to the registers. It sends the data to the
data pins when the mode is HIGH.

o D0 to D7
These are eight data pins numbered as D0, D1, D3, D3, D4, D5, D6, and D7. We can set
the state of the data pin either HIGH or LOW.

Pin 1 of the LCD is the Ground pin, and pin 2 is the Vcc or the voltage source pin.

The pin 3 of the LCD is the VEE or the contrast pin. For example, we can connect the
potentiometer's output to the VEE and can adjust the contrast of the LCD.

The A and K pins are also called as Backlight pins (Bklt+ and Bklt-).

AD

Principle of LCD
The process includes putting the data (to be displayed on the LCD screen) into the data
registers. The instructions in the Register Select are kept in the instruction register. The
liquid crystal library has simplified process to display the characters on the LCD.

AD

The LCDs can be controlled in 4-bit or 8-bit modes, which requires 7 and 11 Input/Output
pins from the particular Arduino board.

Let's discuss a project to display the text on the LCD.

Hardware Required
The components required for the project are listed below:

o LCD Screen (Hitachi HD44780 compatible driver display)


o 1 x 220 Ohm Resistor
o 1 x 10K Ohm Resistor
o Arduino UNO board or Genuino board
o Jump wires
o Pin header required to solder the LCD display pins
o breadboard
Structure of the project
The structure of the project is shown below:

Procedure
The connection is explained below:

AD

We need to first connect the data pins of LCD to the digital pins.

o Connect the RS pin of LCD to pin 13 of the Arduino board.


o Connect the Enable pin of LCD to pin 12 of the Arduino board.
o Connect the D4 pin of LCD to pin 6 of the Arduino board.
o Connect the D5 pin of LCD to pin 4 of the Arduino board.
o Connect the D6 pin of LCD to pin 3 of the Arduino board.
o Connect D7 pin of LCD to pin 2 of the Arduino board.
o Connect the middle terminal of the potentiometer to the VEE (contrast pin).
o Connect the two ends of the potentiometer to the Ground and 5V.
o Connect one end of a resistor to the A and K of the LCD and another end to 5V.
AD
Sketch
The code to display the specified message on the LCD display is given below:

1. // here, we will include the liquid crystal library:


2. #include <LiquidCrystal.h>
3. // initialize the library with the pins on the Arduino board
4. LiquidCrystal lcd(13, 12, 6, 4, 3, 2);
5. void setup() {
6. // Here, 16 and 2 are the columns and rows of the LCD
7. lcd.begin(16, 2);
8. // It prints the message on the LCD.
9. lcd.print("hello Arduino");
10. // We can modify the message as per our choice.
11. }
12. void loop() {
13. // It sets the cursor to column 0, line 1
14. // Since counting begins with 0, line 1 is the second row
15. lcd.setCursor(0, 1);
16. // print the number of seconds
17. lcd.print(millis() / 1000);
18. // Here, millis() is the return type of the timer in milliseconds
19. }

Connection Diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


Output

The message 'Hello Arduino' will be printed on the LCD display, as shown below:
Arduino Interrupt
The interrupts() in Arduino allows to certain essential tasks to be executed in the
background, and these are enabled by default.

The disabling of the interrupts() can interfere with the Arduino functions and may impact
communication. It means that some functions in Arduino will not work if the interrupts() is
disabled.

Interrupts can sometimes disturb the code timings. To prevent such disturbances, interrupts
can be disabled for a critical section of the code.

The syntax is:

1. interrupts()
Let's understand with an example.

Consider the below code:

1. void setup()
2. {
3. }
4. void loop()
5. {
6. interrupts();
7. // code is written here
8. nointerrupts();
9. // it includes sensitive code
10. // critical section of code
11. }

Features of Interrupts()
The features of interrupts() are listed below:

o It saves timing problems.


o It includes reading a rotary encoder or monitors a user input.
o It can free the processor to get some other stuff without missing the input.
o It helps the system to react quickly and efficiently.
External Interrupts
The external interrupts are listed below:

o attachInterrupt()
o detachInterrupt()
AD

attachInterrupt()
The first function to set the interrupt is: attachInterrupt( )

We are required to use the digitalPinToInterrupt(pin) to translate the real digital pin to the
interrupt number (a specified number).

For example,

If we want to connect it to pin number 5, we need to use the parameter as:

1. digitalPinToInterrupt(5)
It is the first parameter that is passed to the attachInterrupt().

AD

Digital pins usable for Interrupts


Let's discuss some digital pins for various Arduino boards, which are usable for Interrupts.

o Arduino UNO, Mini, or Nano


PIN- 2, 3

The pin number will be similar for all the boards based on 328 Microcontroller.

o Arduino Mega ADK, Mega 2560, or Mega


PIN- 2, 3, 18, 19, 20, 21

AD

o Arduino Zero
It includes all digital pins except the pin number 4.

o Arduino MKR Family boards


PIN- 0, 1, 4, 5, 6, 7, 8, 9, A1, A2

o Arduino Due
It includes all digital pins that can be used as interrupts.
Note: The variables modified within the attached function should be declared as
volatile.
Here, the delay( ) function will not work inside the attached function. It needs an
interrupt to work.
The syntax is:

1. attachInterrupt(digitalPinToInterrupt(pin), ISR, mode)


The above syntax is mostly recommended.

AD

The syntax that is not recommended is:

1. attachInterrupt(interrupt, ISR, mode)


The syntax that is suitable for Due, Uno WiFi Rev2, Arduino SAMD Boards, and 101 is:

1. attachInterrupt(pin, ISR, mode)


where,

interrupt: It includes the number of the interrupt.

The data type used here is int.

pin: It includes the specified pin number of the Arduino board.

mode: It determines when the interrupt might be triggered in Arduino.

ISR: It stands for Interrupt Service Routine. It is called when the interrupts arise. It does
not include any parameters.

There are four modes or constants, which are listed below:

o LOW
It is used to trigger the interrupt when the specified pin is low.

o FALLING
It is used to trigger the interrupt when the specified pin goes from high to low.

o CHANGE
It is used to trigger the interrupt when the specified pin changes the value.

o RISING
It is used to trigger the interrupt when the specified pin goes from low to high.
Code Example
Let's understand with an example.

Consider the below code:

1. const byte LEDPin = 13;


2. const byte PINofInterrupt = 2;
3. volatile byte state = LOW;
4. void setup() {
5. // other declaration
6. attachInterrupt(digitalPinToInterrupt(PINofInterrupt), blink, CHANGE);
7. }
8. void loop()
9. {
10. digitalWrite(LEDPin, state);
11. }
12. void blink()
13. {
14. // condition specified here
15. }

detachInterrupt()
The detachInterrupt( ) is used to turn off the given or current interrupt.

The syntax is:

1. detachInterrupt(digitalPinToInterrupt(pin))
The above syntax is probably recommended.

The syntax that is not recommended is:

1. detachInterrupt(interrupt)
The syntax that is suitable for Due, Uno WiFi Rev2, Arduino SAMD Boards, and 101 is:

1. detachInterrupt(pin)
where,

interrupt: It includes the number of the interrupt that we want to disable.

pin: It is the pin number of the Arduino board, which is used for the interrupt to disable.
Arduino SPI
The SPI (Serial Peripheral Interface) is a serial data protocol. The microcontrollers use
the serial protocol to communicate over short distances with one or more peripheral devices
quickly.

The required connection of SPI is a full-duplex that allows devices to simultaneously sent
and receive data. It uses four conductors for data receiving, data sending,
synchronization, and device selection for communication.

The SPI uses a master-slave architecture, where one Master device controls the peripheral
devices.

The SPI has four lines, which are listed below:

o MISO
It stands for Master Input/ Slave Output. The slave line in the MISO pin is used to send
the data to the master.

o MOSI
AD

It stands for Master Output/ Slave Input.

The MOSI and SCK are driven by the Master.

o SCK
It stands for Serial Clock. These are the clock pulses, which are used to synchronize the
transmission of data.

In slave, it works as the input of the clock generator. In master, it works as the output clock.
The data generated by the master is synchronized by the SCK.

o SS
It stands for Slave Select. It is the Slave Select line, which is used by the master. It acts as
the enable line.

When,

SS = LOW

The device interface with the master, when SS is low.

SS = HIGH

The device does not notice the master. It allows us to share the same MISO, CLK, and
MOSI with the multiples SPI devices.
The SPI is a synchronous interface that has a structure of one master and multiple slave
communication.

Working of SPI
The SPI uses four lines for communication that are listed above (MISO, MOSI, CLK, and
SS). A master in the connection is popularly a microcontroller, and the slave can be a
sensor, ADC (Analog to Digital Converter), LCD (Liquid Crystal Display), DAC (Digital to
Analog Converter), etc.

AD

Let's understand the connection of the Master SPI with a slave.

Consider the below examples.

Example 1: Master SPI with a single slave.


Consider the below image:

The arrow sign of MISO is in the opposite direction because it is a slave line that sends data
to the master.

All other lines are directed from the master only.

AD

AD

Example 2: Master SPI with two slaves.


Here, the SPI Master is communicating with two SPI slaves. The individual pins of the SPI
master are connected to SS of each slave.

SPI Pins
Let's discuss the SPI Master and Slave pins on the Arduino board.

The ICSP Header includes 6 pins. The structure is shown below:

The pin number of the SPI pins is listed below:

MOSI -4
MISO -1
SCK - 3
The SPI pins on different Arduino boards are listed below:

Arduino UNO

MOSI - 11
MISO - 12
SCK - 13

Arduino Due

MOSI -4
MISO -1
SCK - 3

Arduino Zero

MOSI -4
MISO -1
SCK - 3

Arduino Mega2560 or Mega1280

MOSI - 51
MISO - 50
SCK - 52

SPI Library
The library of SPI is:

1. # include <SPI.h>
The SPI library allows us to communicate as a master device with the Arduino and the SPI
devices.

AD

SPI Modes
There are four modes of SPI, which combine the clock phase (CPHA), and clock polarity
(CPOL). These modes are called the four modes of transmission in SPI.

The clock phase is determined as the data clock signal and clock polarity determines the
idle state of the high or low signal.

The SPI modes control the shifted in and out state. The state lies on the rising and falling
edge of the clock polarity and clock phase.

The four modes are discussed below:


Mode 0 - Here, the clock polarity is 0 (CPOL = 0), while the clock phase is 0 (CPHA = 0).
The data is captured at the Rising edge, and the output edge is Falling.

Mode 1- Here, the clock polarity is 0 (CPOL = 0), while the clock phase is 1 (CPHA = 1).
The data is captured at the Falling edge, and the output edge is Rising.

Mode 2- Here, the clock polarity is 1 (CPOL = 1), while clock phase is 0 (CPHA = 0). The
data is captured at the Falling edge, and the output edge is Rising.

Mode 3- Here, the clock polarity is 1 (CPOL = 1), while clock phase is 1 (CPHA = 1). The
data is captured at the Rising edge, and the output edge is Falling.

SPI Programming
We have to declare the SPI library before beginning with the SPI programming in Arduino.

SPI Speed
The SPI automatically uses the best speed, which is less or equal than the specified speed
number in the SPISettings. If we are using a chip rate of 15MHz, we can use the data speed
of 15000000.

If we are using a chip rate of 20MHz, we can use the data speed of 20000000.

Functions
The functions used for SPI programming are given below:

o begin()
The SPI.begin() function is used to initialize the bus by setting the SS, SCK, and MOSI pins
to the outputs.

It pulls the lines at the state shown below:

SS = High

SCK, MOSI = Low

The syntax is:

1. SPI.begin()

o SPISettings
It is the object that is used to configure the SPI port for the particular SPI device. It includes
three parameters, which are combined with this object.
The syntax is:

1. SPI.beginTransaction(SPISettings(12000000, MSBFIRST, SPI_MODE0))


The SPISettings can be directly declared inside the SPI.beginTransaction() function if the
three parameters are constant. We can create the SPISettings object if any of the settings
are variables.

The syntax is:

1. SPISettings mySettting(speedMaximum, dataOrder, dataMode)


where,

speedMaximum = It defines the maximum speed of communication.

dataOrder= LSBFIRST (Least Significant Bit First) or MSBFIRST (Most Significant Bit
First).

Most of the data bits in SPI uses the MSBFirst.

dataMode= It includes four modes.

SPI_MODE1, SPI_MODE2, SPI_MODE3, and SPI_MODE4

o beginTransaction()
The beginTransaction() function is used to initialize the SPI bus by using the defined
SPISettings.

The syntax is:

1. SPI.beginTransaction(mysettings);

o end()
The end() function is used to disable the SPI bus without changing the pin modes.

The syntax is:

1. SPI.end()

o transfer()
The transfer() function is used to transfer the data. We can call the function number of
times.

o endTransaction()
The endTransaction() function is used to stop the bus.

The syntax is:


1. SPI.endTransaction()

o setClockDivider()
The setClockDivider() function is used to set the clock divider with respect to the system
clock.

The clock in AVR boards can be divided with the available divider value of 2, 4, 8, 16, 32,
64, and 128. The default value is 4, which is represented as SPI_CLOCK_DIV4 (for
example, 5MHz for the board at 20MHz). Similarly, other value will be represented.

The clock in Arduino due can be divided with the available divider values from 1 to 255,
where 21 is the default value.

The syntax is:

1. SPI.setClockDivider(divider value)

o setDataMode()
The setDataMode() function is used to set the data mode in the SPISettings.

The syntax is:

1. SPI.setDataMode()

o setBitOrder()
The setBitOrder() function is used to set the order of the bits. These bits are shifted in and
out of the Serial Peripheral Interface Bus.

The order of bits is set either as LSBFirst (Least Significant Bit First) or MSBFirst (Most
Significant Bit First).

The syntax is:

1. SPI.setBitOrder(order)

What are the Arduino sensors?


Arduino is the open-source platform used for making custom electronics projects. Before
learning about the Arduino Sensors, lets first understand the sensors as a general term.
What are the sensors?
The sensors are defined as a machine, module, or a device that detect changes in the
environment. The sensors transfer those changes to the electronic devices in the form of a
signal.

A sensor and electronic devices always work together. The output signal is easily readable
by humans.

Nowadays, Sensors are used in daily lives. For example, controlling the brightness of the
lamp by touching its base, etc. The use of sensors is expanding with new technologies.

AD

What is a sensor made of?


The sensor is a device, which is made up of Single Crystal Silicon. It is considered as a
widely used semiconductor material. It has superior mechanical stability, machinability, etc.
It can also combine electronics and sensing elements on the same substrate.

Where are the sensors used?


The sensors are used to measure the physical quantities, such as pressure, temperature,
sound, humidity, and light, etc.

An example of sensors is Fire Alarm, a detector present on the fire alarm detects the smoke
or heat. The signal generated from the detector is sent to the alarming system, which
produces an alert in the form of alarm.

The types of detectors are smoke detectors, heat detectors, carbon monoxide detectors,
multi-sensors detectors, etc.

How are the sensors used in Arduino?


The data signal runs from the sensor to the output pins of the Arduino. The data is further
recorded by the Arduino.

We will discuss various sensors further.

What are the types of sensors in Arduino?


Some of the types of sensors in Arduino are listed below:

o Light sensor
The light sensor is used to control the light. It is used with LDR (Light Dependent Resistor)
in Arduino.
o Ultrasonic sensor
AD

The ultrasonic sensor is used to determine the distance of the object using SONAR.

o Temperature sensor
The temperature sensor is used to detect the temperature around it.

o Knock Sensor
The knock sensor is used to pick the vibrations of the knocking. It is a common category of
a vibration sensor.

o Object Detection Sensor


It is used to detect the object by emitting infrared radiations, which are reflected or bounced
back by that object.

o Tracking Sensor
It allows the robots to follow a particular path specified by sensing the marking or lines on
the surface.

AD

o Metal Touch Sensor


It is suitable for detecting the human touch.

o Water Level Sensor


It is used to measure the water or the depth of the water level. It is also used to detect leaks
in containers.

o Vibration Sensor
The vibration sensor is used to measure the vibrations.

o Air Pressure sensor


It is commonly related to meteorology, biomedical fields. It looks like the below image:
o Pulse Sensor
The pulse sensor is used to measure the pulse rate. It looks like the below image:

AD

o Capacitive soil moisture sensor


It is used to measure the moisture level of the soil.

o Microphone sensor
The microphone sensor in Arduino is used to detect the sound. The analog and digital are
the two outputs of this module. The digital output sends the high signal when the intensity of
sound reaches a certain threshold. We can adjust the sensitivity of a module with the help
of a potentiometer.

o humidity sensor
The humidity sensor is used to monitor weather conditions.

o Motion sensor
The motion sensor detects the movement and occupancy from the human body with the
help of Infrared radiation.

o Vibration sensor
The vibration sensor is used to detect the vibrations.

o Sound sensor
The sound sensor is suitable to detect the sound of the environment.

o Pressure Sensor
The pressure sensor is used to measure the pressure. The sensor in Arduino measures the
pressure and displays it on the small LCD screen.

o Magnetic field sensor


The magnetic field sensor measures the magnetic field strength and produces a varying
voltage as the output in Arduino.

rduino LDR
Arduino LDR (Light Dependent Resistor) project uses the photoresistor to light an LED. The
LED will light up whenever there is dark or no light over the sensor.

What is photoresistor?

It is defined as a light-controlled resistor, which is also called as LDR. It is a variable


resistor that controls the resistance in accordance with the received light intensity. It means,
the resistance decreases as intensity of light increases.

Let's start with the project.

Hardware Required
The components required for the project are listed below:

o 1 x red LED
o 1 x 220 Ohm Resistor
o 1 x 10K Ohm Resistor
o Arduino UNO R3 board
o Jump wires
o 1 x photoresistor
We can use any color LED as per our choice.

AD

Structure of the project


The structure of the project is shown below:
How to calculate the output voltage using photoresistor?

The structure of photoresistor is shown below:

The formula to calculate the dark output voltage is given below:


where,

Vin = 5V

Vout = Output voltage

Here, R2 is the resistance connected in series with the photoresistor = 10K Ohm.

R1 is the resistance of the photoresistor.

Note: The resistance decreases with increasing light. Hence, the output voltage
will increase. It means that the output voltage calculated at the light will be
higher than the output voltage calculated at dark.
Here, dark and light specify the light falling on the sensor.

Connection
The connection of the above project is discussed below:

AD

o Connect the positive leg of the LED in series with the resistor to the pin number 12 of the
Arduino board.
o Connect the negative leg of the LED to the Ground.
o Connect one edge of the photoresistor to the 5V pin on the Arduino board.
o Attach a 10K ohm resistance in series with another edge of the photoresistor and
connect it to the GND.
o Connect the edge of the photoresistor to the analog pin A0.
AD

Note: We have connected the LED only to enhance the project. We can also
create the project without using the LED. It will not impact the output.

Sketch
Consider the below code:

1. const int LEDpin = 12;


2. const int photoPIN = A0;
3.
4. void setup() {
5. // initializing the serial communication:
6. Serial.begin(9600);
7. pinMode(photoPIN, INPUT);
8. pinMode(LEDpin, OUTPUT);
9. }
10. void loop() {
11. // read the sensor:
12. int sensorStatus = analogRead(photoPIN);
13. // now, it will check the reading or status of the sensor is < 200
14. // if it is, LED will be HIGH
15. if (sensorStatus <200)
16. {
17. digitalWrite(LEDpin, HIGH); // LED is ON
18. Serial.println(" LED is ON, status of sensor is DARK");
19. }
20. else
21. {
22. digitalWrite(LEDpin, LOW);
23. Serial.println(" ***************");
24. }
25. }

Connection Diagram
The connection diagram is shown below:

Output
The output on the serial monitor will appear as:

LED is one because there is dark over the sensor.

AD

Arduino Accelerometer
In this topic, we will discuss a project based on an accelerometer. The value will be read
from the series of accelerometer and received in the Arduino IDE's serial monitor. It means
the data will be read and received over the serial port.

We will use a three-axis accelerometer that gives acceleration for each Axis as an analog
voltage for separate pins.

We would be using the ADXL3xx accelerometer series. For example, ADXL320, ADXL322,
ADXL321, ADXL335, etc.

In this project, we are going to work with the ADXL335 accelerometer.

What is accelerometer?

The accelerometer is the device capable of detecting changes in motion in the form of
acceleration. It can also measure the vibration of a structure.

The acceleration is defined as the change in speed or velocity over time.

The motion sensors are present inside the accelerometer.

How does accelerometer work?

The acceleration (change in motion) or the vibration generates the force that causes the
piezoelectric material to be stressed. The microscopic crystals structure present in it creates
the voltage from the stress. The accelerometer interprets this voltage. The voltage is further
used to determine the orientation and velocity.
Usage of Accelerometer

The uses of the accelerometer are listed below:

o It is used to detect earthquakes due to the presence of a motion sensor.


o It is present on the laptop, which protects the hard drives from damage.
o It is used to create custom projects.
o It can determine the movements (uphill, etc.) of the object.

ADXL335 Accelerometer
The structure of ADXL335 is shown below:

The position of the three axis (X-axis, Y-axis, and Z-axis) will change according to the
ADXL335 accelerometer's position.

If we hold the board in a different position, the direction of the three-axis will also change.
Moving the board in a particular direction will cause a change in the voltage of the
respective axis. We can measure the changed voltage on the Arduino.

When we hold the board up and flat, the measured acceleration of 9.8m/s^2 will appear on
the Z-axis.

It is also called as the gravity. Here,

AD

1.0G = of 9.8m/s^2

where,

G is the acceleration due to earth gravity.

The sensitivity of ADXL335 accelerometer is:

s = 0.33V/G.
Gravity force per ADC (Analog to Digital Converter) unit is:

AD

It is because the sensors need 3.3V to operate.

The accelerometer at rest will read half of its maximum analog voltage.

Note: Some accelerometers work at 5V while some at 3.3V. We need to make


sure about the voltage because the 3.3V accelerometer may be damaged with a
5V supply.
Let's start the project.

Hardware Required
The components required for the project are listed below:

o 1 x ADXL335 accelerometer
o 1 x Arduino UNO R3
AD

AD

Principle
We can directly plugged-in the accelerometer onto the Arduino. It is because the
accelerometer operates on minimal current.

The Arduino UNO has six analog pins. The three analog pins will be connected to the Vcc,
Self-Test, and the Ground pin. The other three analog pins will be used to read the analog
output of the accelerometer.

Structure
The structure of the project is shown below:
Connection
The connection for the above project is explained below:

o Connect X of the accelerometer to the analog pin A3 of the Arduino board.


o Connect Y of the accelerometer to the analog pin A2 of the Arduino board.
o Connect X of the accelerometer to analog pin A1 of the Arduino board.
o Connect Vcc of the accelerometer to analog pin A5 of the Arduino board.
o Connect GND of the accelerometer to analog pin A4 of the Arduino board.
o Connect ST of the accelerometer to analog pin Ao of the Arduino board.

Sketch
We will upload the code on the Arduino connected with the accelerometer. The output can
be clearly seen on the Serial Monitor in the Arduino IDE.

Consider the below code:


1. const int GND = A4;
2. const int PowerPIN = A5;
3. const int pinOfX = A3;
4. const int pinOfY= A2;
5. const int pinOfZ= A1;
6. void setup()
7. {
8. Serial.begin(9600);
9. pinMode(GND , OUTPUT);
10. pinMode(PowerPIN , OUTPUT);
11. digitalWrite(GND , LOW); // configuring the GND pin as LOW
12. digitalWrite(PowerPIN , HIGH); // configuring the power pin HIGH (5V/3.3V)
13. }
14. void loop()
15. {
16. // It prints the values of the sensors
17. Serial.print(analogRead(pinOfX)); // print a tab between values:
18. Serial.print("\t");
19. Serial.print(analogRead(pinOfY));
20. Serial.print("\t");
21. Serial.print(analogRead(pinOfZ));
22. Serial.println(); // It delays before next reading
23. delay(100);
24. }

Arduino Ultrasonic distance sensor


The Ultrasonic sensor or HC-SRO4 is used to measure the distance of the object using
SONAR.

It emits the Ultrasound at a frequency of 40KHZ or 40000 Hz. The frequency travels
through the air and strikes the object on its path. The rays bounce back from the object and
reach back to the module.

The four terminals of HC-SRO4 are VCC, TRIG, ECHO, and GND. The voltage supply or
VCC is +5V. We can connect the ECHO and TRIG terminal to any of the digital I/O pin on
the specific Arduino board.

The Ultrasonic sensors work best for medium ranges.

The resolution is 0.3cm.

The medium ranges of the sensor are 10cm to 3m. It works best at this duration.

The maximum range the sensor may detect is 4.5m.


How does Ultrasonic sensor work?
Let's understand how the sensor works.

o It sends ultra-high frequency samples.

o When samples strike the object, it bounces back from the object.
AD

o The distance sensor reports the time it takes between the sending and receiving of the
samples.
AD

Example
Let's consider an example.

An object is 40cm away from the Ultrasonic sensor. The speed of sound in air is
340m/s. We need to calculate the time (in Microseconds).

Solution:

v = 340m/s = 0.034cm/us (centimeter/microseconds)


time = distance/speed
time = 40/0.034
time = 1176 microseconds
The speed of sound from the echo pin will double because the wave travels forward and
backward (bounces).

So, to calculate the distance, we need to divide it by 2. It is shown below:

distance = time x speed of sound/2


distance = time x 0.034/2

Structure of Ultrasonic Sensor


The structure of HC-SRO4 is shown below:

Ultrasonic sensor Timing Diagram


We will set the TRIG pin to HIGH for some time (about 3 to 100 microseconds). As soon the
TRIG pin is LOW, the Ultrasonic sensor sends the pulses and sets the ECHO pin to HIGH.
When the sensor gets the reflected pulses, it sets the ECHO pin to LOW. We need to
measure the time for which the ECHO pin was HIGH.

The timing diagram of the ultrasonic sensor HC-SRO4 is shown below:


Let's start creating the Arduino ultrasonic sensor to measure distance.

AD

Hardware Required
The components required to create the project are listed below:

o Arduino UNO R3 board (We can also use any Arduino board)
o Jump wires
o Ultrasonic sensor HC-SRO4
o Breadboard

Principle
We need to first set the TRIG (triggered) pin at HIGH. It will send out the burst of 8 cycles
called the sonic burst, which will travel at the sound speed. It will be further received by the
ECHO pin. The time traveled by the sound wave is considered the ECHO pin's output time
in microseconds.
We will use the PulseIn() function to read the time from the output of the ECHO pin. It will
wait for the specified pin to go HIGH and LOW. The function would return the timing at the
end.

The TRIG pin is set LOW for 4 microseconds and then HIGH for 15 microseconds.

The timing will be calculated in microseconds.

AD

AD

Procedure
The steps to connect the Ultrasonic sensor to the board are listed below:

o Connect the VCC pin of HC-SRO4 to 5V of the Arduino board.


o Connect the GND pin of HC-SRO4 to GND of the Arduino board.
o Connect the TRIG pin of HC-SRO4 to pin 6 of the Arduino board.
o Connect the ECHO pin of HC-SRO4 to pin 5 of the Arduino board.

Sketch
Consider the below code:

1. #define ECHOpin 5 // it defines the ECHO pin of the sensor to pin 5 of Arduino
2. #define TRIGpin 6
3. // we have defined the variable
4. long duration; // variable for the duration of sound wave travel
5. int distance; // variable for the distance measurement
6. void setup()
7. {
8. pinMode(TRIGpin, OUTPUT); // It sets the ECHO pin as OUTPUT
9. pinMode(ECHOpin, INPUT); // It sets the TRIG pin as INPUT
10. Serial.begin(9600); // // Serial Communication at the rate of 9600 bps
11. Serial.println("Test of the Ultrasonic Sensor HC-SR04"); // It will appear on Serial Monitor
12. Serial.println("with the Arduino UNO R3 board");
13. }
14. void loop()
15. {
16. // It first sets the TRIG pin at LOW for 2 microseconds
17. digitalWrite(TRIGpin, LOW);
18. delayMicroseconds(4);
19. // It now sets TRIG pin at HIGH for 15 microseconds
20. digitalWrite(TRIGpin, HIGH);
21. delayMicroseconds(15);
22. digitalWrite(TRIGpin, LOW);
23. // It will read the ECHO pin and will return the time
24. duration = pulseIn(ECHOpin, HIGH);
25. // distance formula
26. distance = duration*(0.034/2); // (speed in microseconds)
27. // Speed of sound wave (340 m/s)divided by 2 (forward and backward bounce)
28. // To display the distance on Serial Monitor
29. Serial.print("Distance: ");
30. Serial.print(distance);
31. Serial.println(" cm"); //specified unit of distance
32. }
AD

Steps to upload the code to the project


The steps are listed below:

o Open the Arduino IDE.


o Select the type of board from Tools -> Board -> Arduino UNO.
o Select the port from Tools -> Port -> COM..
o Upload the sketch to the connection diagram.

Connection Diagram
The connection diagram is shown below:
Output

The output on the serial monitor will appear as:

Arduino Ultrasonic Range finder


In previous topic of Arduino Ultrasonic Distance Sensor, we have used a four-terminal
Ultrasonic sensor.

Here, we will use a three-terminal Ultrasonic sensor, which is shown below:


It has three terminal GND (Ground), 5V, and SIG (signal). The process and the function of
this sensor is similar to the Ultrasonic Distance Sensor.

The frequency waves travel through the air and strike the object on its path. The waves
bounce back from the object and reach back to the module.

The Ultrasonic Range sensor pings the obstacles or objects with the ultrasound.

It detects the range from 3 cm or 4m or 400 cm.

The example of such a sensor is:

SEN136B5B
It is a sensor from SeedStudio. We need to switch the state between HIGH and LOW to
notice the output.

Let's start the project.

Hardware Required
The components required to create the project are listed below:

o Arduino UNO R3 board (We can also use any Arduino board)
o Jump wires
o Ultrasonic sensor
o Breadboard
AD

Structure of the project


The structure of the project is shown below:
Procedure
The steps to connect the Ultrasonic sensor to the board are listed below:

o Connect 5V pin of the sensor to 5V of the Arduino board.


o Connect the GND pin of the sensor to the GND of the Arduino board.
o Connect the SIG pin of the sensor to pin 8 of the Arduino board.
AD

Sketch
Consider the below code:

1. const int pinTOping = 7;


2. void setup() {
3.
4. Serial.begin(9600); //Serial communication at 9600 bps rate
5. Serial.println("Test for the Ultrasonic range sensor");
6. }
7. void loop()
8. {
9. // initialzing the variables using long data type
10. long TIMEduration, in, cm;
11. // The PING))) is triggered by a HIGH pulse valu2 of 2 or more microseconds.
12. // We have specified short time to clean HIGH pulse:
13. pinMode(pinTOping, OUTPUT);
14. digitalWrite(pinTOping, LOW);
15. delayMicroseconds(4);
16. digitalWrite(pinTOping, HIGH);
17. delayMicroseconds(8);
18. digitalWrite(pinTOping, LOW);
19. // We have used the same pin to read the signal from the PING)), which is a HIGH pulse
20. // the time is measured in microseconds
21. pinMode(pinTOping, INPUT);
22. TIMEduration = pulseIn(pinTOping, HIGH);
23. // convert the time into a distance
24. in = microsecondsToIn(TIMEduration);
25. cm = microsecondsToCm(TIMEduration);
26. Serial.print(in);
27. Serial.print("inches, ");
28. Serial.print(cm);
29. Serial.print("centimeters");
30. Serial.println();
31. delay(200); //time delay of 200 microseconds
32. }
33. long microsecondsToIn(long microseconds) {
34. // there are 73.746 microseconds per inch according to PING datasheet
35. // we need to divide the distance by 2
36. //It is because the ping travels forward and bounces backward
37. return microseconds / 74 / 2;
38. }
39. long microsecondsToCm(long microseconds) {
40. // The speed of sound is 340 m/s
41. return microseconds / 29 / 2;
42. }

Steps to upload the code to the project


The steps are listed below:

o Open the Arduino IDE.


o Select the type of board from Tools -> Board -> Arduino UNO.
o Select the port from Tools -> Port -> COM.
o Upload the sketch to the connection diagram.
Connection Diagram
The connection diagram is shown below:

Output

The output on the serial monitor will appear as:

AD

Arduino temperature sensor


The temperature sensor in Arduino converts the surrounding temperature to voltage. It
further converts the voltage to Celcius, Celcius to Fahrenheit, and prints the Fahrenheit
temperature on the LCD screen.

We will use a temperature sensor (TMP 36) of low voltage. Such sensors are also stable
while dealing with large capacitive loads. It is also suitable for automotive applications.
The temperature sensors TMP 35, TMP 36, and TMP 37 are the sensors with the same
features.

The operating voltage of the TMP 36 sensor ranges from 2.7V to 5.5V.

The sensor will look like the image shown below:

It has three terminals, which are listed below:

o Pin 1: DC voltage
Here, we will connect the DC voltage pin to 5V on the Arduino UNO board.

o Pin 2: Analog voltage output


AD

We will consider the Analog voltage output pin as the output.

o Pin 3: GND
We will connect the GND pin to Ground on the Arduino UNO board.

Let's start the project.

Hardware Required
The components required for the project are listed below:

o 1 x TMP 36 sensor (Temperature sensor)


o 1 x LCD display
o Arduino UNO R3 board (We can take any Arduino board).
o Jump wires
AD

Principle
We will connect the LCD Display and TMP 36 temperature sensor with the Arduino UNO R3
board. The sensor detects the surrounding temperature and converts it into volts, to Celsius
to Fahrenheit, and displays Fahrenheit temperature on the LCD screen.

We need to open the URL: Arduino LCD display for details about LCD display.

Connection
The steps to set up the connection are listed below:

o Connect the RS pin of LCD to pin 13 of the Arduino board.


o Connect the Enable pin of LCD to pin 12 of the Arduino board.
o Connect the D4 pin of LCD to pin 6 of the Arduino board.
o Connect the D5 pin of LCD to pin 4 of the Arduino board.
o Connect the D6 pin of LCD to pin 3 of the Arduino board.
o Connect the D7 pin of LCD to pin 2 of the Arduino board.
o Connect the Vo pin of LCD to pin 8 of the Arduino board.
o Connect the middle terminal to a sensor to A0(analog pin).
o Connect one end of the sensor to GND and another end to 5V.
o Connect one end of a resistor to the A and K of the LCD and another end to 5V.
Sketch

Consider the below code:

1. #include <LiquidCrystal.h>
2. // initialize the library with the pins on the Arduino board
3. LiquidCrystal lcd(13, 12, 6, 4, 3, 2);
4. const int temperature = A0; //A0 is the analog pin
5. const int D = 8; // Vo of LCD is connected to pin 8 of the Arduino
6. void setup()
7. {
8. lcd.begin(16, 2);
9. Serial.begin(9600);
10. pinMode(D, OUTPUT);
11. }
12. void loop()
13. {
14. digitalWrite(D,LOW);
15. int Temp = analogRead(temperature);
16. float volts = (Temp / 965.0) * 5;
17. float celcius = (volts - 0.5) * 100;
18. float fahrenheit = (celcius * 9 / 5 + 32);
19. Serial.println(fahrenheit);
20. lcd.setCursor(5, 0);
21. lcd.print(fahrenheit);
22. delay(2000);
23. // time delay of 2000 microseconds or 2 seconds
24. }
We will show the connection using the Simulator because the connections become clearer
and more precise.

AD

We can make the same connection using the hardware devices.

Output

The output is now visible on the LCD screen.

For better understanding, let's consider the output on the Serial Monitor.

It is the temperature in Fahrenheit.

AD
Arduino Motion Sensor
We will use a PIR motion sensor in this project. All objects (having temperature higher than
absolute zero) emit radiations from the generated heat. These radiations cannot be
detected by a human eye. Hence, electronic devices such as motion sensors, etc. are used
for the detection of these radiations.

What is a PIR sensor?


The Passive Infra-Red sensors or PIR sensors detect motion or movement of an object that
detect infrared radiations, such as the human body. Hence, the use of sensors is very
common.

The advantages of using a PIR sensor are listed below:

o Inexpensive
o Adjustable module
o Efficient
o Small in size
o Less power consumption
o It can detect motion in the dark as well as light.
The PIR sensor is shown below:

The PIR sensor has three terminals, which are listed below:

o VCC
o Digital Output
o GND (Ground)
AD

We will connect the Vcc terminal of the sensor to the 5V on the Arduino board. The PIR's
sensor output can be connected to any of the digital pins on the Arduino board.
The applications of the PIR sensor are automation, security systems, etc. Such sensors
work great in detecting the entrance of a person in an area and leaving it.

The detection range of PIR sensors is from 5m to 12m.

AD

Working of PIR Sensors


The working of the PIR sensor is entirely based on detecting the IR (Infra-Red) radiations,
which are either emitted or reflected by the objects.

The infrared radiations are detected by the crystalline material present at the center of the
sensor.

Consider a person passing in front of the background like a wall, etc. The temperature
changes from room to body temperature and vice-versa within the sensor field. Changes
arising in the arrival infrared radiations are converted by the sensor to the output voltage. It
later detects the human body or object.

Structure of PIR Sensor


A round metal can is mounted on the center with the rectangular crystal that detects the IR
radiations.

A ball like a lens present on some sensors helps in enhancing the viewing angle.

The bottom part of the sensor contains many circuits mounted on it, which is shown below:
Let's start with the project.

Hardware Required
The components required for the project are listed below:

o 1 x PIR motion sensor


o Arduino UNO R3 board (We can take any Arduino board).
o Jump wires
o 1 x red LED (we can take LED of any color)
o 1 x 220 Ohm resistor

Principle
The movement of jumper present on the sensor on the L side will cause a change in the
state of the sensor whenever the motion is detected. Such a condition is defined as a single
trigger mode.

AD
When the sensor resets the timer after every detection of motion, it is defined as repeated
trigger mode.

The two potentiometers present on the sensor are called as Sensitivity Potentiometer
and Time Potentiometer. We can adjust both the parameters (time and sensitivity)
accordingly.

It should be restricted for atleast 15 seconds in front of the PIR sensor for proper calibration
in the output. After 15 seconds, the sensor can easily detect movements.

If any movement is detected, the LED will be HIGH. If there is no such movement, the
output will be LOW.

Connection
The steps to set up the connection are listed below:

AD

o Connect the Vcc terminal of the PIR sensor to the 5V pin of the Arduino board.
o Connect the Output terminal of the PIR sensor to pin 8 of the Arduino board.
o Connect the GND terminal of the PIR sensor to the Ground pin of the Arduino board.
o Connect the positive leg of the LED in series with 220 Ohm resistor to pin 13 of the
Arduino board.
o Connect the negative terminal of the LED to the Ground pin of the Arduino board.
AD

Sketch
Consider the below code:

1. int LEDpin = 13; // LED pin


2. int PIRpin = 8; // The pin of Arduino connected to the PIR output
3. int PIRvalue = 0; // It specifies the status of PIR sensor
4. void setup() {
5. pinMode(LEDpin, OUTPUT);
6. pinMode(PIRpin, INPUT);
7. // the output from the sensor is considered as input for Arduino
8. Serial.begin(9600);
9. }
10. void loop()
11. {
12. PIRvalue = digitalRead(PIRpin);
13. if (PIRvalue == HIGH)
14. {
15. digitalWrite(LEDpin, HIGH);
16. // turn ON LED if the motion is detected
17. Serial.println("hello, I found you...heyyy..");
18. }
19. else
20. {
21. digitalWrite(LEDpin, LOW);
22. // LED will turn OFF if we have no motion
23. Serial.println("I cannot find you");
24. delay(1000);
25. }
26. }

Steps to upload the code to the project


The steps are listed below:

o Open the Arduino IDE.


o Select the type of board from Tools -> Board -> Arduino UNO.
o Select the port from Tools -> Port -> COM..
o Upload the sketch to the connection diagram.

Connection Diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


The output will be based on the detection.

Arduino Stepper motor


The stepper motor does not require any feedback for its operation. It can be controlled with
high accuracy due to its design.

The series of magnets mounted on the shaft of the stepper motor are controlled by the
electromagnetic coils. These coils are negatively and positively charged in a sequence,
which makes the shaft to move in forward and backward in little steps.

We can also hold the position of the motor at any step during rotation. It has a simple,
accurate open-loop system.

The Stepper is categorized into two types, which are listed below:

o Unipolar
o Bipolar
Each type possesses a different circuit, but the coding is similar.

Unipolar

The Unipolar stepper motor consists of one winding that operates with a center tap per
phase. There are three leads per phase in the motor. For the regular two-phase stepper
motor, there are six leads per phase.

The Unipolar stepper motor has five leads when both the phases are joined internally.

Bipolar

The bipolar stepper motor consists of a single winding per phase. There are two leads per
phase in the motor.

The bipolar stepper motors do not have any center tape connections. Such devices are
used when we require high torque popularly at low speeds.

How Stepper motor works?


The stepper motor can control the angular position of the rotor without a closed feedback
loop.

For example,

Consider a motor with six stator teeth and a rotor. It is shown below:

A stepper motor with six stator teeth can be triggered with three different DC power
sources. The rotor in the stepper motor is made up of a stack of steel laminations. It has
different teeth compared to the rotor, which is four.

It is done so that one pair of rotor teeth at a time can be aligned easily with the stator.
If we trigger or energize the coil A and B, the rotor would rotate. The above figure signifies
the step size is 30 degrees. We will energize coil B and C. After that, the coil A will energize
again. It means that the rotor moves to the position with the least reluctance.

AD

The position of the rotor, when coil A is energized is shown below:

The position of the rotor (moves 30 degrees), when coil B is energized is shown below:

When both the coils are excited, the position of the rotor (in between) is shown below:
The energizing of both the coils change the accuracy of the rotor from 30 degrees to 15
degrees.

The common stepper motor type is the hybrid motor type.

AD

In this project, we will use the hybrid motor type. It looks like the image shown below:

AD

Hardware Required
The required components are listed below:

o 1 x Arduino UNO R3 (We can use any Arduino board)


o 1 x Breadboard
o Jump Wires
o 1 x 10K Ohm Potentiometer
o 1 x Stepper motor
o 1 x power supply (according to the stepper)
o U2004 Darlington Array (For a Unipolar stepper)
o SN754410ne H-Bridge (for a bipolar stepper)
AD

Connection diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.

Sketch
Consider the below code:

1. #include <Stepper.h> //library declared for the operation of stepper motor


2.
3. const int stepsPERrevolution = 200; // We can change it according to the required steps per re
volution
4. // for our motor
5.
6.
7. // the initialization of pins 8 to 11 of stepper library
8. Stepper myStepper(stepsPERrevolution, 8, 9, 10, 11);
9.
10. int CountofSTEP = 0; // number of steps the motor has taken
11.
12. void setup()
13. {
14. Serial.begin(9600);
15. }
16.
17. void loop()
18. {
19. // read the sensor value:
20. int ReadingINSensor = analogRead(A1);
21. // we can map it to a range from 0 to 100:
22. int SpeedOFmotor = map(ReadingINSensor, 0, 1023, 0, 100);
23. // to set the speed of the motor
24. if (SpeedOFmotor > 0)
25. {
26. myStepper.setSpeed(SpeedOFmotor);
27. // step 1/100 of a revolution
28. myStepper.step(stepsPERrevolution/ 100);
29. }
30. }

Procedure
The steps to establish the above connection are listed below:

o Connect the negative and positive terminal of the battery to the GND and 5V pin of the
Arduino board.
o One outer pin of the potentiometer is connected to ground (GND), and the other external
pin is connected to 5V of the Arduino board.
o The middle pin of the potentiometer is connected to the analog input pin A1 of the board.
o Connect the 8 to 11 digital pins of the Arduino board to the U2004 Darlington Array,
which is further connected to the motor.
o Connect other pins of the U2004 Darlington Array to the stepper motor, as shown in the
connection diagram.

Arduino Servo Motor


The principle of the servo motor is based on Pulse Width modulation (PWM). It means that
the duration of pulses applied to the specific control pin controls the angle of rotation of the
motor.

The construction of the servo motor is similar to a DC motor. It means that it has a rotor,
stator, and control assemblies. It has closed-loop feedback for controlling the torque and
speed.

The advantages of a servo motor are listed below:

o High efficiency
o High output power
o Small size
o Good power
o High precision
o rapid acceleration of loads
The applications of servo motors are machinery, automated manufacturing, robotics, radio
controller airplanes, etc. The controller is considered as an essential part of the servo
motor.

The movement in a servo motor is determined by an electric signal that can be either digital
or analog.

The Servo library is the library that permits the Arduino to work with servo motors.

What is the Servo library, and why is it used?


The servo library allows controlling the integrated shaft and gears. We can also position
shaft at different angles between 0 and 180 degrees. The servo library on Arduino
boards can support upto 12 motors, while on Arduino Mega board, it can support upto 48
motors.

It is because servos do not interfere with the functionality of PWM pins on the Arduino Mega
board. On other Arduino boards, the servo library disables the PWM pin 9 and 10 even if
the servo is connected to these pins.

The use of motors on Mega is also limited. It means we can use 12 motors on Arduino
Mega. But, using 12 to 23 motors on the Mega board can disable the PWM functionality on
the pin number 11 and 12.

AD

What is the difference between a regular motor and a servo motor?


The difference between regular motor and servo motor are listed below:

o The output shaft of the servo motor can be moved to a specific velocity, position, and
angle while regular motors cannot.
o The feedback from the motor is used by the servo motor control loop, which helps the
motor to reach the desired velocity and position.
AD

What is the difference between a stepper motor and a servo motor?


The difference between stepper motor and servo motor are listed below:

o The servo motor requires a control loop feedback. The control loop is used to monitor
the current distance and velocity. Due to this, it is more reliable than the stepper motor.
o Servo motors usually have a low pole count while the stepper motors have high.
o The speed curve of the servo motor is more flexible compared to the stepper motor.
o The stepper motor has low speed and accuracy than the servo motor.

Project
Let's start the project with Arduino.

Here, the servo motor is simply connected to the Arduino.

Hardware Required
The components required for the project are listed below:

o 1 x Mini Servo motor


o Arduino UNO R3 board (We can take any Arduino board).
o Jump wires
Mini Servo Motor: It is defined as a tiny motor that can approximately rotate upto 180
degrees. It works similar to the usual servo motor, but smaller in size.

We can also use any servo motor. The connection and procedure would be the same.

Principle
The project allows us to control the shaft at angles between 0 and 180 degrees. We can
also set the rotation of the shaft at different speeds.

AD

Servo motor has three terminals signal, power, and ground. The signal terminal is usually
connected to the 5V pin of the Arduino board with the help of a wire.

The ground, power, and signal wire are represented by black, green, and red colors.

AD

Structure of the project


The structure of the connection or project is shown below:
Connection
The steps to set up the connection are listed below:

o Connect the signal terminal of the servo motor to the 5V pin of the Arduino board.
o Connect the power terminal of the servo motor to pin 5 of the Arduino board. We can
connect the power terminal of the motor to any digital PWM pin on the Arduino board.
o Connect the ground terminal of the servo motor to the GND pin of the Arduino board.

Sketch
Consider the below code:

AD

1. #include <Servo.h>
2. int POSservo = 0;
3. Servo servo_5;
4. void setup()
5. {
6. servo_5.attach(5); // power pin connected to pin 5 of Arduino board
7. // Here, the pin of the Arduino board connected to the servo should be a PWM pin
8. }
9. void loop()
10. {
11. // It will sweep the servo from 0 to 180 degrees
12. for (POSservo = 0; POSservo <= 180; POSservo=POSservo+1)
13. {
14. // tell servo to go to position in variable 'POSservo'
15. servo_5.write(POSservo);
16. // It will wait for the specified duration (20 milliseconds) to reach the position
17. delay(20); // delay of 15 millisecond(s)
18. }
19. for (POSservo = 180; POSservo >= 0;POSservo= POSservo-1)
20. {
21. // It will tell servo to go to position in the declared variable 'POSservo'
22. servo_5.write(POSservo);
23. delay(20);
24. // we can modify the duration as per the requirements
25. }
26. }

Steps to upload the code to the project


The steps are listed below:

o Open the Arduino IDE.


o Select the type of board from Tools -> Board -> Arduino UNO.
o Select the port from Tools -> Port -> COM..
o Upload the sketch to the connection diagram.

Connection Diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


Output

The shaft will rotate 90 degree in each direction i.e. approx. 180 degrees

Arduino Servomotor using Potentiometer


The Potentiometer will be used to control the position of the servo motor. The connection
will be similar to the last servo motor project, except the added Potentiometer.

Let's start with the project with Arduino.

Hardware Required
The components required for the project are listed below:

o 1 x Mini Servo motor


o Arduino UNO R3 board (We can take any Arduino board).
o Jump wires
o 1 x 10K Ohm potentiometer
Mini Servo Motor: It is defined as a tiny motor that can approximately rotate up to 180
degrees. It works similar to the usual servo motor, but smaller in size.

AD

Principle
The project allows us to control the shaft at angles between 0 and 180 degrees. We can
also set the rotation of the shaft at different speeds.

Servo motor has three terminals signal, power, and ground.


The power pin of the servo motor is connected to the PWM pin of the Arduino board. Here,
we have connected the power terminal to pin 9 of the Arduino UNO R3 board.

Structure of the project


The structure of the connection or project is shown below:

Sketch
Consider the below code:

1. #include <Servo.h>
2.
3. Servo myservo;
4. // It creates a servo object, which is used to control the servo
5.
6. int potentioPIN = A0; // specified analog pin used to connect the potentiometer
7. int value; // value initialized to the variable to read the value from the analog pin
8.
9. void setup()
10. {
11. myservo.attach(9); // servo connected to pin 9 of the Arduino board to the servo object
12. }
13.
14. void loop()
15. {
16. value = analogRead(potentioPIN);
17. // reads the value of the potentiometer (value between 0 and 1023)
18. value = map(value, 0, 1023, 0, 180);
19. // scale it to use it with the servo (value between 0 and 180)
20. myservo.write(value);
21. delay(1000); // it will wait for 1 second for the
22. // It will set the position of the motor according to the scaled value
23. value = map(value, 1023, 0, 180, 0);
24. // reads the value of the potentiometer (value between 1023 and 0)
25. myservo.write(value);
26. // scale it to use it with the servo (value between 180 and 0)
27. // the motor will rotate in reverse direction
28. delay(1000);
29. // delay time in milliseconds
30. //after 1500 millisecond it will again rotate from 0 to 180 degree
31. }

Steps to upload the code to the board


The steps are listed below:

o Open the Arduino IDE.


o Select the type of board from Tools -> Board -> Arduino UNO.
o Select the port from Tools -> Port -> COM..
o Upload the above sketch to the connection diagram.
AD

We can also modify the code to modify the performance of the servo motor accordingly.

AD

Connection
The steps to set up the connection are listed below:

o Connect the signal terminal of the servo motor to the 5V pin of the Arduino board.
o Connect the power terminal of the servo motor to pin 9 of the Arduino board. We can
connect the power terminal of the motor to any digital PWM pin on the Arduino board.
o Connect the ground terminal of the servo motor to the GND pin of the Arduino board.
o One outer pin of the Potentiometer is connected to the ground (GND), and other external
pin is connected to 5V of the Arduino board.
o The middle terminal of the Potentiometer is connected to the analog input pin A0 of the
board.

Connection Diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.

Output

The shaft will rotate at angles between 0 and 180 degrees and again in the reverse
direction.

We can also modify the code by specifying it only in one direction from 0 to 180 degrees.
Hence, we can make changes according to the requirements.

AD
Arduino DC motor
The DC motor is considered as the simplest motor, which has various applications ranging
from households to industries. Example includes an electric window in cars, electric
vehicles, elevators, etc.

The principle of the DC motors is based on Electromagnetic Induction. It means that the
rotation of the motor depends on the force generated by the magnetic fields. It converts
electrical energy into mechanical energy. Such motors can be powered from the direct
current.

Let's discuss how the DC motor works.

Working of DC Motor
The DC motor consists of a stator, rotor, armature, and a commutator. The commutator
comes with brushes. There are two stationary magnets in the stator that are responsible for
producing the magnetic field.

The armature present in the DC motor carries the alternating current. Electrical energy is
converted into mechanical energy in the form of torque by the armature. It further transfers
this mechanical energy via shaft.

The commutator is defined as the electrical switch. It can also reverse the direction of the
current between the external circuit and the motor. The brushes act as an intermediate
between the external power supply and the rotating coils.

The iron core at the center is wrapped with insulated wires concentrating on the magnetic
field when current passes through the wires. The windings of insulated wire have many
turns around the core of the motor.

The wire ends are connected to the commutator. The commutator further energizes the
armature coils and connects the power supply and the rotating coils through brushes.

AD

Advantages of DC motors
The advantages of using DC motors are listed below:

o Low cost
o Easy motor speed control
o High reliability
o Minimal Maintenance
o High starting torque
o Quick starting
o Variable speeds
o Harmonics free
The DC motor looks like the image shown below:

Let's start with the project.

We will discuss two projects of the DC motor.

Project 1:
Here, we will discuss the simple connection of a DC motor with the Arduino board using
diode, transistor, and resistor.

Hardware Required
The components required in the project are listed below:

o Arduino UNO R3 board


o Breadboard
o A Resistor of 2.2K Ohm
o Transistor (NPN)
o Diode
o DC Motor
o Jump wires
AD

Structure of the project


The structure of the project is shown below:
Sketch
Consider the below code:

1. int PinOFmotor = 10;


2. // PIN 10 of the Arduino is initialized to the variable
3. // the pin must be a PWM pin
4. void setup()
5. {
6. pinMode(PinOFmotor, OUTPUT);
7. }
8. void loop()
9. {
10. digitalWrite(PinOFmotor, HIGH);
11. delay(1000);
12. digitalWrite(PinOFmotor, LOW);
13. delay(1000);
14. }
AD

Steps to upload the code to the board


The steps are listed below:

AD

o Open the Arduino IDE.


o Select the type of board from Tools -> Board -> Arduino UNO.
o Select the port from Tools -> Port -> COM.
o Upload the above sketch to the connection diagram.

Connection
The steps to set up the connection are listed below:

o Connect one end of the resistor to pin 10 (PWM) of the Arduino board.
o Connect the other end of the resistor to the middle pin of the transistor.
o Connect one end terminal of the transistor to the GND pin of the Arduino and another
end terminal to the diode.
o Connect the band facing terminal of the diode to the 5V pin of the Arduino board.
o Connect one end terminal of the DC motor to band facing terminal of the diode.
o Connect another end terminal of the DC motor to the other end of the diode.

Connection Diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


After making connections, the motor will rotate.

Project 2:
Here, we will discuss the connection of a DC Gear motor with the Arduino board using the
L293D H-Bridge motor driver.

AD

Let's discuss the need to use the L293D H-Bridge motor driver with the DC motor.

L293 is defined as the motor driver IC that permits the DC motor to drive in any direction. It
can also simultaneously control two DC motors. It is a 16-pin Integrated Circuit (IC).

It receives signals from the microprocessor present on the Arduino board and transmits this
signal to the motor. It has two VCC or voltage pins, where one pin draws current for its
working and another is used to provide voltage to the DC motor.

The motor usually requires high current for its operation. We can use
the microcontroller present on the Arduino, but high current might damage the
microcontroller. To overcome this, the motor driver is used.

L293D is one of the most popular motor drivers used to drive the DC motors. It can run DC
motors up to 1 Ampere current load.
The four outputs present on the L293D driver makes it suitable for driving the 4-wire stepper
motor as well. We can also drive servo motors using the L293D driver.

L293D Pinout
The pinout of L293D is shown below:

Hardware Required
The components required in the project are listed below:

o Arduino UNO R3 board


o Breadboard
o DC Gear Motor
o Adjustable 30V supply
o Jump wires
o L293D H-Bridge motor driver

Sketch
Consider the below code:

1. #define MOTOR_1 11
2. // PWM pin 11
3. #define MOTOR_A 10
4. // PWM pin 10
5. // we can also connect it to the other PWM pins of the Arduino
6. #define MOTOR_B 8
7. // digital I/O pin
8.
9. #define slow 64
10. #define normal 128
11. #define fast 255
12.
13. int Speed; // initialization of speed variable
14.
15. // created functions
16. void Forward_Rev(void)
17. {
18. analogWrite(MOTOR_1, Speed);
19. digitalWrite(MOTOR_A, HIGH);
20. digitalWrite(MOTOR_B, LOW);
21. }
22. void Backward_Rev(void)
23. {
24. analogWrite(MOTOR_1, Speed);
25. digitalWrite(MOTOR_A, LOW);
26. digitalWrite(MOTOR_B, HIGH);
27. }
28.
29. void Forward_ramp_up(void)
30. {
31. digitalWrite(MOTOR_A, HIGH);
32. digitalWrite(MOTOR_B, LOW);
33. for (int i=0; i<255; i++) // loop started
34. //value set from 0 to 255
35. {
36. analogWrite(MOTOR_A, i);
37. delay(15); // delay time in milliseconds
38. }
39. }
40. void Forward_ramp_down(void)
41. {
42. digitalWrite(MOTOR_A, HIGH);
43. digitalWrite(MOTOR_B, LOW);
44.
45. for (int i=255; i>=0; i--) // loop set in reverse direction
46. // value set from 255 to 0 (reverse)
47. {
48. analogWrite(MOTOR_A, i);
49. delay(15);
50. }
51. }
52. // same statement but within different function
53. void Backward_ramp_up(void)
54. {
55. digitalWrite(MOTOR_A, LOW);
56. digitalWrite(MOTOR_B, HIGH);
57. for (int i=0; i<255; i++)
58. { analogWrite(MOTOR_A, i);
59. delay(15);
60. // we can modify the delay time as per the requirements
61. }
62. }
63. void Backward_ramp_down(void)
64. {
65. digitalWrite(MOTOR_A, LOW);
66. digitalWrite(MOTOR_B, HIGH);
67.
68. for (int i=255; i>=0; i--)
69. {
70. analogWrite(MOTOR_A, i);
71. delay(15);
72. }
73. }
74.
75. void Brake(void)
76. {
77. digitalWrite(MOTOR_A, HIGH);
78. digitalWrite(MOTOR_B, HIGH);
79. }
80.
81. void setup()
82. {
83.
84. Serial.begin(9600); // bps rate of 9600
85. Serial.println("DC motor test using L293D");
86.
87. pinMode(MOTOR_1, OUTPUT);
88. pinMode(MOTOR_A, OUTPUT);
89. pinMode(MOTOR_B, OUTPUT);
90. }
91.
92. void loop()
93. {
94.
95. Speed=slow; // Slow Speed
96. // we can modify the value as fast, slow, and normal depending on the required speed
97. //the motor will revolve according to the specified speed
98. // for example, fast will cause it to move at fast speed
99. // we can also add more parameters using #define
100.
101. Forward_Rev();
102. delay(1000);
103. Brake();
104. delay(500);
105. Backward_Rev();
106. delay(1000);
107. Brake();
108. delay(500);
109. Forward_ramp_up();
110. Forward_ramp_down();
111. Backward_ramp_up();
112. Backward_ramp_down();
113. // the statement inside the functions will run again and again
114. // the motor will revolve in forward and backward direction
115. }

Connection
The steps to set up the connection are listed below:

o Connect the red terminal of the power supply to the VCC of L293D.
o Connect the black terminal of the power supply to the GND of the L293D.
o Connect both terminals of the motor to Output pin 1 and 2 of the L293D driver.
o Connect input pin 2 of L293D to the digital pin 8 of the Arduino board.
o Connect the enable pin 1 and input 1 to the PWM pin 10 and 11 of the Arduino board.
o Connect VCC of the L293D driver to the 5V pin of the Arduino board.
o Connect GND of the L293D driver to the GND pin of the Arduino board.

Connection Diagram
We will show the connection using the Simulator so that the connections become clearer
and more precise.

We can make the same connection using the hardware devices.


The 'Slow' mode of speed will cause the motor to rotate at a slow speed. We can also
change the mode to fast or normal, as explained in the code.

We can also add more speed parameters to the code as per our requirements.

Arduino Nano
The Arduino Nano is a small Arduino board based on ATmega328P or ATmega628
Microcontroller. The connectivity is the same as the Arduino UNO board.

The Nano board is defined as a sustainable, small, consistent, and


flexible microcontroller board. It is small in size compared to the UNO board. The Arduino
Nano is organized using the Arduino (IDE), which can run on various platforms. Here, IDE
stands for Integrated Development Environment.

The devices required to start our projects using the Arduino Nano board are Arduino
IDE and mini USB. The Arduino IDE software must be installed on our respected laptop or
desktop. The mini USB transfers the code from the computer to the Arduino Nano board.
Drawback: The DC power jack is absent in Nano. Thus, we cannot use a battery to apply
any external power supply.

The Arduino Nano is shown below:

Why is Arduino Nano used?


Using the constant voltage, the Arduino Nano is used to produce a clock of a precise
frequency.

AD

What is the difference between Arduino UNO and Nano board?


o The Arduino Nano has a compact size and mini USB cable than the Arduino UNO. We
can use Nano instead of UNO because both operate on the microcontroller
ATmega328p.
o The Arduino UNO is also easily available than Nano. It is considered as the standard
board available in the market, which is easy for use for the starters or beginners.
o The Nano is available in PDIP (Plastic Dual - Inline Package), while Arduino UNO is
available in TQFP (Plastic Quad Flat Pack).
o The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a
power jack, and an ICSP (In-Circuit Serial Programming) header. The Arduino Nano
includes an I/O pin set of 14 digital pins and 8 analog pins. It also includes 6 Power pins
and 2 Reset pins.
Memory
The memory in Arduino Nano is shown in the below image:

The preinstalled flash has a boot loader, which takes the memory of 2Kb.

Technical Specifications
The technical specifications of the Arduino Nano board are:

o The operating voltage of the Nano board varies from 5V to 12V.


o The total pins in Nano are 22 Input/Output pins.
o There are 14 digital pins and 8 analog pins.
o There are 6 PWM (Pulse Width Modulation) pins among the 14 digital pins. The 6 PWM
pins in Arduino Nano are used to convert the digital signals into the analog signals. The
conversion takes place by varying the width of the pulse.
o The crystal oscillator present in Arduino Nano comes with a frequency of 16MHz.
o The Arduino Nano is used in various applications such as Robotics, Control System,
Instrumentation, Automations, and Embedded Systems.
o The projects created using Arduino Nano are QR Code Scanner, DIY Arduino
Pedometer, etc.
o We can also connect Arduino Nano to the Wifi.
o The functionality of Nano is similar to the Arduino UNO.
o The flexibility and eco-friendly nature of Nano make it a unique choice to create
electronic devices and projects with compact size.
AD
How to get started with Arduino Nano?
We can program the Arduino Nano using the Arduino IDE.

We can also use Arduino Web Editor, which allows us to upload sketches and write the
code from our web browser (Google Chrome recommended) to any Arduino Board. It is an
online platform.

The steps to get started with Arduino Nano are listed below:

1. Open the code or sketch written in the Arduino software.


2. Select the port and the type of board.
The ATmega328p microcontroller is used in the Arduino Nano. So, we will select the
Processor as ATmega328p.
Click on 'Tools' and select Processor, as shown below:

3. Now, upload and run the written code or sketch.

To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:
Within the few seconds after the compile and run of code or sketch, the RX and TX light
present on the Arduino board will flash.

The 'Done Uploading' message will appear after the code is successfully uploaded. The
message will be visible in the status bar.

Arduino Pro Mini


The Arduino Pro mini is a small Arduino board based on ATmega328P or Microcontroller.
The connectivity and functionality are the same as other Arduino boards. It is preferred by
advanced users for greater flexibility and small size.

The board comes in different variants. If we want to use the operating voltage of 3.3V, we
need to use the Arduino Pro Mini 3.3V board. For 5V, we are required to use the Arduino
Pro Mini 5V board.

It is primarily used in compact size projects due to its small size.

The Arduino Pro Mini is organized using the Arduino (IDE), which can run on various
platforms. Here, IDE stands for Integrated Development Environment.

The Pro Mini comes without the header. We need to solder the headers while implementing
the board in our projects.

Drawback: The Built-in programmer, shield, and USB port are absent in Arduino Pro Mini.

Arduino Pro Mini board is shown below:


What are the differences between Arduino UNO and Arduino Pro
Mini?
The differences between Arduino UNO and Pro Mini are listed below:

o Arduino Pro Mini operates at the voltage of 3.3V, while Arduino UNO operates at the
voltage of both 3.3 and 5V.
o The oscillator frequency of Arduino Pro Mini is 8MHz, while the oscillator frequency of
Arduino UNO is 16MHz.
o The size of the Arduino Pro Mini is very small compared to the Arduino UNO.
o The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a
power jack, and an ICSP (In-Circuit Serial Programming) header. The Arduino Pro Mini
includes 8 analog pins, 14 digital Input/Output pins from which 6 are PWM pins.
AD

What is the main difference between Arduino Nano and Arduino Pro
Mini?
The differences between Arduino Nano and Pro mini are listed below:

o The size of the Nano board is slightly larger than the Pro Mini board.
o The USB port is absent on the Pro Mini board, while Arduino Nano consists of a mini
USB port on the board.
AD

Memory
The Memory structure of the Pro Mini is similar to Arduino UNO. The memory structure is
shown below:
The preinstalled flash has a bootloader, which takes the memory of 0.5 Kb.

Technical Specifications of Arduino Pro Mini


The technical specifications of Arduino Pro Mini are listed below:

o The crystal oscillator present in Arduino Nano comes with a frequency of 8 MHz.
o It has only one regulator of 3.3V.
o It comes with a built-in LED. The LED will blink only when we will run the program.
o There are 8 analog pins.
o There are 14 digital I/O pins, which comprise of 6 PWM (Pulse Width Modulation) pins.
o The input voltage varies from 5V to 12V.

Pinout
The Pinout of Arduino Pro Mini is shown in the below image:
The description of pins is listed below:

o GND
There are three GND (Ground) pins present on the Pro Mini board.

o Tx0
Tx0 and RX1 pins are used for serial communication. These two pins can also be used as
the digital I/O pins. The Tx0 pin is used for transmission of the data.

o RX1
RX1 is the communication pin, which is used for receiving the data.

AD

o RST
It is used to add a Reset button to the connection.
o Vcc
It is the regulated voltage of 3.3V. We can also regulate the voltage of 5V depending on the
versions of the board.

o Vin
The Vin is the input voltage pin, which is applied while using the external power source.

o A0 - A7
A0, A1, A2, A3, A4, A5, A6, and A7 are the analog pins. The resolution of the analog pins is
10 bits. The above 8 analog pins are used as the analog inputs in the Arduino Pro Mini
board.

o 2 - 13
The PIN from 2 to 13 are the digital I/O pins.

AD

How to get started with Arduino Pro Mini?


We can program the Arduino Pro Mini using the Arduino IDE.

We can also use Arduino Web Editor, which allows us to upload sketches and write the
code from our web browser (Google Chrome recommended) to any Arduino Board. It is an
online platform.

The steps to get started with Arduino Pro Mini are listed below:

1. Open the code or sketch written in the Arduino software.


2. Select the port and the type of board.
The ATmega328p microcontroller is used in the Arduino Pro Mini. So, we will select the
Processor as ATmega328p.
Click on 'Tools' and select Processor, as shown below:
We can select the 3.3V or 5V versions of the Arduino board. We can also choose the board
type Nano w/ ATmega328P or Nano w/ ATmega168. The Arduino Pro Mini board is powered
and connected to the USB called FTDI TTL-232R-3V3. It is the TTL serial level converter
cable.
3. Now, upload and run the written code or sketch.

To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:

Within the few seconds after the compilation and run of code or sketch, the RX and TX light
present on the Arduino board will flash.

The 'Done Uploading' message will appear after the code is successfully uploaded. The
message will be visible in the status bar.
Arduino Mega
The Arduino Mega is based on ATmega2560 Microcontroller. The ATmega2560 is an 8-bit
microcontroller. We need a simple USB cable to connect to the computer and the AC to DC
adapter or battery to get started with it.

The Arduino Mega is organized using the Arduino (IDE), which can run on various
platforms. Here, IDE stands for Integrated Development Environment.

The functioning of the Arduino Mega is similar to other Arduino Boards. We need not
require extra components for its working.

The ATmega2560 Microcontroller is consistent with most of the shields of Arduino UNO.

The Arduino Mega board is shown below:

Why we use Arduino Mega?


The advantage of using the Arduino Mega board over other boards is that it gives the
advantage of working with more memory space.

It has higher processing power, which can help us to work with the number of sensors at a
time.

AD

What is the difference between Arduino UNO and Arduino Mega?


o The Arduino UNO is based on the ATmega328 Microcontroller, while Arduino Mega is
based on ATmega2560 Microcontroller.
o Arduino Mega (8Kb SRAM) acquires more SRAM space than Arduino UNO (2Kb
SRAM). The greater the SRAM space, the more space would the Arduino have to
manipulate and create a variable when it runs.
o The Arduino UNO includes 6 analog pin inputs, 14 digital pins, a USB connector, a
power jack, and an ICSP (In-Circuit Serial Programming) header. The Arduino Mega
includes 54 I/O digital pins and 16 Analog Input/Output (I/O), ICSP header, a reset
button, 4 UART (Universal Asynchronous Reciever/Transmitter) ports, USB connection,
and a power jack.

Memory
The memory structure is shown in the below image:

The preinstalled flash has a bootloader, which takes the memory of 8Kb.

Here, SRAM stands for Static Random Access Memory, and EEPROM stands
for Electrically Erasable Programmable Read-Only Memory.

Technical Specifications of Arduino Mega


The technical specifications of Arduino Mega are listed below:

o There are 54 Input/Output digital pins and 16 Analog Input/Output (I/O) present on the
Mega board.
o The 15 pins from the 54 digital I/O pins are PWM output pins. The PWM pins are Pulse
Width Modulation capable pins.
o The input voltage of the Mega board varies from 7V to 12V.
o The crystal oscillator present in Arduino Mega comes with a frequency of 16MHz.
o The functionality of Mega is similar to the Arduino UNO.
o The operating voltage of the Arduino Mega is 5 V.
o The Mega board is considered superior in terms of SRAM memory space.
o It is well-suited for most of the Arduino shields.
o The bootloader is used to eliminate the exterior burner utilization.
o It is generally used to create complex projects due to its structure.
o The projects that use Arduino Mega board are IOT Applications, 3D Printers,
temperature sensing, monitoring of real-time applications, etc.
AD

How to get started with Arduino Mega?


We can program the Arduino Mega using the Arduino IDE. We need to install the Arduino
IDE software to get started with the process.

We can also use Arduino Web Editor, which allows us to upload sketches and write the
code from our web browser (Google Chrome recommended) to any Arduino Board. It is an
online platform.

The USB cable is crucial for the connection between the board and the computer. The
green LED will light, which indicates the successful connection between the computer and
the board.

The steps to get started with Arduino Mega are listed below:

o Open the code or sketch written in the Arduino software.


o Select the type of board.
The ATmega2560 microcontroller is used in the Arduino Mega. So, we will select the
Processor as ATmega2560.
As we select the board, the processor is automatically selected by default.
Click on 'Tools' and select Processor, as shown below:

o Select the port. Click on the Tools -> Port (select the port). The port likely will
be COM3 or higher. For example, COM6, etc. The COM1 and COM2 ports will not
appear, because these two ports are reserved for the hardware serial ports.
o Now, upload and run the written code or sketch.
To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:

Within the few seconds after the compile and run of code or sketch, the RX and TX light
present on the Arduino board will flash.

AD

The 'Done Uploading' message will appear after the code is successfully uploaded. The
message will be visible in the status bar.
Arduino Micro
The Arduino Micro (a type of Arduino board) is based on the ATmega32U4 Microcontroller.
It comes with the inbuilt USB. The Micro can also perform as a mouse or keyboard when
connected to the computer. It uses Micro USB cable.

We need to use the micro USB cable to establish the connection between the Micro board
and the computer to get started with the programming. The USB port is inbuilt in the
ATmega32U4 Microcontroller, which eliminates the use of a secondary processor.

The Arduino Micro board is shown below:

What is the difference between Arduino Micro and Arduino UNO?


o The Arduino Micro consists of 20 sets of pins. The 7 pins from the set are PWM (Pulse
Width Modulation) pins, while 12 pins are analog input pins. The other components on
board are reset button, 16MHz crystal oscillator, ICSP header, and a micro USB
connection. Whereas, the Arduino UNO consists of 6 analog pin inputs, 14 digital
pins, a USB connector, a power jack, and an ICSP (In-Circuit Serial Programming)
header.
o Arduino Micro consumes less power than Arduino UNO.
o Arduino Micro has a small size compared to UNO.
o Arduino UNO is based on an ATmeg328p Whereas, Arduino Micro is based on
the ATmega32U4 Microcontroller.
AD

What is the main difference between Arduino Micro and Arduino Pro
Mini?
o The oscillator frequency of Arduino Pro Mini is 8MHz, while the oscillator frequency of
Arduino Micro is 16 MHz.
o The size of the Arduino Pro Mini is small as compared to the Arduino Micro.
o Arduino Micro is based on the ATmega32U4 Microcontroller, while Arduino Pro Mini is
based on ATmega328P
AD

What is the difference between Arduino Micro and Arduino Nano?


o Arduino Micro is based on the ATmega32U4 Microcontroller, while Arduino Nano is
based on ATmega328 Microcontroller.
o Arduino Nano has 2KB of SRAM, while Micro has 2.5KB of SRAM. Here, SRAM stands
for Static Random-Access Memory.

Technical Specifications of Arduino Micro


The technical specifications of Arduino Micro are listed below:

o It consists of 12 analog pins.


o The 7 pins from the set of digital pins are the PWM (Pulse Width Modulation) pins.
These pins are used to convert the digital signal into the analog signal. It is commonly
used when the built-in DAC (Digital to Analog Converter) is absent on the Arduino board.
o The program or firmware with the advanced functionalities is received by a
microcontroller with the help of the ICSP (In-Circuit Serial Programming) header.
o The recommended input voltage is between 7V to 12V.
o The operating voltage of the Arduino Micro is 5V.
o The microcontroller used is ATmega32U4. It is a low power microcontroller.

Getting started with Arduino Micro


We can program the Arduino Micro using the Arduino IDE.

We can also use Arduino Web Editor, which allows us to upload sketches and write the
code from our web browser (Google Chrome recommended) to any Arduino Board. It is an
online platform.

The steps to get started with Arduino Micro are listed below:

o Install the drivers of the Arduino Micro board.


The driver will be installed automatically when we plug-in the board into our computer using
the USB. But in some Windows (Vista, 10, and 7), we need to manually install the driver
using the option Start-> Control Panel-> Hardware-> Select the appropriate board -
> Right-click -> select Update Driver.

o Open the code or sketch written in the Arduino software.


o Select the port and the type of board.
.
Here, we will select the Arduino Micro. The port will be visible, when the board is
successfully connected to our computer.
For example, let's open an example of Button using the options File -> Examples -
> Digital -> Button. It is shown below:

The example of the Button sketch will be opened.

The selected board is shown below:


o Now, upload and run the written code or sketch.
To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:

Within the few seconds after the compile and run of code or sketch, the RX and TX light
present on the Arduino board will flash.

The 'Done Uploading' message will appear after the code is successfully uploaded. The
message will be visible in the status bar.
Arduino Due
The Arduino Due is based on the 32- bit ARM core. It is the first Arduino board that is
developed based on the ARM Microcontroller. It has two ports, which are named as Native
USB port and Programming port.

It consists of 54 Digital Input/Output pins and 12 Analog pins. The Microcontroller present
on the board is the Atmel SAM3X8E ARM Cortex-M3 CPU. The Arduino Due is also
organized using the Arduino (IDE), which can run on various platforms. Here, IDE stands for
Integrated Development Environment.

The Arduino Due board is shown below:

Serial Ports: The Native USB port and the programming USB port are the two ports on the
Arduino Due board.

Native USB port: The Native port is directly connected to the SAM3X MCU. It uses the
serial USB object to support the CDC (Communication Device Class) serial communication.

Programming USB port: The programming port is connected to the high-performance 8-bit
Microcontroller (ATMEL 16U2), which also acts as a USB to serial converter.

Reset Button: It is used to add a Reset button to the connection. To reset the
Microcontroller, we need to press and hold the Reset button.

Power Jack: The adapter can be plugged-in into the power jack to connect it to
the Arduino Due board.

Analog pins: The pins numbered as Ao, A1, A2, A3, A4, A5, A6, A7, A8, A9,
A10, and A11 are the analog pins. The function of Analog pins is to read the analog sensor
used in the connection. These pins can also act as GPIO (General Purpose Input Output)
pins.

Digital I/O pins: There are 54 digital Input/Output pins. The digital pins have the value
HIGH or LOW.

What is the difference between Arduino Due and Arduino UNO?


The difference between Arduino Due and Arduino UNO are listed below:

o Arduino Due consists of 54 Digital Input/Output pins and 12 Analog pins, while Arduino
UNO consists of 6 analog pin inputs and 14 digital pins.
o Arduino Due is based on the ARM Microcontroller, while Arduino UNO is based on the
ATmega328 Microcontroller.
o Arduino Due uses system voltage of 3.3V, while Arduino UNO uses a system voltage of
5V.
AD

What is the difference between Arduino Due and Arduino Mega?


The difference between Arduino Due and Arduino Mega are listed below:

o Arduino Due has more memory and better processing power than Arduino Mega.
o Arduino Due is based on the ARM Microcontroller, while Arduino Mega is based on the
ATmega2560 Microcontroller.
o The library and shields are more compatible with ATmega2560 Microcontroller
compared to Arduino Due.
o Arduino Due consists of 54 Digital Input/Output pins and 12 Analog pins, while Arduino
Mega consists of 14 analog pin inputs and 54 digital pins.
AD

Technical Specifications of Arduino Due


The technical specifications of Arduino Due are listed below:

o The ARM Microcontroller is 32-bit.


o The 12 pins from the set of digital pins are the PWM pins.
o The operating voltage of Arduino Due is 3.3V.
o It consists of two serial ports.
o There are 4 UART (Universal Asynchronous Receiver Transmitter) serial modules.
o The 12 pins from the set of pins are the analog pins labeled from A0 to A11.
o The input voltage of Arduino Due varies from 7V to 12V.
o It consists of the 512KB Flash Memory and 96KB SRAM.
o The SRAM consists of two banks of memory, which are 32KB and 64KB.
o The CPU Frequency of the clock is 84MHz.

To Get Started with Arduino Due


We can program the Arduino Due using the Arduino IDE. The Arduino IDE is the Integral
Development program, which is common to all the boards.

We can also use Arduino Web Editor, which allows us to upload sketches and write the
code from our web browser (Google Chrome recommended) to any Arduino Board. It is an
online platform.

The steps to get started with Arduino Due are listed below:

o Install the drivers of the board.


We do not need to install the drivers on the OSX. But we may get a dialog box to open the
"Network Preferences" on our computer. Click on Network Preferences -> Click on Apply -
> Quit the System Preferences.

AD

Due will work but it displays "Not Configured."

But, for Windows XP and Windows 7, follow the below steps:

1. Download the Arduino software -> Unzip the file -> connect the board to our computer
using USB via Programming port only -> Driver Installation will be initiated.
2. Click on Start -> Control Panel -> System and Security.
3. Click on System -> Device Manager -> Ports (COM &LPT) -> Open port "Arduino Due
Prog. Port."
4. Right-click "Arduino Due Prog. Port" -> Update Driver Software -> Browse my computer
for driver software.
5. Navigate to the Arduino downloaded folder.
6. In the main Arduino folder, select and locate the 'Drivers.'
7. To proceed, click on OK -> Next.
8. Click on the button 'Continue Anyway.'
9. Installation finished. We can now see our port in the Device Manager.

Linux : For Linux, we are not required any driver installation.

o Select the type of board and port.


We should use the Programming port that is adjacent to the power jack for uploading the
sketches.

We are required to follow some steps to upload our sketch through the Programming port,
which are listed below:

AD

1. Plug-in the USB cable to the Programming Port.


2. Click on Tools -> choose the Serial Port.
3. Click on 'Tools' -> Click on Board -> Select Arduino Due (Programming port), as shown
below:
o Open any sketch from the File -> Examples. We can also create our own sketch.
o Now, upload and run the written code or sketch.
To upload and run, click on the button present on the top panel of the Arduino display, as
shown below:

Within the few seconds after the compile and run of code or sketch, the RX and TX light
present on the Arduino board will flash.

The 'Done Uploading' message will appear once the code is successfully uploaded. The
message will be displayed in the status bar.

Arduino vs. Raspberry Pi


Arduino and Raspberry Pi are used as a tool for creating electronic projects.

The Arduino is considered a part of the Raspberry Pi.


The difference between Arduino and Raspberry Pi are listed in the below table:

Arduino
o The Arduino is defined as a simple microcontroller motherboard.
o The Arduino helps us to make the projects simpler.
o It was developed to create microcontroller kits, which was used to build electronic
devices.
o Most Arduinos come with an 8-bit Microcontroller.
o It has 32K bytes and 2K bytes of flash memory and SRAM. The flash memory consists
of a stored sketch of Arduino, while SRAM manipulates the processing variables.
o It promotes C++ as the primary programming language.
o It has no Operating system. The software platform requires Windows, Linux, and macOS
operating system to run the program.
o The types of Arduino are Started kits (for beginners), Arduino shields (printed circuit
expansion boards), Standard Arduino boards, and boards with advanced features.
o The Arduino runs a single piece of code over and over again. Due to this, it starts quickly
as soon as we ON the power.
o It is based on IDE (Integrated Development Environment), which is limited to the
programming interface.
o The connection to the Internet is quite complicated.
o The Arduino project was started in Italy.
o The design of the Arduino board consists of different controllers and microprocessors.
Some board also includes USB (Universal Serial Bus), models, and serial
communication interfaces.
o The processor speed in Arduino ranges from 8MHz to 400MHz. The average speed of
most of the types of Arduino is 16MHz.
o The projects of Arduino are connected to a computer using the USB port.
o The Analog to Digital converter is inbuilt in the Arduino.
o The Arduino UNO has 14 digital Input/Output pins, 6 analog pins, and power pins.
AD

Raspberry Pi
o The Raspberry Pi is defined as the mini computer.
o It is considered superior at software applications.
o It was developed to encourage basic learning for computer science students and other
growing countries.
o It consists of a 64-bit quad-core processor or microprocessor.
o The Raspberry Pi has about 1GiB of RAM. Here, 1 GiB = 1024 x 1024 x 1024 bytes =
(1024)^3 bytes.
o It promotes Scratch and Python as the chief programming language.
o The foundation of Raspberry Pi provides an operating system such as Linux. It also
provides a non-Linux operating system, such as OpenBSD, NetBSD, HelenOS, etc.
o The types of Raspberry Pi are Raspberry Pi Alternatives, Raspberry Pi Zero W, and
Raspberry Pi 3 Model B+.
o We can run all types of applications in Raspberry Pi, including Microsoft Office, emails,
or specific code for an electronics project.
o We can run a single or different piece of code in Raspberry Pi.
o The Operating system in all the files is saved in the SD card. For one Raspberry Pi, we
can have multiple SD cards for the different operating system or file system.
o It is consistent in many programming languages.
o It can be easily connected to the Internet.
o The Raspberry Pi Foundation developed the Raspberry Pi in the United Kingdom.
o The design of Raspberry Pi board consists of CPU (Central Processing Unit), GPU
(Graphics Processing Unit), the graphics chip, RAM, Xbee port, Ethernet port, power
source connector, UART (Universal Asynchronous Reciever/Transmitter), and GPIO
(General-Purpose Input/Output) pins.
o The processor speed in Raspberry Pi ranges from 700MHz to 1.5GHz.
o The hard drive for the Raspberry Pi is the slot on the board, in which the SD card is
inserted.
o The Analog to Digital converter is attached externally to the Raspberry Pi.
o The Raspberry Pi3 has 40 Input/Output pins on board.
AD

Arduino Potentiometer
The potentiometer is a device that is used to measure the voltage or electric potential. It
provides a variable resistance when the shaft of the device is turned.

Here, we will measure the amount of resistance as an analog value produced by the
potentiometer. We will connect the potentiometer to the Arduino UNO board and will
measure the state of the potentiometer. The required code will be uploaded from our
computer to the Arduino board.

The variable resistance measured by the potentiometer can be easily read as an analog
value into the Arduino board.

What is Potentiometer?
The potentiometer is a three-terminal device. It has a rotating contact that acts as an
adjustable voltage divider.

The potentiometer structure consists of a sliding contact (called wiper), a resistive element,
electrical terminals, and a housing.

The sliding contact moves along the resistive element, while the housing consists of the
wiper and the element.

Working: The fixed input voltage is applied across the two ends terminal of a
potentiometer, which further produces the adjustable output voltage at the wiper or slider.

As the slider moves from one end to another, the divider can vary the output voltage from
maximum to Ground.
The connection of potentiometer with Arduino board is shown below:

The middle terminal of potentiometer is connected to the analog pin to read the analog data.

Potentiometer with LED


In this example, we will use a potentiometer that controls the value at which LED blinks.

Hardware Required

The required components are listed below:

o 1 x red LED
o Arduino UNO R3 board
o 10K Ohm Potentiometer
o Jump wires
o 220 Ohm resistor
Connection

o One outer pin of the potentiometer is connected to ground (GND), and other external pin
is connected to 5V of the Arduino board.
o The middle pin of the potentiometer is connected to the analog input pin A2 of the board.
o The positive terminal of the LED is connected in series with 220 Ohm resistor to pin
number 13 of the board, and the negative terminal is connected to the GND.
AD

Procedure
The analog input will turn the LED ON and OFF, which is connected to the pin number 13 of
the Arduino UNO board. The time (delay time) at which LED is ON/OFF depends on the
value acquired by the analogread( ).

We have connected the potentiometer to the analog pin number 2 of the Arduino UNO
board.

AD

When the shaft is turned, the amount of resistance on either side of the potentiometer
changes. The distance between the pin connected to 5V and GND gives the analog input.
We read input 0 when the shaft is turned in one direction, while we read input 1023 when
the shaft is turned in another direction.

In between the turning input between 0 and 1023, we get the desired value returned by the
analogRead( ). It is proportional to the voltage being applied to the pin.

Code

We will now upload the code to the board.

The code is given below:

AD

1. int potentiometerPIN = 2;
2. // It select the input pin connected to the middle terminal of the potentiometer
3. int LEDpin = 13; // It selects the LED pin
4. int value = 0; // value initialized to store the coming value from the sensor
5. void setup()
6. {
7. pinMode(LEDpin, OUTPUT); // The LED pin is declared as the output pin
8. }
9. void loop()
10. {
11. value = analogRead(potentiometerPIN); // It reads the value from the sensor
12. digitalWrite(LEDpin, HIGH); // turn the LEDpin ON
13. delay(value); // delay time in milliseconds
14. digitalWrite(LEDpin, LOW); // turn the LEDpin OFF
15. delay(value);
16. // the delay time depends on the value stored from the sensor
17. }
Connection diagram

The connection diagram is shown below:


Arduino Nano Pinout
The Arduino Nano is a small Arduino board based on ATmega328P or ATmega628
Microcontroller. The Nano board is defined as a small and flexible microcontroller board.

The board includes the mini USB jack to connect computer and the Nano board. The DC
power jack is absent in Arduino Nano board.

The Pinout of the Arduino Nano board is shown below:


The description of pins present on the Arduino Nano board is listed below:

o Atmega328P Microcontroller
The Atmega328P is a high performance and low powered 8-bit microcontroller, which is
based on AVR RISC Architecture. Here, AVR stands for Audio Video Recorder and RISC
stands for Reduced Instruction Set Computing. It is also considered as the most popular
AVR controller.

It consumes less power than Atmega328 Microcontroller.

o RXD and TXD


AD

TXD and RXD pins are used for serial communication. The TXD is used for transmitting the
data, and RXD is used for receiving the data. It also represents the successful flow of data
from computer to the board.

o Mini USB
The Mini USB is smaller than the standard USB but thick than the micro USB. It allows the
board to connect to the computer. It is essential for the programming of the Arduino Nano
board.

We usually plug the USB cable in the Mini-USB jack to load the sketch to the board.

o SMD Crystal
The Surface Mount crystals have better stability than other crystals. The device can be
easily soldered on any board. The SMD crystal used in the Arduino Nano is of 16MHz.

o RST
It is used to add a Reset button to the connection.

o Power Indicator
It indicates the status of the battery. It can also show the voltage of the battery on the LCD
display connected to the Arduino board.

o Digital Pins
There are 14 digital I/O pins. The six pins from the set of digital pins are PWM (Pulse Width
Modulation) pins numbered D3, D5, D6, D9, D10, and D11. The digital pins have the value
either HIGH or LOW.

o Analog Pins
There are eight analog pins numbered from A0 to A7. The function of Analog pins is to read
the value of analog sensor used in the connection. It can also act as GPIO (General
Purpose Input Output) pins.

o Analog Reference or (AREF)


The AREF pin acts as a reference voltage to feed the Arduino from an external power
supply voltage.

o Vin
It is defined as the input voltage, which is applied to the Arduino Board when it is using an
external power source.

o 3V3
The 3V3 pin works as the output regulated voltage of 3.3V.

AD

o 5V
The 5V pin works as the output regulated voltage of 5V. The power source of 5V for the
Arduino Nano board are USB connector, DC power jack, and the Vin. The power can be
supplied to the board from either of the above specified sources.

Arduino Mega Pinout


The Arduino Mega is based on ATmega2560 Microcontroller. The advantage of using the
Arduino Mega board over other boards is that it gives the advantage of working with more
memory space.
The Pinout of Arduino Mega is shown below:

The description of pins present on the Arduino board are listed below:

o ATmega2560 Microcontroller - The Atmega2560 is a CMOS (Complementary Metal


Oxide Semiconductor) low powered 8-bit microcontroller. The Mega 2560 is based on
AVR RISC Architecture. Here, AVR stands for Audio Video Recorder and RISC stands
for Reduced Instruction Set Computing.
It is used for the boards that require more memory, sketch, and I/O lines. It is recommended
for complex projects, such as Robotics, etc.

o GND - Ground Pins. The ground pins are used to ground the circuit.
o USB Port
AD
It allows the board to connect to the computer. It is essential for the programming of
the Arduino Mega board.

We usually plug the USB cable in the USB port to load the sketch to the board.

o UART-
It stands for Universal Asynchronous Receiver and Transmitter. It permits the Arduino to
communicate with serial devices.

o Power Jack
The power jack is used to supply the power to the board. The adapter is plugged-in to the
power jack of the Arduino Mega board.

o ICSP Header
The program or firmware with the advanced functionalities is received by microcontroller
with the help of the ICSP (In-Circuit Serial Programming) header.

The ICSP header consists of 6 pins.

The structure of the ICSP header is shown below:

It is the top view of the ICSP header.

o I2C
It is the two-wire serial communication protocol. It stands for Inter-Integrated Circuits. The
I2C is a serial communication protocol that uses SCL (Serial Clock) and SDA (Serial Data)
to receive and send data between two devices. The SCL is a clock line, while SDA is a data
line.

o Analog pins
There are total of 16 Analog pins from A0 - A15. The function of Analog pins is to read the
analog sensor used in the connection. It can also act as GPIO (General Purpose Input
Output) pins.

o Digital Pins
There are 54 digital Input/Output pins from pin numbered from 0 to 53. The 15 pins from the
digital I/O are PWM (Pulse Width Modulation) pins numbered from D2 - D13 and D44 - D46.
The digital pins have the value either HIGH or LOW.

o SPI-SCK
It stands for Serial Peripheral Interface. It is popularly used by the microcontrollers to
communicate with one or more peripheral devices quickly. The SCK stands for serial clock.
In slave, it works as the input of the clock generator. In master, it works as the output clock.

SPI can even have various devices on the bus.

AD

o MISO
It stands for Master In/ Slave Output. The slave line in MISO is used to send data to the
master.

o MOSI
It stands for Master Output/ Slave Input. The MOSI line Arduino carries the data from
Arduino to the control devices of SPI. The slave line in MOSI is used to send data to its
peripherals.

SS

It stands for Slave Select. It is the Slave Select line, which is used by the master. It acts as
the enable line.

The MISO, MOSI, and SS support SPI communication.

AD

The multiple SPI devices in Arduino are able to share the same SS, MOSI, and MISO lines.

o IOREF
It stands for Input Output voltage REFerence. It allows the shields to check the operating
voltage (3.3V or 5V) of the board. The shields are connected to the Arduino Board.

The Microcontroller operates with the reference voltage provided by the IOREF.

o 5V: The 5V pin works as the output regulated voltage of 5V.


o 3V3: The 3V3 pin works as the output regulated voltage of 3.3V.
o RX and TX: The successful flow of data is represented by the lighting of the TX and RX
LED.
o Vin: It is defined as the input voltage, which is applied to the Arduino Board when it is
using an external power source.

Arduino Micro Pinout


The Arduino Micro is based on the ATmega32U4 Microcontroller with the inbuilt USB. The
Micro can also appear as a mouse or keyboard when connected to the computer. It uses
Micro USB B cable.

The pinout of Arduino Micro is shown below:

Let's discuss each pin in detail.

o Atmega32U4 Microcontroller
It is the low power 8-bit Microcontroller with the 2.5KB SRAM, 32KB Flash memory, and
1KB EEPROM. The operating voltage lies between 2.7 and 5.5V. It is a 12 channel 10-bit
Analog to Digital converter. The 16Mhz clock oscillator is used by the microcontroller to
achieve the 16 MIPS (Millions Instructions Per Second) throughput.

o SS
AD

It stands for Slave Select. It is the Slave Select line, which is used by the master. It acts as
the enable line.

o GND - Ground pins


The ground pins are used to ground our circuit.

o SDA
The pin numbered as 2 is the SDA pin. It is the data line. We need to use a pull-up resistor
while connecting the SDA pin.

o AREF
The Analog Reference (AREF) pin is used to feed a reference voltage to the Arduino Micro
board from the external power supply.

o SCL
The pin numbered as 3 is the SCL pin. It is the clock line. We need to use a pull-up resistor
while connecting the SCL pin.

o MISO
It stands for Master In/ Slave Output. The slave line in MISO is used to send data to the
master.

o MOSI
It stands for Master Output/ Slave Input. The slave line in MOSI is used to send data to its
peripherals.

o SCK
The SCK stands for serial clock. In slave, it works as the input of the clock generator. In
master, it works as the output clock. The data generated by the master is synchronized by
the SCK.

o PWM pins
The PWM (Pulse Width Modulation) pins are used to convert the digital signal into the
analog signal. It is commonly used when the built-in DAC (Digital to Analog Converter) is
absent on the Arduino board.

The pins numbered as 3, 6, 9, 10, 11, and 13 are the PWM pins.
o USB Port
It allows the board to connect to the computer. It is essential for the programming of the
Arduino Micro board.

o ICSP Header
The program or firmware with the advanced functionalities is received by microcontroller
with the help of the ICSP (In-Circuit Serial Programming) header.

The ICSP header consists of 6 pins.

AD

The structure of the ICSP header is shown below:

It is the top view of the ICSP header.

o Analog Pins
The function of Analog pins is to read the analog sensor used in the connection. It can also
act as GPIO (General Purpose Input Output) pins.

There are 12 analog pins labeled as Ao, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11.

o Digital Pins
The pins numbered as 4, 6, 8, 9, 10, and 12 are the digital Input/Output pins. The digital
pins have the value HIGH or LOW.

AD

o RESET
It is used to add a Reset button to the connection. To reset the Microcontroller, we need to
press and hold the Reset button.
o TX and RX
The successful flow of data is represented by the lighting of the TX and RX LED. The Serial
1 (TX) and Serial 0 (RX) is used to transmit and receive the TTL serial data using the serial
capability of the Arduino ATmega32U4 hardware.

o Vin
The Input Voltage (Vin) is applied as the input voltage to the Arduino board from an external
power source. We can also access the power jack voltage through this pin.

o Vcc
The Vcc is the voltage supplied to the ATmega32U4 on board. It also depends on the
version of the board used.

Arduino Due Pinout


The Arduino Due is based on the 32- bit ARM core. It is the first Arduino board that is
developed based on the ARM Microcontroller. It has two ports, which are named as Native
USB port and Programming port.

The pinout of Arduino Due is shown below:


Let's discuss this in detail:

RX and TX

The successful flow of data is represented by the lighting of the TX and RX LED. Power
Pins

The power pins consist of GND (Ground), 5V, 3V3, Vin, and IOREF pins.

GND: These are the ground pins, which are used to ground our circuit.

5V: The 5V pin works as the output regulated voltage of 5V. The power source of 5V for
the Arduino Due board are USB connector, DC power jack, and the Vin. The power can be
supplied to the board from either of the above-specified sources.

3V3: The 3V3 pin works as the output regulated voltage of 3.3V. It can provide power to the
SAM3X Microcontroller.

Vin: It is defined as the input voltage, which is applied to the Arduino Board when it is using
an external power source.
IOREF: It stands for Input-Output voltage REFerence. It allows the shields to check the
operating voltage (3.3V or 5V) of the board. The shields are connected to
the Arduino Board.

The Microcontroller operates with the reference voltage provided by the IOREF.

Analog Pins

The pins numbered as Ao, A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, and A11 are the
analog pins. The function of Analog pins is to read the analog sensor used in the
connection. It can also act as GPIO (General Purpose Input Output) pins.

Digital pins

There are 54 digital Input/Output pins. The digital pins have the value HIGH or LOW. The
pins labeled from 0 to 53 are the digital pins.

SPI Communication

AD

SPI stands for Serial Peripheral Interface, which is considered as a system for serial
communication. It uses conductors for data receiving, data sending, synchronization, and
device selection (for communication).

It can communicate quickly over short distances. It is also used to communicate between
the two Microcontrollers.

I2C Communication

The I2C (Inter-Integrated Circuits) is a serial communication protocol that uses SCL (Serial
Clock) and SDA (Serial Data) to receive and send data between two devices.

Voltage for ADC

AD

The ADC (Analog to Digital Converter) is used to map the voltage value to the integer value.
The voltage from 0 to 5 is mapped into the integer value from 0 to 1023. ADC in Arduino
Due is a 6-channel converter of 10-bit.

Erase Button

The on-board Erase button allows to erase the Flash Memory of the SAM3X. To erase, we
need to on the power of the board and press and hold the Erase button for a few seconds.

It will remove or erase the current sketch loaded in the MCU.

Reset Button
It is used to add a Reset button to the connection. To reset the Microcontroller, we need to
press and hold the Reset button.

USB Port

It allows the board to connect to the computer. It is essential for the programming of the
Arduino Due board.

We usually plug the USB cable in the Programming port to load the sketch to the board.

Programming USB port

The programming port is connected to the high-performance 8-bit Microcontroller (ATMEL


16U2), which also acts as a USB to serial converter.

Native USB port

The Native port is directly connected to the SAM3X MCU. It uses the serial USB object to
support the CDC (Communication Device Class) serial communication.

Power Jack

The adapter can be plugged-in into the power jack to connect it to the Arduino Due board.

32-bit ARM Controller

The use of a 32-bit ARM Controller makes the board useful for large scale projects. The AC
to DC adapter is mounted on it, which acts as a power source for the board. It is only
consistent with the shields that are working at the voltage of 3.3V. It is based on the Atmel
SAM3X8E ARM Cortex-M3 CPU.

PWM Output

The PWM (Pulse Width Modulation) pins are used to convert the digital signal into the
analog signal. The pin labeled from 2 to 13 can be used as the PWM output pins.

Serial Communication

The serial port is also known as the UART port. It uses the USB port to communicate with
the computer. It is also used to communicate on the transmitting LED called TX and RX.

You might also like