Unit-3 ES & IOT Notes-IOT and Arduino Programming
Unit-3 ES & IOT Notes-IOT and Arduino Programming
• IoT Configurations
• Basic Components
• Introduction to Arduino
• Types of Arduino
• Arduino Toolchain
• Sketches
• Pins
IoT stands for Internet of Things, which means accessing and controlling daily usable
equipments and devices using Internet.
Connecting everyday things embedded with electronics, software, and sensors to internet
enabling to collect and exchange data without human interaction called as the Internet of Things
(IoT).
The term "Things" in the Internet of Things refers to anything and everything in day to day life
which is accessed or connected through the internet.
IoT is an advanced automation and analytics system which deals with artificial intelligence,
sensor, networking, electronic, cloud messaging etc. to deliver complete systems for the product
or services. The system created by IoT has greater transparency, control, and performance.
As we have a platform such as a cloud that contains all the data through which we connect all the
things around us. For example, a house, where we can connect our home appliances such as air
conditioner, light, etc. through each other and all these things are managed at the same platform.
Since we have a platform, we can connect our car, track its fuel meter, speed level, and also track
the location of the car.
If there is a common platform where all these things can connect to each other would be great
because based on my preference, I can set the room temperature. For example, if I love the room
temperature to to be set at 25 or 26-degree Celsius when I reach back home from my office, then
according to my car location, my AC would start before 10 minutes I arrive at home. This can be
done through the Internet of Things (IoT).
Connectivity: Connectivity refers to establish a proper connection between all the things of IoT
to IoT platform it may be server or cloud. After connecting the IoT devices, it needs a high speed
messaging between the devices and cloud to enable reliable, secure and bi-directional
communication.
Analyzing: After connecting all the relevant things, it comes to real-time analyzing the data
collected and use them to build effective business intelligence. If we have a good insight into
data gathered from all these things, then we call our system has a smart system.
Integrating: IoT integrating the various models to improve the user experience as well.
Artificial Intelligence: IoT makes things smart and enhances life through the use of data. For
example, if we have a coffee machine whose beans have going to end, then the coffee machine
itself order the coffee beans of your choice from the retailer.
Sensing: The sensor devices used in IoT technologies detect and measure any change in the
environment and report on their status. IoT technology brings passive networks to active
networks. Without sensors, there could not hold an effective or true IoT environment.
Active Engagement: IoT makes the connected technology, product, or services to active
engagement between each other.
Endpoint Management: It is important to be the endpoint management of all the IoT system
otherwise, it makes the complete failure of the system. For example, if a coffee machine itself
order the coffee beans when it goes to end but what happens when it orders the beans from a
retailer and we are not present at home for a few days, it leads to the failure of the IoT system.
So, there must be a need for endpoint management.
An embedded device system generally runs as a single application. However, these devices can
connect through the internet connection, and able communicate through other network devices.
5|P ag e
3.1.5. Embedded System Hardware
The embedded system can be of type microcontroller or type microprocessor. Both of these types
contain an integrated circuit (IC).
The essential component of the embedded system is a RISC family microcontroller like
Motorola 68HC11, PIC 16F84, Atmel 8051 and many more. The most important factor that
differentiates these microcontrollers with the microprocessor like 8085 is their internal read and
writable memory. The essential embedded device components and system architecture are
specified below.
6|P ag e
The IoT decision framework is much more important as the product or services communicates
over networks goes through five different layers of complexity of technology.
1. Device Hardware
2. Device Software
3. Communications
4. Cloud Platform
5. Cloud Application
The IoT decision framework pays attention to six key decision areas in any IoT product. These
decision areas are:
1. User Experience (UX)
2. Data
3. Business
4. Technology
5. Security
6. Standards & Regulations
Each of these decision areas is evaluated at each of the IoT Technology Stack. The User
Experience will be evaluated at Device Hardware, Device Software and so to provide the better
user experience. Then at the next step Data Decision Area, we have to explore data
considerations for all the stages of IoT Technology Stack.r
7|P ag e
Let's see each of the Decision Area of IoT Decision Framework in detail:
1. User Experience Decision Area: This is the area where we concentrate about who are
the users, what are their requirements and how to provide a great experience at each step
of IoT stack without worrying about the technical details.
2. Data Decision Area: In this area, we make the overall data strategy such as the data flow
over the entire IoT stack to fulfill the user's requirements.
3. Business Decision Area: Based on the previous decisions area, we make the decision
how product or services will became financial potential. At each of the IoT Stack level
are monetized about the costs of providing services.
4. Technology Decision Area: In this area, we work with the technology for each layer to
facilitate the final solution.
5. Security Decision Area: After going through the implementation of technology it is
important to decide and provide the security at each stage of the IoT Stack.
6. Standards & Regulations Decision Area: At the last stage of IoT Decision Area, we
identify the standards and regulations of product or services that will affect your product
at each layer of the IoT Stack.
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.
8|P ag e
Stages of IoT Solutions Architecture
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.
9|P ag e
3.1.8. Difference Between IoT Devices and Computers
we will discuss the overview of the Internet of Things and Computers and mainly will focus on
the difference between IoT devices and compters. Let’s discuss it one by one.
Internet of Things (IoT):
The Internet of Things (IoT) is the network of physical objects/devices like vehicles, buildings,
cars, and other items embedded with electronics, software, sensors, and network connectivity
that enables these objects to collect and exchange data. IoT devices have made human life easier.
The IoT devices like smart homes, smart cars have made the life of humans very comfortable.
IoT devices are now being a part of our day-to-day life.
Computers:
A computer is a hardware device embedded with software in it. The computer does most of the
work like calculations, gaming, web browsers, word processors, e-mails, etc. The main function
of a computer is to compute the functions, to run the programs. It takes input from the computer
and then computes/processes it and generates the output.
Function of Computer
10 | P a g e
3.2. Overview of IoT Vs Computers
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.
To get started with IoT device discovery in your network, all you need is a security device
connected to Juniper ATP Cloud.
11 | P a g e
IoT Device Discovery and Policy Enforcement Topology
As shown in the topology, the network includes some IoT devices connected to an SRX Series
device through wireless access point (AP). The security device is connected to the Juniper Cloud
ATP server, and to a host device.
The security device collects IoT device metadata and streams the relevant information to the
Juniper ATP Cloud. To enable streaming of IoT metadata, you'll need to create security metadata
streaming policies and attach these policies to security policies. Streaming of the IoT device
traffic pauses automatically when Juniper Cloud server has sufficient details to classify the IoT
device.
Juniper ATP cloud discovers and classifies IoT devices. Using the inventory of discovered IoT
devices, you'll create threat feeds in the form of dynamic address groups. Once the security
device downloads dynamic address groups, you can use the dynamic address groups to create
and enforce security policies for the IoT traffic.
Requirements
• SRX Series device or NFX Series device
• Junos OS Release 22.1R1 or later
• Juniper Advanced Threat Prevention Cloud Account. We've verified and tested the
configuration using a vSRX instance with Junos OS Release 22.1R1.
12 | P a g e
o Change the default password to something complex with 16 characters or more if
feasible.
o Make sure no management interface is accessed over an unencrypted channel
(e.g. use HTTPS rather than HTTP and disable the latter).
o For Raspberry Pi Devices:
▪ Make sudo require a password.
▪ Modify the sshd configuration to allow only specific users for SSH access.
▪ Use key-based authentication as an alternative to a password login.
o For printers, disable any unnecessary services. Disable the following where
possible, as they are commonly visible without a username or password:
• Internal storage or job forwarding
• Job logs
• Print queue
• Device management logs
2. Software updates
1. Keep the device software updated with the latest security patches and firmware.
• Some patches can revert or change passwords.
3. Services
1. Disable all unused services, such as telnet, ssh, FTP/TFTP, MySQL, email, web
proxy, SLP/Device Announcement Agent, WS-Discovery/XML Services, Web
Services Print, WINS, LLMNR, IPX/SPX, DLC/LLC, Multicast IPv4, File
Access Settings (JPL Disk Access, SNMP Disk Access, etc.).
2. For printers:
• Automatically delete data after the printing process is complete. Options
can be set for how long data can be resident on the printer – set to lowest
time available.
• Confirm deletion of data upon job completion.
• Disable local use of printer memory if possible.
4. Network
1. IoT devices must use a non-publicly-routable IP address wherever possible.
Exceptions must be approved by the Office of the Chief Information Security
Officer (CISO).
13 | P a g e
2. If possible, use a firewall or similar means of restricting access to the IoT device
management services to only the IP address ranges needed. For off-campus
access, the campus VPN range should be included rather than any external IP
addresses.
3. For Raspberry Pi Devices:
• Install and configure fail2ban.
• Install virus protection.
5. Logging
1. Enable logging of IoT device access and configuration changes. Have the logs
sent to an external device.
2. Monitor logs for unusual behavior.
6. Redundancy and backups
1. If the device has a critical function, consider having a backup configured or
purchasing a second device.
2. Regularly back up the device’s configuration, or keep track of its configuration on
an external system.
3. Check with the device’s vendor for security bulletins or configuration.
4. Consider the types of data your device stores or processes and ensure
unauthorized individuals can’t access that data.
3.4.ComponentsofIoTSystem
What are the major components of Internet of Things?
14 | P a g e
layer. The latest techniques in semiconductor technology are capable of producing micro smart
sensors for various applications.
Common sensors are:
• Temperature sensors and thermostats
• Pressure sensors
• Humidity / Moisture level
• Light intensity detectors
• Moisture sensors
• Proximity detection
• RFID tags
How are the devices connected?
Most modern smart devices and sensors can be connected to low-power wireless networks like
Wi-Fi, ZigBee, Bluetooth, Z-wave, LoRAWAN, etc. Each of these wireless technologies has its
pros and cons in terms of power, data transfer rate, and overall efficiency.
Developments in low-power low cost wireless transmitting devices are promising in the
area of IoT due to their long battery life and efficiency. Many companies have adopted the latest
protocols like 6LoWPAN- IPv6 over Low Power Wireless Personal Area Networks to implement
energy-efficient data transmission for IoT networks. LoWPAN uses reduced transmission time
(typically short time pulses) and thus saves energy.
2. Gateway
IoT Gateway manages the bidirectional data traffic between different networks and
protocols. Another function of the gateway is to translate different network protocols and make
sure interoperability of the connected devices and sensors.
15 | P a g e
Gateways can be configured to perform pre-processing of the collected data from thousands of
sensors locally before transmitting it to the next stage. In some scenarios, it would be necessary
due to the compatibility of the TCP/IP protocol.
IoT gateway offers a certain level of security for the network and transmitted data with higher -
order encryption techniques. It acts as a middle layer between devices and the cloud to protect
the system from malicious attacks and unauthorized access.
3. Cloud
The Internet of Things creates massive data from devices, applications, and users, which
has to be managed in an efficient way. IoT cloud offers tools to collect, process, manage and
store huge amounts of data in real time. Industries and services can easily access these data
remotely and make critical decisions when necessary.
Cloud system integrates billions of devices, sensors, gateways, protocols, and data storage and
provides predictive analytics. Companies use these analytics data to improve products and
services, preventive measures for certain steps, and build their new business model accurately.
4. Analytics
Analytics is the process of converting analog data from billions of smart devices and
sensors into useful insights which can be interpreted and used for detailed analysis. Smart
analytics solutions are inevitable for IoT systems for the management and improvement of the
entire system.
One of the major advantages of an efficient IoT system is real-time smart analytics which helps
engineers to find out irregularities in the collected data and act fast to prevent an undesired
16 | P a g e
scenario. Service providers can prepare for further steps if the information is collected
accurately at the right time.
Big enterprises use the massive data collected from IoT devices and utilize the insights for their
future business opportunities. Careful analysis will help organizations to predict trends in the
market and plan ahead for a successful implementation.
Information is very significant in any business model, and predictive analysis ensures success in
the concerned area of the business line.
5. User interface
User interfaces are the visible, tangible part of the IoT system which users can access.
Designers will have to make sure of a well-designed user interface for minimum effort for users
and encourage more interactions.
Modern technology offers much interactive design to ease complex tasks into simple touch panel
controls. Multicolor touch panels have replaced hard switches in our household appliances, and
the trend is increasing for almost every smart home device.
The user interface design has higher significance in today’s competitive market; it often
determines the user whether to choose a particular device or appliance. Users will be interested
in buying new devices or smart gadgets if it is very user-friendly and compatible with common
wireless standards.
17 | P a g e
3.4.2. RealLife Example DepictingWorking of IoT
Here, we will discuss some examples, which states how IoT works in real-life:
i. Say, we have an AC in our room, now the temperature sensor installed in it in the room will be
integrated with a gateway. A gateway’s purpose is to help connect the temperature sensor (inside
the AC) to the Internet by making use of a cloud infrastructure.
ii. A Cloud/server infrastructure has detailed records about each and every device connected to it
such as device id, a status of the device, what time was the device last accessed, number of times
the device has been accessed and much more.
iii. A connection with the cloud then implement by making use of web services such as RESTful.
iv. We in this system, act as end-users and through the mobile app interact with Cloud (and in
turn devices installed in our homes). A request will send to the cloud infrastructure with the
authentication of the device and device information. It requires authentication of the device to
ensure cybersecurity.
v. Once the cloud has authenticated the device, it sends a request to the appropriate sensor
network using gateways.
vi. After receiving the request, the temperature sensor inside the AC will read the current
temperature in the room and will send the response back to the cloud.
vii. Cloud infrastructure will then identify the particular user who has requested the data and will
then push the requested data to the app. So, a user will get the current information about the
temperature in the room, pick up through AC’s temperature sensors directly on his screen.
3.5. Arduino
A decade ago, working around electronics involved knowledge in physics and math, expensive
lab equipment, a laboratory type setup and important of all, love for electronics. But the picture
has changed over the decade or so where the above-mentioned factors became irrelevant to work
around electronics except for the last part: love for electronics. One such product which made
use of the above specified and many other reasons and made electronics be able reach anyone
regardless of their background is ―Arduino‖.
18 | P a g e
3.5.1. Introduction
Arduino is an open-source prototyping platform in electronics based on easy-to-use hardware
and software. Subtly speaking, Arduino is a microcontroller based prototyping board which can
be used in developing digital devices that can read inputs like finger on a button, touch on a
screen, light on a sensor etc. and turning it in to output like switching on an LED, rotating a
motor, playing songs through a speaker etc.
The aim of Arduino is to introduce the world of electronics to people who have small to no
experience in electronics like hobbyists, designers, artists etc.
19 | P a g e
Arduino is based on open source electronics project i.e. all the design specifications, schematics,
software are available openly to all the users. Hence, Arduino boards can bought from vendors as
they are commercially available or else you can make your own board by if you wish i.e. you can
download the schematic from Arduino’s official website, buy all the components as per the
design specification, assemble all the components, and make your own board.
The important feature of the Arduino boards is the standard connectors. Using these connectors,
we can connect the Arduino board to other devices like LEDs or add-on modules called Shields.
The Arduino boards also consists of on board voltage regulator and crystal oscillator. They also
consist of USB to serial adapter using which the Arduino board can be programmed using USB
connection.
In order to program the Arduino board, we need to use IDE provided by Arduino. The Arduino
IDE is based on Processing programming language and supports C and C++.
Arduino boards are available in different sizes, form factors, different no. of I/O pins etc. Some
of the commonly known and frequently used Arduino boards are Arduino UNO, Arduino Mega,
Arduino Nano, Arduino Micro and Arduino Lilypad.
20 | P a g e
There are add-on modules called Arduino Shields which can be used to extend the functionalities
of the Arduino boards. Some of the commonly used shields are Arduino Proto shield, Arduino
WiFi Shield and Arduino Yun Shield.
21 | P a g e
3.5.3.2. Arduino NG, Diecimila, and the Duemilanove (Legacy Versions)
Legacy versions of the Arduino Uno product line consist of the NG, Diecimila, and the
Duemilanove. The important thing to note about legacy boards is that they lack particular feature
of the Arduino Uno. Some key differences:
• The Diecimila and NG use an ATMEGA168 chips (as opposed to the more powerful
ATMEGA328),
• Both the Diecimila and NG have a jumper next to the USB port and require manual selection of
either USB or battery power.
• The Arduino NG requires that you hold the rest button on the board for a few seconds prior to
uploading a program.
22 | P a g e
The LilyPad was designed for wearable and e-textile applications. It is intended to be sewn to
fabric and connected to other sewable components using conductive thread. This board requires
the use of a special FTDI-USB TTL serial programming cable. For more information,
the Arduino LilyPad page is a decent starting point.
(Note that some of the links on this page are affiliate links. This does not change the cost of the
item for you. I reinvest whatever proceeds I receive into making new projects. If you would like
any suggestions for alternative suppliers, please let me know.)
The nice thing about the Arduino board is that it is relatively cheap, plugs straight into a
computer's USB port, and it is dead-simple to setup and use (compared to other development
boards).
Some of the key features of the Arduino Uno include:
An open source design. The advantage of it being open source is that it has a large
community of people using and troubleshooting it. This makes it easy to find someone to help
you debug your projects.
• An easy USB interface . The chip on the board plugs straight into your USB port and registers
on your computer as a virtual serial port. This allows you to interface with it as through it were a
23 | P a g e
serial device. The benefit of this setup is that serial communication is an extremely easy (and
time-tested) protocol, and USB makes connecting it to modern computers really convenient.
• Very convenient power management and built-in voltage regulation. You can connect an
external power source of up to 12v and it will regulate it to both 5v and 3.3v. It also can be
powered directly off of a USB port without any external power.
• An easy-to-find, and dirt cheap, microcontroller "brain." The ATmega328 chip retails for about
$2.88 on Digikey. It has countless number of nice hardware features like timers, PWM pins,
external and internal interrupts, and multiple sleep modes. Check out the official datasheet for
more details.
• A 16mhz clock. This makes it not the speediest microcontroller around, but fast enough for most
applications.
• 32 KB of flash memory for storing your code.
• 13 digital pins and 6 analog pins. These pins allow you to connect external hardware to your
Arduino. These pins are key for extending the computing capability of the Arduino into the real
world. Simply plug your devices and sensors into the sockets that correspond to each of these
pins and you are good to go.
• An ICSP connector for bypassing the USB port and interfacing the Arduino directly as a serial
device. This port is necessary to re-bootload your chip if it corrupts and can no longer talk to
your computer.
• An on-board LED attached to digital pin 13 for fast an easy debugging of code.
• And last, but not least, a button to reset the program on the chip.
The Arduino Programmer is based on the Processing IDE and uses a variation of the C and C++
programming languages.
You can find the most recent version of the Arduino Programmer on this page.
Step 4: Plug It In
24 | P a g e
Connect the Arduino to your computer's USB port.
Please note that although the Arduino plugs into your computer, it is not a true USB device. The
board has a special chip that allows it to show up on your computer as a virtual serial port when
it is plugged into a USB port. This is why it is important to plug the board in. When the board is
not plugged in, the virtual serial port that the Arduino operates upon will not be present (since all
of the information about it lives on Arduino board).
It is also good to know that every single Arduino has a unique virtual serial port address. This
means that every time you plug in a different Arduino board into your computer, you will need to
reconfigure the serial port that is in use.
Step 5: Settings
Before you can start doing anything in the Arduino programmer, you must set the board-type and
serial port.
To set the board, go to the following:
Tools --> Boards
Select the version of board that you are using. Since I have an Arduino Uno plugged in, I
obviously selected "Arduino Uno."
To set the serial port, go to the following:
Tools --> Serial Port
Select the serial port that looks like:
/dev/tty.usbmodem [random numbers]
25 | P a g e
Step 6: Run a Sketch
26 | P a g e
Arduino programs are called sketches. The Arduino programmer comes with a ton of example
sketches preloaded. This is great because even if you have never programmed anything in your
life, you can load one of these sketches and get the Arduino to do something.
To get the LED tied to digital pin 13 to blink on and off, let's load the blink example.
The blink example can be found here:
Files --> Examples --> Basics --> Blink
The blink example basically sets pin D13 as an output and then blinks the test LED on the
Arduino board on and off every second.
Once the blink example is open, it can be installed onto the ATMEGA328 chip by pressing the
upload button, which looks like an arrow pointing to the right.
Notice that the surface mount status LED connected to pin 13 on the Arduino will start to blink.
You can change the rate of the blinking by changing the length of the delay and pressing the
upload button again.
27 | P a g e
The serial monitor allows your computer to connect serially with the Arduino. This is important
because it takes data that your Arduino is receiving from sensors and other devices and displays
it in real-time on your computer. Having this ability is invaluable to debug your code and
understand what number values the chip is actually receiving.
For instance, connect center sweep (middle pin) of a potentiometer to A0, and the outer pins,
respectively, to 5v and ground. Next upload the sketch shown below:
File --> Examples --> 1.Basics --> AnalogReadSerial
28 | P a g e
Click the button to engage the serial monitor which looks like a magnifying glass. You can now
see the numbers being read by the analog pin in the serial monitor. When you turn the knob the
numbers will increase and decrease.
The numbers will be between the range of 0 and 1023. The reason for this is that the analog pin
is converting a voltage between 0 and 5V to a discreet number.
Step 8: Digital In
The Arduino has two different types of input pins, those being analog and digital.
To begin with, lets look at the digital input pins.
Digital input pins only have two possible states, which are on or off. These two on and off states
are also referred to as:
• HIGH or LOW
• 1 or 0
• 5V or 0V.
This input is commonly used to sense the presence of voltage when a switch is opened or closed.
Digital inputs can also be used as the basis for countless digital communication protocols. By
creating a 5V (HIGH) pulse or 0V (LOW) pulse, you can create a binary signal, the basis of all
computing. This is useful for talking to digital sensors like a PING ultrasonic sensor, or
communicating with other devices.
For a simple example of a digital input in use, connect a switch from digital pin 2 to 5V, a 10K
resistor** from digital pin 2 to ground, and run the following code:
File --> Examples --> 2.Digital --> Button
**The 10K resistor is called a pull-down resistor because it connects the digital pin to ground
when the switch is not pressed. When the switch is pressed, the electrical connections in the
switch has less resistance than the resistor, and the electricity no longer connects to ground.
Instead, electricity flows between 5V and the digital pin. This is because electricity always
chooses the path of least resistance. To learn more about this, visit the Digital Pins page.
29 | P a g e
Step 9: Analog In
Aside from the digital input pins, the Arduino also boasts a number of analog input pins.
Analog input pins take an analog signal and perform a 10-bit analog-to-digital (ADC) conversion
to turn it into a number between 0 and 1023 (4.9mV steps).
This type of input is good for reading resistive sensors. These are basically sensors which
provide resistance to the circuit. They are also good for reading a varying voltage signal between
0 and 5V. This is useful when interfacing with various types of analog circuitry.
If you followed the example in Step 7 for engaging the serial monitor, you have already tried
using an analog input pin.
30 | P a g e
Step 10: Digital Out
A digital out pin can be set to be HIGH (5v) or LOW (0v). This allows you to turn things on and
off.
Aside from turning things on and off (and making LEDs blink), this form of output is convenient
for a number of applications.
Most notably, it allows you to communicate digitally. By turning the pin on and off rapidly, you
are creating binary states (0 and 1), which is recognized by countless other electronic devices as
a binary signal. By using this method, you can communicate using a number of different
protocols.
Digital communication is an advanced topic, but to get a general idea of what can be done, check
out the Interfacing With Hardware page.
If you followed the example in Step 6 for getting an LED to blink, you have already tried using a
digital output pin.
31 | P a g e
Pulse width modulation - or PWM for short - works by rapidly turning the PWM pin high (5V)
and low (0V) to simulate an analog signal. For instance, if you were to blink an LED on and off
rapidly enough (about five milliseconds each), it would seem to average the brightness and only
appear to be receiving half the power. Alternately, if it were to blink on for 1 millisecond and
then blink off for 9 millisecond, the LED would appear to be 1/10 as bright and only be receiving
1/10 the voltage.
PWM is key for a number of applications including making sound, controlling the brightness of
lights, and controlling the speed of motors.
To try out PWM yourself, connect an LED and 220 ohm resistor to digital pin 9, in series to
ground. Run the following example code:
File --> Examples --> 3.Analog --> Fading
Step 12: Write Your Own Code
To write your own code, you will need to learn some basic programming language syntax. In
other words, you have to learn how to properly form the code for the programmer to understand
it. You can think of this kind of like understanding grammar and punctuation. You can write an
entire book without proper grammar and punctuation, but no one will be abler to understand it,
32 | P a g e
even if it is in English.
Some important things to keep in mind when writing your own code:
• An Arduino program is called a sketch.
• All code in an Arduino sketch is processed from top to bottom.
• Arduino sketches are typically broken into five parts.
1. The sketch usually starts with a header that explains what the sketch is doing, and who
wrote it.
2. Next, it usually defines global variables. Often, this is where constant names are given to
the different Arduino pins.
3. After the initial variables are set, the Arduino begins the setup routine. In the setup
function, we set initial conditions of variables when necessary, and run any preliminary
code that we only want to run once. This is where serial communication is initiated, which
is required for running the serial monitor.
4. From the setup function, we go to the loop routine. This is the main routine of the sketch.
This is not only where your main code goes, but it will be executed over and over, so long
as the sketch continues to run.
5. Below the loop routine, there is often other functions listed. These functions are user -
defined and only activated when called in the setup and loop routine. When these functions
are called, the Arduino processes all of the code in the function from top to bottom and
then goes back to the next line in the sketch where it left off when the function was called.
Functions are good because they allow you to run standard routines - over and over -
without having to write the same lines of code over and over. You can simply call upon a
function multiple times, and this will free up memory on the chip because the function
routine is only written once. It also makes code easier to read.
• All of that said, the only two parts of the sketch which are mandatory are the Setup and Loop
routines.
• Code must be written in the Arduino Language, which is roughly based on C.
• Almost all statements written in the Arduino language must end with a ;
• Conditionals (such as if statements and for loops) do not need a;
• Conditionals have their own rules and can be found under "Control Structures" on the Arduino
Language
• Variables are storage compartments for numbers. You can pass values into and out of variables.
Variables must be defined (stated in the code) before they can be used and need to have a data
type associated with it. To learn some of the basic data types, review the Language Page.
33 | P a g e
Step 13: Shields
Shields are expansion apdapter boards that plug in over top of the Arduino Uno and gives it
special functions.
Since the Arduino is open hardware, anyone who has the inclination is free to make an Arduino
shield for whatever task they wish to accomplish. On account of this, there are countless number
of Arduino shields out in the wild. You can find an ever-growing list of Arduino shields in the
Arduino playground. Keep in mind that there will be more shield in existence than you will find
on listed on that page (as always, Google is your friend).
As your projects get more complex, you will want to build your own circuits to interfacewith the
Arduino. While you won't learn electronics overnight, the internet is an unbelievable resource for
electronic knowledge and circuit diagrams.
To get started with electronics, visit the Basic Electronics Instructable.
34 | P a g e
3.6. Arduino ToolChain
Today we’re going to talk about how the Arduino tool chain converts instructions you type into
the text editor into machine language the microcontroller can understand.
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.
The statement here may make total sense to you if you’ve been working with Arduino for a
while. Or, if not, it may not make any sense at all. Either way, just go with me here for a minute.
This is just an illustration which does not require complete understanding of the code.
Int Temp = analogRead(sensorPin);
If (Temp > 500)
{
//more complex instructions go here
}
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.
35 | P a g e
a good way to think about digital signals.
Going from complex instructions to simple ones the microcontroller understands requires several
layers of software that translate the high-level operations into simpler instructions.
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.
36 | P a g e
another way to visualize the Arduino code compilation process.
Another piece of software, called AVR Dude (for Downloader UploaDEr) starts when we press
the upload button. This software sends the .hex file to the ATMega328 on the Arduino board. On
the chip resides the bootloader. This bootloader was put there on purpose by the folks at Arduino
and works with AVR Dude to get the .hex into the flash memory on the chip.
All of this happens very quickly and seamlessly behind the scenes of the Arduino IDE.
37 | P a g e
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.
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.
Sketch: The first new terminology is the Arduino program called ―sketch‖.
3.7.1. Structure
Arduino programs can be divided in three main parts: Structure, Values (variables and
constants), and Functions. 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
38 | P a g e
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.
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.
Void, Boolean , char, Unsigned, Unsigned, char , byte, int, Unsigned, int, word String. Array,
long, long, short , float , double , array, char, String, object
void
39 | P a g e
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.
40 | P a g e
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
41 | P a g e
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
42 | P a g e
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.
43 | P a g e
are:
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.
44 | P a g e
3.7.3. 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
subtraction - Subtracts second operand from the first A - B will give -10
45 | P a g e
multiplication * Multiply both operands A * B will give 200
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 −
Operato Operator Description Example
r name simple
46 | P a g e
Called Logical AND operator. If both the
(A && B) is
and && operands are non-zero then then condition
true
becomes true.
Bitwise Operators
Assume variable A holds 60 and variable B holds 13 then −
Operato Operator Description Example
r name simple
Binary Left Shift Operator. The left operands A << 2 will give
shift left << value is moved left by the number of bits 240 which is 1111
specified by the right operand. 0000
Compound Operators
Assume variable A holds 10 and variable B holds 20 then −
47 | P a g e
Operator Operator Description Example
name simple
Arduino IDE
The Arduino IDE is very simple and easy to use.
Let’s see how to use it with the help of Blink example that comes in the Built-In examples with
the IDE.
1. Open the Arduino IDE from the folder you installed/unzipped it in.
48 | P a g e
2. In the File tab, go to the Examples option. Here you will find a list of all the Built-In
examples that come along with the IDE. You will also see Examples For Any Board in below the
Built-In examples.
Here, we will see the Blink example which blinks the LED on the Arduino board.
3. Once you click on Blink, a new window will open with the sketch (Arduino refers to codes
written in its IDE as sketch) for Blink.
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.
49 | P a g e
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.
50 | P a g e
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.
51 | P a g e
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.
• This is used to open the serial monitor that comes with the Arduino IDE.
Note : You can use any other serial terminal program if you want instead of the Arduino serial
monitor. The serial monitor that comes with Arduino IDE can open only one serial port for
52 | P a g e
communication. If you need to observe multiple ports (multiple Arduino boards connected to the
same computer/laptop), you need to use other programs like Putty, RealTerm, TeraTerm, etc.
9. Now that we have selected the appropriate board, communication port, and the programmer,
we need to upload the Blink sketch on to the board.
We can either verify the sketch before the upload process or skip the verification process.
The IDE does the part of verifying the sketch before uploading as a part of the upload process.
10. Since this is a built-in example sketch, we will not get any warnings or errors upon verifying.
If there are any warnings or errors, they are displayed by the IDE in the black coloured area
below the area for writing code. This area is shown in the image in the next point, highlighted in
red.
11. Now upload the sketch onto the board. When the upload process is done, you will get a done
uploading message. You should be able to see the LED on your Arduino board blinking at 1
second intervals.
53 | P a g e
12. This process needs to be followed for all the sketches that are built-in or created by the user.
Understanding how the Arduino IDE sets up its file directory system can spare you some
confusion when it comes to saving, organizing and opening your Arduino sketches (or sketches
you have downloaded from the internet).
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.
54 | P a g e
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.
55 | P a g e
*/
There's another style for short, single-line comments. These start with
//
and continue to the end of the line. For example, in the line:
1int ledPin = 13; // LED connected to digital pin 13 the message "LED connected to
digital pin 13" is a comment.
Variables
A variable is a place for storing a piece of data. It has a name, a type, and a value. For
example, the line from the Blink sketch above declares a variable with the name ledPin, the
type int, and an initial value of 13. It's being used to indicate which Arduino pin the LED is
connected to. Every time the name ledPin appears in the code, its value will be retrieved. In this
case, the person writing the program could have chosen not to bother creating the ledPin variable
and instead have simply written 13 everywhere they needed to specify a pin number. The
advantage of using a variable is that it's easier to move the LED to a different pin: you only need
to edit the one line that assigns the initial value to the variable. Often, however, the value of a
variable will change while the sketch runs. For example, you could store the value read from
an input into a variable.
Functions
A function (otherwise known as a procedure or sub-routine) is a named piece of code that can
be used from elsewhere in a sketch. For example, here's the definition of the
setup()
56 | P a g e
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
The first line provides information about the function, like its name, "setup". The text before
and after the name specify its return type and parameters: these will be explained later. The
code between the { and } is called the body of the function: what the function does.
You can call a function that's already been defined (either in your sketch or as part of
the Arduino language). For example, the line pinMode(ledPin, OUTPUT); calls the pinMode()
function, passing it two parameters: ledPin and OUTPUT. These parameters are used by the
pinMode() function to decide which pin and mode to set.
The digitalWrite()
functions outputs a value on a pin. For example, the line:
digitalWrite(ledPin, HIGH);
set the ledPin (pin 13) to HIGH, or 5 volts. Writing a LOW to pin connects it to ground, or 0
volts.
The delay() causes the Arduino to wait for the specified number of milliseconds before
continuing on to the next line. There are 1000 milliseconds in a second, so the line:
delay(1000);
creates a delay of one second.
57 | P a g e
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 the file>Sketch book, 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.
58 | P a g e
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
3.9. Arduino Pins
An Introduction to Arduino Uno Pinout
Arduino Uno is based on the ATmega328 by Atmel. The Arduino Uno pinout consists of 14
digital pins, 6 analog inputs, a power jack, USB connection and ICSP header. The versatility of
the pinout provides many different options such as driving motors, LEDs, reading sensors and
more. In this post, we’ll go over the capabilities of the Arduino Uno pinout.
59 | P a g e
Arduino Uno Pinout – Diagram
• VIN Pin - This pin is used to power the Arduino Uno board using an external power
source. The voltage should be within the range mentioned above.
• USB cable - when connected to the computer, provides 5 volts at 500mA.
There is a polarity protection diode connecting between the positive of the barrel jack to the VIN
pin, rated at 1 Ampere.
The power source you use determines the power you have available for your circuit. For
instance, powering the circuit using the USB limits you to 500mA. Take into consideration that
this is also used for powering the MCU, its peripherals, the on-board regulators, and the
60 | P a g e
components connected to it. When powering your circuit through the barrel jack or VIN, the
maximum capacity available is determined by the 5 and 3.3 volts regulators on-board the
Arduino.
• 5v and 3v3
They provide regulated 5 and 3.3v to power external components according to manufacturer
specifications.
• GND
In the Arduino Uno pinout, you can find 5 GND pins, which are all interconnected.
The GND pins are used to close the electrical circuit and provide a common logic reference level
throughout your circuit. Always make sure that all GNDs (of the Arduino, peripherals and
components) are connected to one another and have a common ground.
61 | P a g e
• Pins 0-13 of the Arduino Uno serve as digital input/output pins.
• Pin 13 of the Arduino Uno is connected to the built-in LED.
On the Arduino, When the digital pins are configured as output, they are set to 0 or 5 volts.
When the digital pins are configured as input, the voltage is supplied from an external device.
This voltage can vary between 0-5 volts which is converted into digital representation (0 or 1).
To determine this, there are 2 thresholds:
When connecting a component to a digital pin, make sure that the logic levels match. If the
voltage is in between the thresholds, the returning value will be undefined.
What is PWM?
In general, Pulse Width Modulation (PWM) is a modulation technique used to encode
a message into a pulsing signal. A PWM is comprised of two key components:
frequency and duty cycle. The PWM frequency dictates how long it takes to complete a single
cycle (period) and how quickly the signal fluctuates from high to low. The duty cycle determines
how long a signal stays high out of the total period. Duty cycle is represented in percentage.
In Arduino, the PWM enabled pins produce a constant frequency of ~ 500Hz, while the duty
cycle changes according to the parameters set by the user. See the following illustration:
62 | P a g e
PWM signals are used for speed control of DC motors, dimming LEDs and more.
Communication Protocols
Serial (TTL) - Digital pins 0 and 1 are the serial pins of the Arduino Uno.
They are used by the onboard USB module.
63 | P a g e
well. This allows the user to connect multiple serial-enabled devices and leave the main serial
port available for the USB.
Software serial and hardware serial - Most microcontrollers have hardware designed to
communicate with other serial devices. Software serial ports use a pin-change interrupt system to
communicate. There is a built-in library for Software Serial communication. Software serial is
used by the processor to simulate extra serial ports. The only drawback with software serial is
that it requires more processing and cannot support the same high speeds as hardware serial.
SPI - SS/SCK/MISO/MOSI pins are the dedicated pins for SPI communication. They can be
found on digital pins 10-13 of the Arduino Uno and on the ICSP headers.
What is SPI?
Serial Peripheral Interface (SPI) is a serial data protocol used by microcontrollers to
communicate with one or more external devices in a bus like connection. The SPI can also be
used to connect 2 microcontrollers. On the SPI bus, there is always one device that is denoted as
a Master device and all the rest as Slaves. In most cases, the microcontroller is the Master device.
The SS (Slave Select) pin determines which device the Master is currently communicating with.
SPI enabled devices always have the following pins:
• MISO (Master In Slave Out) - A line for sending data to the Master device
• MOSI (Master Out Slave In) – The Master line for sending data to peripheral devices
• SCK (Serial Clock) - A clock signal generated by the Master device to synchronize data
transmission.
I2C - SCL/SDA pins are the dedicated pins for I2C communication. On the Arduino Uno they
are found on Analog pins A4 and A5.
What is I2C?
I2C is a communication protocol commonly referred to as the ―I2C bus‖. The I2C protocol was
designed to enable communication between components on a single circuit board. With I2C there
are 2 wires referred to as SCL and SDA.
• SCL is the clock line which is designed to synchronize data transfers.
• SDA is the line used to transmit data.
Each device on the I2C bus has a unique address, up to 255 devices can be connected on the
same bus.
Interrupt - INT0 and INT1. Arduino Uno has two external interrupt pins.
64 | P a g e
External Interrupt - An external interrupt is a system interrupt that occurs when outside
interference is present. Interference can come from the user or other hardware devices in the
network. Common uses for these interrupts in Arduino are reading the frequency a square wave
generated by encoders or waking up the processor upon an external event.
Arduino has two forms of interrupt:
• External
• Pin Change
There are two external interrupt pins on the ATmega168/328 called INT0 and INT1. both INT0
and INT1 are mapped to pins 2 and 3. In contrast, Pin Change interrupts can be activated on any
of the pins.
Output pins
An output pin provides VDD or 0 V, by making a connection to VDD or ground via a
transistor. You set its state to HIGH (for VDD ) or LOW (for 0 V) using the digitalWrite()
function. A (simplified) schematic of an output pin is shown below. You might notice that it
looks a bit like a CMOS inverter (or rather, two).
The
transistors in the output pin have non-negligible on resistance, so aren’t suitable for driving
large loads. When talking about this resistance in relation to an output pin, we call it the output
65 | P a g e
resistance of the pin—in other words, the resistance ―seen‖ by a device connected to the pin.
Since this resistance might depend on the state of the pin (HIGH or LOW), it actually has two
output resistances. You’ll measure both in prelab 2b.
Input pins
An input pin reads the voltage on the pin as if it were a voltmeter, and returns either HIGH (1) in
software if the voltage is close to VDD , or LOW (0) if it is close to 0 V. An input pin can be
read using the digitalRead() function.
The value returned by digitalRead() is unpredictable (i.e., could be either HIGH or LOW)
when the input voltage is not close to either VDD or 0 V. The precise meaning of ―close‖
varies between microcontrollers, but for the Adafruit Metro Mini1 in our circuit, the input pin
voltage needs to be at least 0.6VDD to qualify as HIGH, and at most 0.3VDD to qualify as
LOW.
66 | P a g e
This means that it takes very little current to switch the input pin from one state to another. This
makes the pins useful for such tasks as implementing a capacitive touch sensor or reading an
LED as a photodiode.
Pins configured as pinMode(pin, INPUT) with nothing connected to them, or with wires
connected to them that are not connected to other circuits, report seemingly random changes in
pin state, picking up electrical noise from the environment, or capacitively coupling the state of a
nearby pin.
Pull-up Resistors
Pull-up resistors are often useful to steer an input pin to a known state if no input is present. This
can be done by adding a pull-up resistor (to +5V), or a pull-down resistor (resistor to ground) on
the input. A 10K resistor is a good value for a pull-up or pull-down resistor.
Using Built-in Pull-up Resistor with Pins Configured as Input
There are 20,000 pull-up resistors built into the Atmega chip that can be accessed from software.
These built-in pull-up resistors are accessed by setting the pinMode() as INPUT_PULLUP. This
effectively inverts the behavior of the INPUT mode, where HIGH means the sensor is OFF and
LOW means the sensor is ON. The value of this pull-up depends on the microcontroller used. On
most AVR-based boards, the value is guaranteed to be between 20kΩ and 50kΩ. On the Arduino
Due, it is between 50kΩ and 150kΩ. For the exact value, consult the datasheet of the
microcontroller on your board.
When connecting a sensor to a pin configured with INPUT_PULLUP, the other end should be
connected to the ground. In case of a simple switch, this causes the pin to read HIGH when the
switch is open and LOW when the switch is pressed. The pull-up resistors provide enough
current to light an LED dimly connected to a pin configured as an input. If LEDs in a project
seem to be working, but very dimly, this is likely what is going on.
Same registers (internal chip memory locations) that control whether a pin is HIGH or LOW
control the pull-up resistors. Consequently, a pin that is configured to have pull-up resistors
turned on when the pin is in INPUTmode, will have the pin configured as HIGH if the pin is then
switched to an OUTPUT mode with pinMode(). This works in the other direction as well, and an
output pin that is left in a HIGH state will have the pull-up resistor set if switched to an input
with pinMode().
Example
pinMode(3,INPUT) ; // set pin to input without using built in pull up resistor
pinMode(5,INPUT_PULLUP) ; // set pin to input using built in pull up resistor
Pins Configured as OUTPUT
Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. This means
that they can provide a substantial amount of current to other circuits. Atmega pins can source
(provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current
to other devices/circuits. This is enough current to brightly light up an LED (do not forget the
series resistor), or run many sensors but not enough current to run relays, solenoids, or motors.
67 | P a g e
Attempting to run high current devices from the output pins, can damage or destroy the output
transistors in the pin, or damage the entire Atmega chip. Often, this results in a "dead" pin in the
microcontroller but the remaining chips still function adequately. For this reason, it is a good
idea to connect the OUTPUT pins to other devices through 470Ω or 1k resistors, unless
maximum current drawn from the pins is required for a particular application.
pinMode() Function
The pinMode() function is used to configure a specific pin to behave either as an input or an
output. It is possible to enable the internal pull-up resistors with the mode INPUT_PULLUP.
Additionally, the INPUT mode explicitly disables the internal pull-ups.
pinMode() Function Syntax
Void setup ()
{
pinMode (pin , mode);
}
• pin − the number of the pin whose mode you wish to set
• mode − INPUT, OUTPUT, or INPUT_PULLUP.
Example
int button = 5 ; // button connected to pin 5
int LED = 6; // LED connected to pin 6
void setup () {
pinMode(button , INPUT_PULLUP);
// set the digital pin as input with pull-up resistor
pinMode(button , OUTPUT); // set the digital pin as output
}
void setup () {
If (digitalRead(button ) == LOW) // if button pressed {
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
}
digitalWrite() Function
The digitalWrite() function is used to write a HIGH or a LOW value to a digital pin. If the pin
has been configured as an OUTPUT with pinMode(), its voltage will be set to the corresponding
value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V (ground) for LOW. If the pin is configured as
an INPUT, digitalWrite() will enable (HIGH) or disable (LOW) the internal pullup on the input
68 | P a g e
pin. It is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up
resistor.
If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when calling
digitalWrite(HIGH), the LED may appear dim. Without explicitly setting pinMode(),
digitalWrite() will have enabled the internal pull-up resistor, which acts like a large current-
limiting resistor.
digitalWrite() Function Syntax
Void loop()
{
digitalWrite (pin ,value);
}
• pin − the number of the pin whose mode you wish to set
• value − HIGH, or LOW.
Example
int LED = 6; // LED connected to pin 6
void setup ()
{
pinMode(LED, OUTPUT); // set the digital pin as output
}
void setup ()
{
digitalWrite(LED,HIGH); // turn on led
delay(500); // delay for 500 ms
digitalWrite(LED,LOW); // turn off led
delay(500); // delay for 500 ms
}
analogRead( ) function
Arduino is able to detect whether there is a voltage applied to one of its pins and report it through
the digitalRead() function. There is a difference between an on/off sensor (which detects the
presence of an object) and an analog sensor, whose value continuously changes. In order to read
this type of sensor, we need a different type of pin.
In the lower-right part of the Arduino board, you will see six pins marked ―Analog In‖. These
special pins not only tell whether there is a voltage applied to them, but also its value. By using
the analogRead() function, we can read the voltage applied to one of the pins.
This function returns a number between 0 and 1023, which represents voltages between 0 and 5
volts. For example, if there is a voltage of 2.5 V applied to pin number 0, analogRead(0) returns
512.
analogRead() function Syntax
69 | P a g e
analogRead(pin);
• pin − the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on
the Mini and Nano, 0 to 15 on the Mega)
Example
int analogPin = 3;//potentiometer wiper (middle terminal)
// connected to analog pin 3
int val = 0; // variable to store the value read
void setup()
{
Serial.begin(9600); // setup serial
}
void loop()
{
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
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.
70 | P a g e
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.
71 | P a g e
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
72 | P a g e
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.
73 | P a g e
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
74 | P a g e
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 board can work with the logic level of 3.3V or 5V.
75 | P a g e
o We can establish a connection to the Arduino project by touching the shield.
3.12. Integration of Sensors and Actuators with Arduino
Sensors
A better term for a sensor is a transducer. A transducer is any physical device that converts one
form of energy into another. So, in the case of a sensor, the transducer converts some physical
phenomenon into an electrical impulse that determines the reading. A microphone is a sensor
that takes vibrational energy (sound waves), and converts it to electrical energy in a useful way
for other components in the system to correlate back to the original sound.
Actuators
Another type of transducer that you will encounter in many IoT systems is an actuator. In simple
terms, an actuator operates in the reverse direction of a sensor. It takes an electrical input and
76 | P a g e
turns it into physical action. For instance, an electric motor, a hydraulic system, and a pneumatic
system are all different types of actuators.
Controller
In a typical IoT system, a sensor may collect information and route to a control center. There,
previously defined logic dictates the decision. As a result, a corresponding command controls
an actuator in response to that sensed input. Thus, sensors and actuators in IoT work together
from opposite ends. Later, we will discuss where the control center resides in the greater IoT
system.
77 | P a g e
6. Monitor and Debug:
Open the Arduino Serial Monitor (Tools -> Serial Monitor) to view sensor
readings and debugyour code.
Adjust the code as necessary to achieve the desired behavior.
7. Power Considerations:
Ensure that your power supply can handle the power requirements of your sensors
and actuators.Some components may require an external power supply.
78 | P a g e