Unit 3 - Iot and Arduino Programming
Unit 3 - Iot and Arduino Programming
Introduction to the Concept of IoT Devices – IoT Devices Versus Computers – IoT
Configurations – Basic Components – Introduction to Arduino – Types of Arduino – Arduino
Toolchain – Arduino Programming Structure – Sketches – Pins – Input/Output From Pins
Using Sketches – Introduction to Arduino Shields – Integration of Sensors and Actuators
with Arduino.
Over 9 billion ―Things‖ (physical objects) are currently connected to the Internet, as of now.
In the near future, this number is expected to rise to a whopping 20 billion.
Main components used in IoT:
2. Make the Internet ever more expansive, but this requires hard-core technologies such as
rigorous cloud computing and rapid big data storage (expensive).
In the near future, IoT will become broader and more complex in terms of scope. It will
change the world in terms of ―anytime, anyplace, anything in connectivity.‖
IoT Enablers:
RFIDs: uses radio waves in order to electronically track the tags attached to each
physical object.
Sensors: devices that are able to detect changes in an environment (ex: motion
detectors).
Nanotechnology: as the name suggests, these are extremely small devices with
dimensions usually less than a hundred nanometers.
Smart networks: (ex: mesh topology).
Collect and Transmit Data : For this purpose sensors are widely used they are used as
per requirements in different application areas.
Actuate device based on triggers produced by sensors or processing devices : If certain
condition is satisfied or according to user‟s requirements if certain trigger is activated
then which action to performed that is shown by Actuator devices.
Receive Information : From network devices user or device can take certain information
also for their analysis and processing purposes.
Communication Assistance : Communication assistance is the phenomena of
communication between 2 network or communication between 2 or more IoT devices of
same or different Networks. This can be achieved by different communication protocols
like : MQTT , Constrained Application Protocol, ZigBee, FTP, HTTP etc.
Working of IoT
Characteristics of IoT:
Massively scalable and efficient
IP-based addressing will no longer be suitable in the upcoming future.
An abundance of physical objects is present that do not use IP, so IoT is made possible.
Devices typically consume less power. When not in use, they should be automatically
programmed to sleep.
A device that is connected to another device right now may not be connected in another
instant of time.
Intermittent connectivity – IoT devices aren‟t always connected. In order to save
bandwidth and battery consumption, devices will be powered off periodically when not
in use. Otherwise, connections might turn unreliable and thus prove to be inefficient.
Interconnectivity
It is the basic first requirement in any IoT infrastructure. Connectivity should be guaranteed
from any devices on any network then only devices in a network can communicate with
each other.
Heterogeneity
There can be diversity in IoT enabled devices like different hardware and software
configuration or different network topologies or connections but they should connect and
interact with each other despite of so much heterogeneity.
Dynamic in nature
IoT devices should dynamically adapt themselves to the changing surroundings like
different situation and different prefaces.
Self adapting and self configuring technology
For example surveillance camera. It should be flexible to work in different weather
conditions and different light situations (morning, afternoon, or night).
Intelligence
Just data collection is not enough in IoT, extraction of knowledge from the generated data
is very important. For example, sensors generate data, but that data will only be useful if it
is interpreted properly. So intelligence is one of the key characteristics in IoT. Because data
interpretation is the major part in any IoT application because without data processing we
can‟t make any insights from data . Hence big data is also one of the most enabling
technology in IoT field.
Scalability
The number of elements (devices) connected to IoT zone is increasing day by day.
Therefore, an IoT setup should be capable of handling the expansion. It can be either
expand capability in terms of processing power, Storage, etc. as vertical scaling or
horizontal scaling by multiplying with easy cloning
Identity
Each IoT device has a unique identity (e.g., an IP address). This identity is helpful in
communication, tracking and to know status of the things. If there is no identification then
it will directly effect security and safety of any system because without discrimination we
can‟t identify with whom one network is connected or with whom we have to
communicate. So there should be clear and appropriate discrimination technology available
between IoT networks and devices.
Safety
Sensitive personal details of a user might be compromised when the devices are connected
to the Internet. So data security is a major challenge. This could cause a loss to the user.
Equipment in the huge IoT network may also be at risk. Therefore, equipment safety is also
critical.
Architecture
It should be hybrid, supporting different manufacturer‟s products to function in the IoT
network.
As a quick note, IoT incorporates trillions of sensors, billions of smart systems, and
millions of applications.
Application Domains: IoT is currently found in four different popular domains:
1) Manufacturing/Industrial business - 40.2%
2) Healthcare - 30.3%
3) Security - 7.7%
4) Retail - 8.3%
Modern Applications:
1. Smart Grids and energy saving
2. Smart cities
3. Smart homes/Home automation
4. Healthcare
5. Earthquake detection
6. Radiation detection/hazardous gas detection
7. Smartphone detection
8. Water flow monitoring
9. Traffic monitoring
10. Wearables
11. Smart door lock protection system
12. Robots and Drones
13. Healthcare and Hospitals, Telemedicine applications
14. Security
15. Biochip Transponders(For animals in farms)
16. Heart monitoring implants(Example Pacemaker, ECG real time tracking)
Advantages of IoT :
1. Improved efficiency and automation of tasks.
2. Increased convenience and accessibility of information.
3. Better monitoring and control of devices and systems.
4. Greater ability to gather and analyze data.
5. Improved decision-making.
6. Cost savings.
Disadvantages of IoT :
1. Security concerns and potential for hacking or data breaches.
2. Privacy issues related to the collection and use of personal data.
3. Dependence on technology and potential for system failures.
4. Limited standardization and interoperability among devices.
5. Complexity and increased maintenance requirements.
6. High initial investment costs.
7. Limited battery life on some devices.
8. Concerns about job displacement due to automation.
9. Limited regulation and legal framework for IoT, which can lead to confusion and
uncertainty.
IoT Architecture
There is not such a unique or standard consensus on the Internet of Things (IoT) architecture
which is universally defined. The IoT architecture differs from their functional area and their
solutions. However, the IoT architecture technology mainly consists of four major components:
Components of IoT Architecture
o Sensors/Devices
o Gateways and Networks
o Cloud/Management Service Layer
o Application Layer
Stages of IoT Solutions Architecture
There are several layers of IoT built upon the capability and performance of IoT elements that
provides the optimal solution to the business enterprises and end-users. The IoT architecture is a
fundamental way to design the various elements of IoT, so that it can deliver services over the
networks and serve the needs for the future.
Following are the primary stages (layers) of IoT that provides the solution for IoT architecture.
1. Sensors/Actuators: Sensors or Actuators are the devices that are able to emit, accept and process
data over the network. These sensors or actuators may be connected either through wired or
wireless. This contains GPS, Electrochemical, Gyroscope, RFID, etc. Most of the sensors need
connectivity through sensors gateways. The connection of sensors or actuators can be through a
Local Area Network (LAN) or Personal Area Network.
2. Gateways and Data Acquisition: As the large numbers of data are produced by this sensors and
actuators need the high-speed Gateways and Networks to transfer the data. This network can be of
type Local Area Network (LAN such as WiFi, Ethernet, etc.), Wide Area Network (WAN such as
GSM, 5G, etc.).
3. Edge IT: Edge in the IoT Architecture is the hardware and software gateways that analyze and pre-
process the data before transferring it to the cloud. If the data read from the sensors and gateways
are not changed from its previous reading value then it does not transfer over the cloud, this saves
the data used.
4. Data center/ Cloud: The Data Center or Cloud comes under the Management Services which
process the information through analytics, management of device and security controls. Beside this
security controls and device management the cloud transfer the data to the end users application
such as Retail, Healthcare, Emergency, Environment, and Energy, etc.
One big difference between IoT devices and computers is that the main function of IoT devices is
not to compute(not to be a computer) and the main function of a computer is to compute functions
and to run programs. But on IoT devices that is not its main point, it has some other function besides
that. As an example like in cars, the function of IoT devices are not to compute anti-lock breaking or
to do fuel injection, their main function from the point of view of a user is to be driven and to move
you from place to place and the computer is just to help that function. For example, The main
function of the car is not to compute like anti-lock breaking or to do fuel injection their main
function from the point of view of a user is to drive, to move you from place to place. But when we
embed software in it then the software can be able for fuel limit detection.
In the last IoT tutorial, we introduced hardware and software used in IoT. Today, we will
study how IoT works or How the Internet of Things works. Moreover, we will the IoT
components. In addition, we will see some real-time example of how IoT works.
People who came up with this idea, have also realized that this IoT ecosystem is not limited to
a particular field but has business applications in areas of home automation, vehicle
automation, factory line automation, medical, retail, healthcare and more.
How IoT Works – Internal working of the Internet of Things
IoT Components
Here, 4 fundamental components of IoT system, which tells us how IoT works.
i. Sensors/Devices
First, sensors or devices help in collecting very minute data from the surrounding
environment. All of this collected data can have various degrees of complexities ranging from
a simple temperature monitoring sensor or a complex full video feed.
A device can have multiple sensors that can bundle together to do more than just sense things.
For example, our phone is a device that has multiple sensors such as GPS, accelerometer,
camera but our phone does not simply sense things.
The most rudimentary step will always remain to pick and collect data from the surrounding
environment be it a standalone sensor or multiple devices.
ii. Connectivity
Next, that collected data is sent to a cloud infrastructure but it needs a medium for transport.
The sensors can be connected to the cloud through various mediums of communication and
transports such as cellular networks, satellite networks, Wi-Fi, Bluetooth, wide-area networks
(WAN), low power wide area network and many more.
Every option we choose has some specifications and trade-offs between power consumption,
range, and bandwidth. So, choosing the best connectivity option in the IOT system is
important.
Introduction to Arduino
Arduino is a project, open-source hardware, and software platform used to design and build
electronic devices. It designs and manufactures microcontroller kits and single-board
interfaces for building electronics projects.
The Arduino boards were initially created to help the students with the non-technical
background.
The Arduino board consists of sets of analog and digital I/O (Input / Output) pins, which are
further interfaced to breadboard, expansion boards, and other circuits. Such boards feature
the model, Universal Serial Bus (USB), and serial communication interfaces, which are
used for loading programs from the computers.
TYPES OF AURDINO
The flexibility of the Arduino board is enormous so that one can do anything they imagine.
This board can be connected very easily to different modules such as obstacle sensors,
presence detectors, fire sensors, GSM Modules GPS modules, etc. The main function of the
Arduino board is to control electronics through reading inputs & changing it into outputs
because this board works like a tool. This board is also used to make different electronics
projects in the field of electronics, electrical, robotics, etc.
The features of different types of Arduino boards are listed in the tabular form.
Digital Analogue
Arduino Board Processor Memory I/O I/O
6 input, 0
16Mhz 2KB SRAM,
Arduino Uno 14 output
ATmega328 32KB flash
84MHz 96KB SRAM, 12 input, 2
Arduino Due AT91SAM3X8 512KB 54 output
E flash
8KB SRAM, 16 input, 0
16MHz 256KB
Arduino Mega 54 output
ATmega2560 flash
2.5KB SRAM, 12 input, 0
Arduino 16MHz 32KB 20 output
Leonardo ATmega32u4 flash
The Uno is a huge option for your initial Arduino. This Arduino board depends on an
ATmega328P based microcontroller. As compared with other types of arduino boards, it is
very simple to use like the Arduino Mega type board. .It consists of 14-digital I/O pins, where
6-pins can be used as PWM(pulse width modulation outputs), 6-analog inputs, a reset button,
a power jack, a USB connection, an In-Circuit Serial Programming header (ICSP), etc. It
includes everything required to hold up the microcontroller; simply attach it to a PC with the
help of a USB cable and give the supply to get started with an AC-to-DC adapter or battery.
Arduino Uno (R3)
rduino Uno is the most frequently used board and it is the standard form apart from all the
existing Arduino Boards. This board is very useful for beginners. Please refer to this link to
know more about Arduino Uno Board
Arduino Nano
This is a small board based on the microcontrollers like ATmega328P otherwise ATmega628
but the connection of this board is the same as to the Arduino UNO board. This kind of
microcontroller board is very small in size, sustainable, flexible, and reliable.
Arduino Nano
As compared with the Arduino Uno board, it is small in size. The devices like mini USB and
Arduino IDE are necessary to build the projects. This board mainly includes analog pins-8,
digital pins-14 with the set of an I/O pin, power pins-6 & RST (reset) pins-2. Please refer to
this link to know more about Arduino Nano Board.
Arduino Micro
The Arduino Micro board mainly depends on the ATmega32U4 based Microcontroller that
includes 20-sets of pins where the 7-pins are PWM pins, 12-analog input pins. This board
includes different components like an ICSP header, RST button, small USB connection,
crystal oscillator-16MHz. The USB connection is inbuilt and this board is the shrunk version
of the Leonardo board.
Arduino Micro
Arduino Due
This Arduino board depends on the ARM Cortex-M3 and it is the first Arduino
microcontroller board. This board includes digital I/O pins-54 where 12-pins are PWM o/p
pins, analog pins -12, UARTs-4, a CLK with 84 MHz, an USB OTG, DAC-2, a power jack,
TWI-2, a JTAG header, an SPI header, two buttons for reset & erase.
Arduino Due
This board works with 3.3V where the highest voltage that the pins of input/output can stand
is 3.3V because providing a high voltage to any I/O pin can lead to damage the board This
board is simply connected to a computer through a small USB cable otherwise it can be
powered through an AC to DC adapter. This Arduino Due board is suitable with all shields of
Arduino at 3.3V.
The Lily Pad Arduino board is a wearable e-textile technology expanded by Leah ―
Buechley‖ and considerately designed by ―Leah and SparkFun‖. Each board was
imaginatively designed with huge connecting pads & a smooth back to let them to be sewn
into clothing using conductive thread. This Arduino also comprises of I/O, power, and also
sensor boards which are built especially for e-textiles. These are even washable!
LilyPad Arduino Boards
Arduino Bluetooth
This Bluetooth mainly depends on the microcontroller like ATmega168 and this board is also
called Arduino BT. This kind of board includes different components like digital pins-16,
analog pins-6, crystal oscillator-16MHz, reset button, screw terminals, ICSP header. In this
board, the screw terminals are mainly used for power. The programming of this Bluetooth
microcontroller can be done with Bluetooth like a wireless connection.
Arduino Diecimila
The microcontroller board like Arduino Diecimila mainly depends on the ATmega168. This
board includes digital I/O pins -14 where 6-pins can be used like PWM outputs & analog
inputs-6, a USB connection, a crystal oscillator-16 MHz, an ICSP header, a reset button & a
power jack. This board can be connected to a computer through a USB cable and it can be
activated using a battery and an AC-DC adapter.
Arduino Diecimila
As the name suggests, the meaning of Diecimila in Italian is 10,000 which means that marks
the truth that above 10k Arduino boards have been designed. In a set of USB Arduino boards,
it is the latest one as compared with other versions.
The RedBoard Arduino board can be programmed using a Mini-B USB cable using the
Arduino IDE. It will work on Windows 8 without having to modify your security settings. It
is more constant due to the USB or FTDI chip we used and also it is entirely flat on the back.
Creating it is very simple to utilize in the project design. Just plug the board, select the menu
option to choose an Arduino UNO and you are ready to upload the program. You can control
the RedBoard over a USB cable using the barrel jack.
RedBoard Arduino Boards
The Arduino Mega is similar to the UNO‟s big brother. It includes lots of digital I/O pins
(from that, 14-pins can be used as PWM o/ps), 6-analog inputs, a reset button, a power jack, a
USB connection, and a reset button. It includes everything required to hold up the
microcontroller; simply attach it to a PC with the help of a USB cable and give the supply to
get started with an AC-to-DC adapter or battery. The huge number of pins make this Arduino
board very helpful for designing projects that need a bunch of digital i/ps or o/ps like lots of
buttons. Please refer to this link to know more about Arduino Mega (R3) Board
The first development board of an Arduino is the Leonardo board. This board uses one
microcontroller along with the USB. That means, it can be very simple and cheap also.
Because this board handles USB directly, program libraries are obtainable which let the
Arduino board to follow a keyboard of the computer, mouse, etc.
Arduino Leonardo Board
Arduino Robot
This kind of board is the first Arduino over wheels. This Arduino robot includes two
processors on each of its boards. The two boards are the motor board and control board where
the motor board controls the motors & the control board is used to read the sensors for
operating. Every board is a complete Arduino board and its programming can be done
through the Arduino IDE. These are microcontroller boards that depend on the ATmega32u4.
The pins of this Robot are mapped to actuators and sensors onboard. The process of
programming the robot is the same as the Arduino Leonardo board. It is also named a small
computer and it is extensively used in robotics. This board includes the speaker, color screen,
buttons-5, motors-2, a digital compass, an SD card reader, potentiometers-2 & floor sensors-
5. The library of this robot can be used for controlling the sensors as well as the actuators.
Arduino Esplora
Arduino Esplora
The programming of this board can be done using Arduino Software like IDE which takes the
data from the inputs and controls the output like a keyboard or a mouse. As compared with all
other types of Arduino boards, this esplora is totally different because the inputs, as well as
outputs, are connected to the board already. So connecting the components like actuators or
sensors is very simple. Thus, programming is somewhat different as compared with other
types of Arduino boards. This esplora board includes its own library so that the data from the
sensors & actuators are very easy to read and write.
The Arduino Pro Micro board is the same as the Arduino Mini board apart from the
ATmega32U4 Microcontroller. This pro mic board includes digital I/O pins-12, pulse width
modulation (PWM) pins-5, serial connections of Tx & Rx &10-bit ADC.
Arduino Ethernet
The Arduino Ethernet board depends on the microcontroller like ATmega328. This kind of
microcontroller board includes analog pins-5, digital I/O pins-14, RST button, an RJ45
connection, crystal oscillator, a power jack, ICSP header, etc. The connection of the Arduino
board can be done through the Ethernet shield to the internet.
Arduino Zero
This is a powerful as well as simple 32-bit board and it provides the best platform for
innovative projects like wearable technology, smart IoT devices, crazy robotics, high-tech
automation, etc. This board expands by providing improved performance, permitting a range
of project opportunities & performs like a great educational tool.
Arduino Zero
This board includes analog input pins-6, digital I/O pins-14, a power jack, AREF button,
UART port pins, a USB connector & an In-Circuit Serial Programming (ICSP) header, a
power header, etc.
This board is power-driven through the SAMD21 microcontroller based on Atmel. The main
feature of this is EDBG (Embedded Debugger) based on Atmel and it provides a complete
debug interface without using extra hardware.
Fastest Arduino Board
Designing one of the best Arduino development boards that are familiar with Arduino MEGA
& UNO is the hifive1 board that includes a 320 MHz RISC-V microcontroller unit. This kind
of fastest board has Cortex M-7 with a 400 MHz microcontroller unit.
RAM – 1 Mbyte
DMA controllers -4
Communication peripherals- Up to 35
Cryptographic Acceleration
A tool chain is simply a set of software tools that work together to complete a task. for
example, if we were going to hang a picture, the tool chain might include a hammer, maybe a
tape measure and some nails.
The problem is that a microcontroller (like the ATmega328 on the Uno) can only execute
simple, low-level instructions. These simple instructions include things like add variable a to
variable b or take variable b and put it in register x.
And, to complicate matters, microcontrollers only speak in binary. For those who don’t
know, binary numbers are long strings of 1s and 0s. If you need to brush up on binary
numbers, see A Bit of Fun with Binary Number Basics.
Glad you asked. No, really, I am. This is what we’re going to answer now.
Microcontrollers are electronic devices, so to speak to one you need to send electronic
signals, as in figure 1. That’s where binary numbers come into play. A zero represents low or
off, usually 0 V or close to it, while a one represents high or on, usually either about 5 V or
3.3 V, depending on the processor.
A good way to think of binary numbers and digital signals is like a single pole light switch.
The light is either on or its off, there is nothing in between. Zero is off and one is on.
Going from complex instructions to simple ones the microcontroller understands requires
several layers of software that translate the high-level operations into simpler instructions.
How the Arduino Compiler Works
Enter the compiler. Compiling a program in Arduino is referred to as verifying. The terms
mean the same thing, so throughout these tutorials we’ll use them interchangeably.
The compiler first transforms the code you write into assembly language. The name of the
compiler we’ll be using on our Uno is AVR-GCC. If you’re new to this, that may sound kind
of weird but try not to obsess over it. It’s just a name.
The assembler, which come with the IDE with the compiler, then translates the assembly
language program into machine language. It then creates object files, which combine
machine language, data, and information it needs to place instructions properly in memory.
Often, the assembler creates multiple files which will eventually be put together.
This is where the linker — another part of the compiler software package — shines. The
linker will take all the independently assembled machine language programs and object files
and put them together. This produces a .hex file that the microprocessor can understand and
run.
The two figures below, though they apply to C/C++ programming in general, are a good
illustration of this process.
Figure: Arduino code compilation process. The figure below is another way to view it.
Programming in C vs Arduino
A few words are in order on this subject due to the enormous popularity of Arduino boards
and the C/C++ language in general.
Some of you use stand-alone or naked microcontrollers for your projects. After all, this is
how things are actually made and mass-produced in the real world. And it’s cheaper. We
talked about naked or stand-alone microcontrollers vs Arduino in an earlier tutorial.
Others use platforms or ecosystems such as the Arduino almost (or entirely) exclusively.
Finally, some of you may use both depending on your goals and background.
For hobbyists, the number of people who use platforms like Arduino has exceeded those who
only use naked microcontrollers.
When we talk about programming the Arduino, we’ll talk about the C/C++ languages. The
truth is, sketches are written in a language similar to C, though a sketch itself is not
completely compatible with C.
In Arduino, the main() function is hidden from view and added for you when you compile or
―verify‖ your sketch. Also, there are two functions which the Arduino ecosystem absolutely
requires: setup() and loop(). The only function C requires is main().
C also lacks built-in functions for using microcontroller I/O such as digitalWrite().
To make learning simple, the Arduino IDE designers hide a lot of detail and functionality
behind layers of abstraction, many of which come in the form of libraries. Note that the C
programming language also uses libraries. The linker adds them during the linking process.
Though there are a few slight differences, if you can become a competent C programmer,
you’ll also master the Arduino IDE and crush it on your Arduino projects. And if you desire
to port the code from Arduino to a naked micro it will be a cinch.
Sketch − The first new terminology is the Arduino program called ―sketch‖.
Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions. In this tutorial, we will learn about the Arduino software program,
step by step, and how we can write the program without any syntax or compilation error.
Let us start with the Structure. Software structure consist of two main functions −
Setup( ) function
Loop( ) function
Void setup ( ) {
}
PURPOSE − The setup() function is called when a sketch starts. Use it to initialize the
variables, pin modes, start using libraries, etc. The setup function will only run once, after
each power up or reset of the Arduino board.
INPUT − -
OUTPUT − -
RETURN − -
Void Loop ( ) {
}
PURPOSE − After creating a setup() function, which initializes and sets the initial values,
the loop() function does precisely what its name suggests, and loops consecutively, allowing
your program to change and respond. Use it to actively control the Arduino board.
INPUT − -
OUTPUT − -
RETURN − -
2. Arduino – DataTypes
Data types in C refers to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in the storage
and how the bit pattern stored is interpreted.
The following table provides all the data types that you will use during Arduino
programming.
Void, Boolean , char, Unsigned, Unsigned, char , byte, int, Unsigned, int, word
String. Array, long, long, short , float , double , array, char, String, object
void
The void keyword is used only in function declarations. It indicates that the function is
expected to return no information to the function from which it was called.
Boolean
A Boolean holds one of two values, true or false. Each Boolean variable occupies
one byte of memory.
Char
A data type that takes up one byte of memory that stores a character value. Character literals are
written in single quotes like this: 'A' and for multiple characters, strings use double quotes:
"ABC".
However, characters are stored as numbers. You can see the specific encoding in the ASCII
chart. This means that it is possible to do arithmetic operations on characters, in which the
ASCII value of the character is used. For example, 'A' + 1 has the value 66, since the ASCII
value of the capital letter A is 65.
unsigned char
Unsigned char is an unsigned data type that occupies one byte of memory. The unsigned char
data type encodes numbers from 0 to 255.
byte
Example
Unsigned Char chr_y = 121 ; // declaration of variable with type Unsigned char and
initialize it with character y
Int
Example
byte m = 25 ;//declaration of variable with type byte and initialize it with
25
Integers are the primary data-type for number storage. int stores a 16-bit (2-byte) value.
This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of
(2^15) - 1).
The int size varies from board to board. On the Arduino Due, for example, an int stores a
32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value
of -2^31 and a maximum value of (2^31) - 1).
Example
int counter = 32 ;// declaration of variable with type int and initialize it with
32
Unsigned int
Unsigned ints (unsigned integers) are the same as int in the way that they store a 2 byte value.
Instead of storing negative numbers, however, they only store positive values, yielding a useful
range of 0 to 65,535 (2^16) - 1). The Due stores a 4 byte (32-bit) value, ranging from 0 to
4,294,967,295 (2^32 - 1).
Example
Unsigned int counter= 60 ; // declaration of variable with type unsigned int and
initialize it with 60
Word
On the Uno and other ATMEGA based boards, a word stores a 16-bit unsigned number. On the
Due and Zero, it stores a 32-bit unsigned number.
Example
word w = 1000 ;//declaration of variable with type word and initialize it with
1000
Long
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from
2,147,483,648 to 2,147,483,647.
Example
Long velocity= 102346 ;//declaration of variable with type Long and initialize it with
102346
unsigned long
Unsigned long variables are extended size variables for number storage and store 32 bits (4
bytes). Unlike standard longs, unsigned longs will not store negative numbers, making
their range from 0 to 4,294,967,295 (2^32 - 1).
Unsigned Long velocity = 101006 ;// declaration of variable with type Unsigned
Long and initialize it with 101006
short
A short is a 16-bit data-type. On all Arduinos (ATMega and ARM based), a short stores a
16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a
maximum value of (2^15) - 1).
Float
short val= 13 ;//declaration of variable with type short and initialize it with
13
Data type for floating-point number is a number that has a decimal point. Floating-point
numbers are often used to approximate the analog and continuous values because they have
greater resolution than integers.
float num = 1.352;//declaration of variable with type float and initialize it with 1.352
double
On the Uno and other ATMEGA based boards, Double precision floating-point
number occupies four bytes. That is, the double implementation is exactly the same as
the float, with no gain in precision. On the Arduino Due, doubles have 8-byte (64 bit)
precision.
double num = 45.352 ;// declaration of variable with type double and initialize it with
45.352
Before we start explaining the variable types, a very important subject we need to make sure,
you fully understand is called the variable scope.
Local Variables
Variables that are declared inside a function or block are local variables. They can be used only
by the statements that are inside that function or block of code. Local variables are not known to
function outside their own. Following is the example using local variables:
Global Variables
Global variables are defined outside of all the functions, usually at the top of the program.
The global variables will hold their value throughout the life-time of your program.
A global variable can be accessed by any function. That is, a global variable is available for
use throughout your entire program after its declaration.
Arduino - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators
−
Arithmetic Operators
Comparison Operators
Boolean Operators
Bitwise Operators
Compound Operators
Arithmetic Operators
Assume variable A holds 10 and variable B holds 20 then –
Operator Operator Description Example
name simple
assignment = Stores the A=B
operator value to the
right of the
equal sign in
the variable
to the left of
the equal
sign.
addition + Adds two A + B
operands will give
30
subtraction - Subtracts A - B
second will give
operand from -10
the first
multiplication * Multiply both A * B
operands will give
200
division / Divide B / A
numerator by will give
denominator 2
modulo % Modulus B % A
Operator and will give
remainder of 0
after an
integer
division
Comparison Operators
Assume variable A holds 10 and variable B holds 20 then −
Boolean Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator Operator Description Example
name simple
Called Logical OR
Operator. If any of
the two operands is (A || B)
or ||
non-zero then then is true
condition becomes
true.
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Operator Operator Description Example
name simple
(A | B)
Binary OR Operator copies will give
or | a bit if it exists in either 61 which
operand is 0011
1101
(A ^ B)
Binary XOR Operator will give
xor ^ copies the bit if it is set in 49 which
one operand but not both. is 0011
0001
(~A )
will give
Binary Ones Complement
-60
not ~ Operator is unary and has
which is
the effect of 'flipping' bits.
1100
0011
A << 2
Binary Left Shift Operator.
will give
The left operands value is
240
shift left << moved left by the number
which is
of bits specified by the
1111
right operand.
0000
Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
Operator Operator Description Example
name simple
Increment operator,
A++ will
increment ++ increases integer value
give 11
by one
Decrement operator,
A-- will
decrement -- decreases integer value
give 9
by one
Subtract AND
assignment operator. It B -= A is
compound subtracts right operand equivalent
-=
subtraction from the left operand to B = B -
and assign the result to A
left operand
Multiply AND
assignment operator. It B*= A is
compound multiplies right operand equivalent
*=
multiplication with the left operand and to B = B*
assign the result to left A
operand
Modulus AND B %= A
assignment operator. It is
compound
%= takes modulus using two equivalent
modulo
operands and assign the to B = B
result to left operand %A
A |= 2 is
compound bitwise inclusive OR and
|= same as A
bitwise or assignment operator
=A|2
A &= 2 is
compound Bitwise AND
&= same as A
bitwise and assignment operator
=A&2
Arduino IDE
4. Before burning this code into the Arduino board, we need to configure the IDE for the board
we need to burn this sketch into. We also need to select the appropriate communication port and
the method used for burning the code.
5. Go to the Tools tab and find the Board option in it. It will have a list of all the Arduino
Boards in it. Select the board you are using from that list. Here, we have used Arduino/Genuino
Uno Board.
Arduino and Genuino are one and the same thing. Outside the USA, the Arduino boards are
called Genuino.
6. Now we need to select the appropriate communication port over which the computer/laptop
will communicate with the Arduino board. Under the Tools tab, you will find the Port option.
Select the port you have connected the Arduino board to from the Ports available in this list.
7. Now that we have selected the board and the communication port, we need to select the
appropriate programmer.
We will be using the AVR ISP mk2 programmer.
8. On the Arduino IDE, you will find 6 unique buttons. These are described below.
This is used to upload (Arduino refers burning a program as uploading) the sketch
onto the board.
The Arduino Sketchbook Folder And Changing The Default Save Location
The default location where Arduino sketches you write will be saved is called the Sketchbook.
The Sketchbook is simply a folder on your computer like any other. It acts as a handy repository
for sketches and is also where add-on code libraries get saved.
You can see the sketches in the Sketchbook folder by going to File > Sketchbook.
The default name of the Sketchbook folder is ―Arduino‖ and the default location of the
Sketchbook folder is in the ―My Documents‖ folder (or just ―Documents‖ for Mac users).
If your Sketchbook does not appear to be in this default location, you can see exactly where it is
by opening the Arduino IDE and going to Arduino > Preferences.
The default file path for your sketches is listed at the top of Arduino Preferences window. Mine
is:
/Users/michaelJames/Documents/Arduino
When I save a file in the Arduino IDE, this ―Arduino‖ folder is the default location where the
sketch will be saved, unless I choose to change that location by selecting a different folder on
my computer’s directory.
If you want to change this default location, you click the Browse button next to the file directory
path and choose a different place. Pretty simple.
SKETCH FOLDERS
If you go into your file directory system and open up the Sketchbook folder (again, named
―Arduino‖ by default), you may see a bunch of folders that you didn’t make. This is because
every Arduino file must be inside a folder that has the same name as the file (there are some
exceptions to this that we’ll talk about in a moment).
Let me say that one more time because it is really important to understand. Every Arduino file
must be inside a folder that has the same name as the file When I write a new sketch and save it,
the Arduino IDE automatically creates a new folder that has the exact same name as the sketch
itself. The Arduino file (which has the extension .ino) is placed inside this enclosing folder,
which is called a sketch folder.
If you go into the Sketchbook folder and change the name of the enclosing folder, it will create
some issues. The first issue is that when you go to File > Sketchbook, the sketch will no longer
show up! If you want to open this sketch you need to go to the .ino file in your directory and
open it from there.
If you open a .ino file that is not inside an enclosing sketch folder of the exact same name, then
you will get a pop-up from the Arduino IDE that says:
―The file ―sketch_name.ino‖ needs to be inside a sketch folder named ―sketch_name‖. Create
this folder, move the file, and continue?‖
If you choose Cancel, the sketch will not open. If you choose OK, then a folder gets created (it
will have the same name as the sketch) and the .ino file is placed inside it.
This sketch folder will be created in whatever directory the .ino file was that you tried to open.
For example, if you tried to open a .ino file that was in your My Downloads folder, then the
enclosing sketch folder also will be created inside the My Downloads folder.
Once you get a handle on some of these intricacies of the Arduino IDE file system, it can really
help to clear things up.
Arduino Shields
Shield is defined as the hardware device that can be mounted over the board to increase the
capabilities of the projects. It also makes our work easy. For example, Ethernet shields are used
to connect the Arduino board to the Internet.
The pin position of the shields is similar to the Arduino boards. We can also connect the
modules and sensors to the shields with the help of the connection cable.
Arduino motor shields help us to control the motors with the Arduino board.
Why do we need Shields?
The advantages of using Arduino shields are listed below:
o It adds new functionalities to the Arduino projects.
o The shields can be attached and detached easily from the Arduino board. It does not
require any complex wiring.
o It is easy to connect the shields by mounting them over the Arduino board.
o The hardware components on the shields can be easily implemented.
Types of Shields
The popular Arduino shields are listed below:
o Ethernet shield
o Xbee Shield
o Proto shield
o Relay shield
o Motor shield
o LCD shield
o Bluetooth shield
o Capacitive Touchpad Shield
o We can also connect another shield on the top of the Ethernet shield. It means that we can
also mount two shields on the top of the Arduino board.
Xbee Shield
o We can communicate wirelessly with the Arduino board by using the Xbee Shield with
Zigbee.
o It reduces the hassle of the cable, which makes Xbee a wireless communication model.
o The Xbee wireless module allows us to communicate outdoor upto 300 feet and indoor
upto 100 feet.
o The Xbee shield is shown below:
Proto shield
o Proto shields are designed for custom circuits.
o We can solder electronic circuits directly on the shield.
o The shield consists of two LED pads, two power lines, and SPI signal pads.
o The IOREF (Input Output voltage REFerence) and GND (Ground) are the two power
lines on the board.
The proto shield is shown below:
o We can also solder the SMD (Surface Mount Device) ICs on the prototyping area. A
maximum of 24 pins can be integrated onto the SMD area.
Relay shield
o The Arduino digital I/O pins cannot bear the high current due to its voltage and current
limits. The relay shield is used to overcome such situation. It provides a solution for controlling
the devices carrying high current and voltage.
o The shield consists of four relays and four LED indicators.
o It also provides NO/NC interfaces and a shield form factor for the simple connection to
the Arduino board.
o The LED indicators depicts the ON/OFF condition of each relay.
o The relay used in the structure is of high quality.
o The NO (Normally Open), NC (Normally Closed), and COM pins are present on each
relay.
o The relay shield is shown below:
o The applications of the motor shield are intelligent vehicles, micro-robots, etc.
LCD shield
o The keypad of LCD (Liquid Crystal Display) shield includes five buttons called as up,
down, left, right, and select.
o There are 6 push buttons present on the shield that can be used as a custom menu control
panel.
o It consists of the 1602 white characters, which are displayed on the blue backlight LCD.
o The LED present on the board indicates the power ON.
o The five keys present on the board helps us to make the selection on menus and from
board to our project.
o
The LCD shield is shown below:
o The LCD shield is popularly designed for the classic boards such as Duemilanove, UNO,
etc.
Bluetooth shield
o The Bluetooth shield can be used as a wireless module for transparent serial
communication.
o It includes a serial Bluetooth module. D0 and D1 are the serial hardware ports in the
Bluetooth shield, which can be used to communicate with the two serial ports (from D0 to D7)
of the Arduino board.
o We can install Groves through the two serial ports of the Bluetooth shield called a Grove
connector. One Grove connector is digital, while the other is analog.
The Bluetooth shield is shown below:
o The communication distance of the Bluetooth shield is upto 10m at home without any
obstacle in between.
The Internet of Things is a major contributing factor of the new Data Economy. The value of an
IoT system goes beyond the original intended use case, for instance in automation. This is
because further value lies in the intelligence that an IoT system creates. Sensors are the source
of IoT data. Furthermore, sensors and actuators in IoT can work together to enable automation
at industrial scale. Finally, analysis of the data that these sensors and actuators produce can
provide valuable business insights over time.
Different applications call for different ways of measuring the same thing. At the same time, a
single variable could trigger multiple actions. As a result, sensors and actuators in IoT must
work together reliably.
When the impeller spins, it will send a stream of electrical impulses to a computer. The
computer will interpret the impulses to determine how much beer is flowing through. Sounds
simple, right?
This is where sensors get interesting. If you look back at our description, you’ll see that we
never directly measured the amount of beer flowing through the sensor; we interpreted it from a
stream of electrical impulses. That means that we must first figure out how to interpret it.
Sensor Calibration
To calibrate the sensor, we’d have to take a container with a known carrying capacity, say, a
pint glass. Then we’d have to fill that container under a variety of conditions to determine what
the electrical pulse signal looked like. Then, monitor the actuator that is responsible to turn on
and off the flow on the other end.
For instance, the first pour off a new keg might tend to have more foam, which would read
differently than a pour from the middle of the keg that was all beer. It’s only through repeated
trials and a lot of data that we gain confidence that we can interpret the data. Sensors and
actuators in IoT can work together to automate processes, such as filling bottles.
The Importance of Accurate Calibration
With this correlation identified, a protocol can always assure the sensor is reading correctly.
This process is calibration. Reputable manufacturers will deliver fully calibrated devices and
provide instruction on how to re-calibrate to verify sensor accuracy.
The accuracy of sensed data is paramount, since you will make mission-critical decisions based
on later analysis of the data, which will hold little value if the data is wrong.
Pins
Digital vs Analog
Digital Input
int digitalRead(pin)
int pinval;
pinval = digitalRead(3);
Digital Output
Analog Input
int analogRead(pin)
int pinval;
pinval = analogRead(A3);
Analog Output
ARDUINO SHIELDS
Types of Shields
o Ethernet shield
o Xbee Shield
o Proto shield
o Relay shield
o Motor shield
o LCD shield
o Bluetooth shield
o Capacitive Touchpad Shield
Ethernet shield
o The Ethernet shields are used to connect the Arduino board to the Internet. We need
to mount the shield on the top of the specified Arduino board.
o The USB port will play the usual role to upload sketches on the board.
o The latest version of Ethernet shields consists of a micro SD card slot. The micro SD
card slot can be interfaced with the help of the SD card library.
o We can also connect another shield on the top of the Ethernet shield. It means that we
can also mount two shields on the top of the Arduino board.
Xbee Shield
o We can communicate wirelessly with the Arduino board by using the Xbee Shield
with Zigbee.
o It reduces the hassle of the cable, which makes Xbee a wireless communication
model.
o The Xbee wireless module allows us to communicate outdoor upto 300 feet and
indoor upto 100 feet.
o The Xbee shield is shown below:
Proto shield
o Proto shields are designed for custom circuits.
o We can solder electronic circuits directly on the shield.
o The shield consists of two LED pads, two power lines, and SPI signal pads.
o The IOREF (Input Output voltage REFerence) and GND (Ground) are the two power
lines on the board.
o We can also solder the SMD (Surface Mount Device) ICs on the prototyping area. A
maximum of 24 pins can be integrated onto the SMD area.
Relay shield
o The Arduino digital I/O pins cannot bear the high current due to its voltage and
current limits. The relay shield is used to overcome such situation. It provides a
solution for controlling the devices carrying high current and voltage.
o The shield consists of four relays and four LED indicators.
o It also provides NO/NC interfaces and a shield form factor for the simple connection
to the Arduino board.
o The LED indicators depicts the ON/OFF condition of each relay.
o The relay used in the structure is of high quality.
o The NO (Normally Open), NC (Normally Closed), and COM pins are present on each
relay.
o The relay shield is shown below:
Motor shield
o The motor shield helps us to control the motor using the Arduino board.
o It controls the direction and working speed of the motor. We can power the motor
shield either by the external power supply through the input terminal or directly by the
Arduino.
o We can also measure the absorption current of each motor with the help of the motor
shield.
o The motor shield is based on the L298 chip that can drive a step motor or two DC
motors. L298 chip is a full bridge IC. It also consists of the heat sinker, which
increases the performance of the motor shield.
o It can drive inductive loads, such as solenoids, etc.
o The operating voltage is from 5V to 12V.
The Motor shield is shown below:
o The applications of the motor shield are intelligent vehicles, micro-robots, etc.
LCD shield
o The keypad of LCD (Liquid Crystal Display) shield includes five buttons called as up,
down, left, right, and select.
o There are 6 push buttons present on the shield that can be used as a custom menu
control panel.
o It consists of the 1602 white characters, which are displayed on the blue backlight
LCD.
o The LED present on the board indicates the power ON.
o The five keys present on the board helps us to make the selection on menus and from
board to our project.
o The LCD shield is popularly designed for the classic boards such as Duemilanove,
UNO, etc.
Bluetooth shield
o The Bluetooth shield can be used as a wireless module for transparent serial
communication.
o It includes a serial Bluetooth module. D0 and D1 are the serial hardware ports in the
Bluetooth shield, which can be used to communicate with the two serial ports (from
D0 to D7) of the Arduino board.
o We can install Groves through the two serial ports of the Bluetooth shield called a
Grove connector. One Grove connector is digital, while the other is analog.
o The communication distance of the Bluetooth shield is upto 10m at home without any
obstacle in between.
o The board can work with the logic level of 3.3V or 5V.
o We can establish a connection to the Arduino project by touching the shield.
Arduino is a popular microcontroller platform that allows you to easily interface with various
sensors and actuators to create interactive projects. Integrating sensors and actuators with
Arduino involves the following steps:
Selecting the appropriate sensors and actuators: Identify the specific sensors and actuators
you need for your project. Arduino supports a wide range of sensors such as temperature
sensors, motion sensors, light sensors, and actuators such as motors, servos, and LEDs.
Power supply: Ensure that your sensors and actuators have a suitable power supply. Arduino
boards can usually provide power to low-power sensors and actuators directly from their
digital or analog pins. However, high-power devices like motors may require an external
power source.
Wiring connections: Connect the sensors and actuators to the Arduino board using jumper
wires or appropriate connectors. Arduino boards typically have digital input/output (I/O)
pins, analog input pins, and power pins that you can use for wiring.
For digital sensors and actuators, you can connect them to the digital I/O pins. These pins can
be configured as either input or output.
Analog sensors can be connected to the analog input pins, which can read continuous voltage
values.
Power and ground connections should be made to provide appropriate voltage and common
reference for the sensors and actuators.
Library installation: Some sensors and actuators require specific libraries to be installed in the
Arduino Integrated Development Environment (IDE). These libraries provide pre-written
code and functions that make it easier to interface with the devices. You can install libraries
by navigating to Sketch -> Include Library -> Manage Libraries in the Arduino IDE.
Code development: Write the Arduino code to read sensor data and control the actuators. The
code should include appropriate functions and commands to initialize the sensors, read their
values, and control the actuators based on the sensor inputs. The specific code will depend on
the sensors and actuators you are using, so refer to their respective documentation and
examples.
Uploading and testing: Upload the code to the Arduino board and test the integration. Use the
Serial Monitor in the Arduino IDE to view sensor readings or debug any issues. Make sure
the sensors and actuators are functioning as expected.
By following these steps, you can integrate sensors and actuators with Arduino to create
interactive projects and prototypes. The possibilities are vast, ranging from simple projects
like temperature monitoring and LED control to complex robotics and automation systems.