Unit 4 Iot
Unit 4 Iot
Unit 4 Iot
UNIT-4
Voltage Regulator
The function of the voltage regulator is to control the voltage given
to the Arduino board and stabilize the DC voltages used by the
processor and other elements.
Crystal Oscillator
The crystal oscillator helps Arduino in dealing with time issues.
How does Arduino calculate time? The answer is, by using the
crystal oscillator. The number printed on top of the Arduino crystal
is 16.000H9H. It tells us that the frequency is 16,000,000 Hertz or
16 MHz.
Arduino Reset
You can reset your Arduino board, i.e., start your program from the
beginning. You can reset the UNO board in two ways. First, by
using the reset button (17) on the board. Second, you can connect an
external reset button to the Arduino pin labelled RESET (5).
Analog pins
The Arduino UNO board has six analog input pins A0 through A5.
These pins can read the signal from an analog sensor like the
humidity sensor or temperature sensor and convert it into a digital
value that can be read by the microprocessor.
Main microcontroller
Each Arduino board has its own microcontroller (11). You can
assume it as the brain of your board. The main IC (integrated
circuit) on the Arduino is slightly different from board to board. The
microcontrollers are usually of the ATMEL Company. You must
know what IC your board has before loading up a new program
from the Arduino IDE. This information is available on the top of
the IC.
ICSP pin
Mostly, ICSP (12) is an AVR, a tiny programming header for the
Arduino consisting of MOSI, MISO, SCK, RESET, VCC, and
GND. It is often referred to as an SPI (Serial Peripheral Interface),
which could be considered as an "expansion" of the output.
Actually, you are slaving the output device to the master of the SPI
bus.
Power LED indicator
This LED should light up when you plug your Arduino into a power
source to indicate that your board is powered up correctly. If this
light does not turn on, then there is something wrong with the
connection.
TX and RX LEDs
On your board, you will find two labels: TX (transmit) and RX
(receive). They appear in two places on the Arduino UNO board.
First, at the digital pins 0 and 1, to indicate the pins responsible for
serial communication. Second, the TX and RX led (13). The TX led
flashes with different speed while sending the serial data. The speed
of flashing depends on the baud rate used by the board. RX flashes
during the receiving process.
Digital I/O
The Arduino UNO board has 14 digital I/O pins (15) (of which 6
provide PWM (Pulse Width Modulation) output. These pins can be
configured to work as input digital pins to read logic values (0 or 1)
or as digital output pins to drive different modules like LEDs,
relays, etc. The pins labeled “~” can be used to generate PWM.
AREF
AREF stands for Analog Reference. It is sometimes, used to set an
external reference voltage (between 0 and 5 Volts) as the upper limit
for the analog input pins.
Arduino IDE:=>
Here we will learn in easy steps, how to set up the Arduino IDE on our computer
and prepare the board to receive the program via USB cable.
Step 1 − First you must have your Arduino board (you can choose your favorite
board) and a USB cable. In case you use Arduino UNO, Arduino Duemilanove,
Nano, Arduino Mega 2560, or Diecimila, you will need a standard USB cable (A
plug to B plug), the kind you would connect to a USB printer.
You can get different versions of Arduino IDE from the Download page on the
Arduino Official website. You must select your software, which is compatible with
your operating system (Windows, IOS, or Linux). After your file download is
complete, unzip the file.
The Arduino Uno, Mega, Duemilanove and Arduino Nano automatically draw
power from either, the USB connection to the computer or an external power supply.
If you are using an Arduino Diecimila, you have to make sure that the board is
configured to draw power from the USB connection. The power source is selected
with a jumper, a small piece of plastic that fits onto two of the three pins between
the USB and power jacks. Check that it is on the two pins closest to the USB port.
Connect the Arduino board to your computer using the USB cable. The green power
LED (labeled PWR) should glow.
Step 4 − Launch Arduino IDE.
After your Arduino IDE software is downloaded, you need to unzip the
folder. Inside the folder, you can find the application icon with an infinity
label (application.exe). Double-click the icon to start the IDE.
Here, we are selecting just one of the examples with the name Blink. It
turns the LED on and off with some time delay. You can select any other
example from the list.
To avoid any error while uploading your program to the board, you must
select the correct Arduino board name, which matches with the board
connected to your computer.
Go to Tools → Board and select your board.
Here, we have selected Arduino Uno board, but you must select the
name matching the board that you are using.
Select the serial device of the Arduino board. Go to Tools → Serial Port
menu. This is likely to be COM3 or higher (COM1 and COM2 are usually
reserved for hardware serial ports). To find out, you can disconnect your
Arduino board and re-open the menu, the entry that disappears should be
of the Arduino board. Reconnect the board and select that serial port.
Before explaining how we can upload our program to the board, we must
demonstrate the function of each symbol appearing in the Arduino IDE
toolbar.
A − Used to check if there is any compilation error.
B − Used to upload a program to the Arduino board.
C − Shortcut used to create a new sketch.
D − Used to directly open one of the example sketch.
E − Used to save your sketch.
F − Serial monitor used to receive serial data from the board and send
the serial data to theboard.
Now, simply click the "Upload" button in the environment. Wait a few
seconds; you will see the RX and TX LEDs on the board, flashing. If the
upload is successful, the message "Done uploading" will appear in the
status bar.
Arduino Coding:=>
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.
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 − -
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.
Unsigned
void Boolean char byte int Unsigned int word
char
Variable Scope:=>
Variables in C programming language, which Arduino uses, have a property called scope. A
scope is a region of the program and there are three places where variables can be declared. They
are −
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 −
Void setup () {
Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}
Global Variables
Global variables are defined outside of all 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.
Void setup () {
Void loop () {
int x , y ;
int z ; Local variable declaration
x = 0;
y = 0; actual initialization
z = 10;
}
Operator:=>
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
If statement
It takes an expression in parenthesis and a statement or block of statements. If
1
the expression is true then the statement or block of statements gets executed
otherwise these statements are skipped.
If …else statement
2 An if statement can be followed by an optional else statement, which executes
when the expression is false.
5 Conditional Operator ? :
The conditional operator ? : is the only ternary operator in C.
Arduino – Loops:=>
while loop
while loops will loop continuously, and infinitely, until the expression inside
1
the parenthesis, () becomes false. Something must change the tested variable,
or the while loop will never exit.
do…while loop
The do…while loop is similar to the while loop. In the while loop, the loop-
2
continuation condition is tested at the beginning of the loop before performed
the body of the loop.
for loop
A for loop executes statements a predetermined number of times. The control
3
expression for the loop is initialized, tested and manipulated entirely within
the for loop parentheses.
Nested Loop
4 C language allows you to use one loop inside another loop. The following
example illustrates the concept.
Infinite loop
5
It is the loop having no terminating condition, so the loop becomes infinite.
Arduino – Functions:=>
There are two required functions in an Arduino sketch or a program i.e. setup () and loop().
Other functions must be created outside the brackets of these two functions.
Strings are used to store text. They can be used to display text on an LCD or in the Arduino IDE
Serial Monitor window. Strings are also useful for storing the user input. For example, the
characters that a user types on a keypad connected to the Arduino.
Arrays of characters, which are the same as the strings used in C programming.
The Arduino String, which lets us use a string object in a sketch.
This example will show how to make a string and print it to the serial monitor window.
Example
void setup() {
char my_str[6]; // an array big enough for a 5 character string
Serial.begin(9600);
my_str[0] = 'H'; // the string consists of 5 characters
my_str[1] = 'e';
my_str[2] = 'l';
my_str[3] = 'l';
my_str[4] = 'o';
my_str[5] = 0; // 6th array element is a null terminator
Serial.println(my_str);
}
void loop() {
This same example can be written in a more convenient way as shown below −
Example
void setup() {
char my_str[] = "Hello";
Serial.begin(9600);
Serial.println(my_str);
}
void loop() {
}
Arduino - String Object:=>
An object is a construct that contains both data and functions. A String object can be created just
like a variable and assigned a value or string. The String object contains functions (which are
called "methods" in object oriented programming (OOP)) which operate on the string data
contained in the String object.
Example
void setup() {
String my_str = "This is my string.";
Serial.begin(9600);
void loop() {
Result
This is my string.
THIS IS MY STRING.
My new string.
My new Arduino sketch.
String length is: 22
Arduino – Time:=>
Arduino provides four different time manipulation functions. They are −
S.No. Function & Description
delay () function
The way the delay() function works is pretty simple. It accepts a single integer
1
(or number) argument. This number represents the time (measured in
milliseconds).
delayMicroseconds () function
The delayMicroseconds() function accepts a single integer (or number)
2
argument. There are a thousand microseconds in a millisecond, and a million
microseconds in a second.
millis () function
3 This function is used to return the number of milliseconds at the time, the
Arduino board begins running the current program.
micros () function
The micros() function returns the number of microseconds from the time, the
4
Arduino board begins running the current program. This number overflows i.e.
goes back to zero after approximately 70 minutes.
Declaring Arrays:=>
Arrays occupy space in memory. To specify the type of the elements and the number of elements
required by an array, use a declaration of the form −
Example
// n is an array of 10 integers
int n[ 10 ] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 } ;
void setup () {
void loop () {
for ( int i = 0; i < 10; ++i ) {
Serial.print (i) ;
Serial.print (‘\n’) ;
}
for ( int j = 0; j < 10; ++j ) // output each array element's value {
Serial.print (n[j]) ;
Serial.print (‘\n’) ;
}
}
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37
Arduino - I/O Functions:=>
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.
Example
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
pin. It is recommended to set the pinMode() to INPUT_PULLUP to enable the internal pull-up
resistor.
Example
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.
void setup() {
Serial.begin(9600); // setup serial
}
void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
The Arduino Math library (math.h) includes a number of useful mathematical functions for
manipulating floating-point numbers.
Library Functions
Given below is the list of functions are defined in the header math.h
Example
The following example shows how to use the most common math.h library functions −
void setup() {
Serial.begin(9600);
Serial.print("cos num = ");
Serial.println (cos (double__x) ); // returns cosine of x
Serial.print("absolute value of num = ");
Serial.println (fabs (double__x) ); // absolute value of a float
Serial.print("floating point modulo = ");
Serial.println (fmod (double__x, double__y)); // floating point modulo
Serial.print("sine of num = ");
Serial.println (sin (double__x) ) ;// returns sine of x
Serial.print("square root of num : ");
Serial.println ( sqrt (double__x) );// returns square root of x
Serial.print("tangent of num : ");
Serial.println ( tan (double__x) ); // returns tangent of x
Serial.print("exponential value of num : ");
Serial.println ( exp (double__x) ); // function returns the exponential value of x.
Serial.print("cos num : ");
Serial.println (atan (double__x) ); // arc tangent of x
Serial.print("tangent of num : ");
Serial.println (atan2 (double__y, double__x) );// arc tangent of y/x
Serial.print("arc tangent of num : ");
Serial.println (log (double__x) ) ; // natural logarithm of x
Serial.print("cos num : ");
Serial.println ( log10 (double__x)); // logarithm of x to base 10.
Serial.print("logarithm of num to base 10 : ");
Serial.println (pow (double__x, double__y) );// x to power of y
Serial.print("power of num : ");
Serial.println (square (double__x)); // square of x
}
void loop() {
Result
cos num = 0.10
absolute value of num = 45.45
floating point modulo =15.25
sine of num = 0.99
square root of num : 6.74
tangent of num : 9.67
exponential value of num : ovf
cos num : 1.55
tangent of num : 0.59
arc tangent of num : 3.82
cos num : 1.66
logarithm of num to base 10 : inf
power of num : 2065.70
LEDs are small, powerful lights that are used in many different applications. To start, we will
work on blinking an LED, the Hello World of microcontrollers. It is as simple as turning a light
on and off. Establishing this important baseline will give you a solid foundation as we work
towards experiments that are more complex.
Components Required
1 × Breadboard
1 × Arduino Uno R3
1 × LED
1 × 330Ω Resistor
2 × Jumper
Procedure
Follow the circuit diagram and hook up the components on the breadboard as shown in the image
given below.
Note − To find out the polarity of an LED, look at it closely. The shorter of the two legs, towards
the flat edge of the bulb indicates the negative terminal.
Components like resistors need to have their terminals bent into 90° angles in order to fit the
breadboard sockets properly. You can also cut the terminals shorter.
Sketch
Open the Arduino IDE software on your computer. Coding in the Arduino language will control
your circuit. Open the new sketch File by clicking New.
Arduino Code
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/
// the setup function runs once when you press reset or power the board
void loop() {
digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Code to Note
pinMode(13, OUTPUT) − Before you can use one of Arduino’s pins, you need to tell Arduino
digitalWrite(13, HIGH) − When you are using a pin as an OUTPUT, you can
Result
You should see your LED turn on and off. If the required output is not seen, make sure you have
assembled the circuit correctly, and verified and uploaded the code to your board.
Arduino Simulator ( Emulator ) :=>
The Arduino simulator is a virtual portrayal of the circuits of Arduino in the real world. We
can create many projects using a simulator without the need for any hardware.
The Simulator helps beginner and professional designers to learn, program, and create their
projects without wasting time on collecting hardware equipments.
There are various advantages of using simulator, which are listed below:
It saves money, because there is no need to buy hardware equipments to make a project.
The task to create and learn Arduino is easy for beginners.
We need not to worry about the damage of board and related equipments.
No messy wire structure required.
It helps students to eliminate their mistakes and errors using simulator.
It supports line to line debugging, and helps to find out the errors easily.
We can learn the code and build projects anywhere with our computer and internet
connection.
We can also share our design with others.
Types of Simulator
There are various simulators available. Some are available for free, while some require a license
to access the simulators.
o Autodesk Tinkercad
o Emulator Arduino Simulator
o Autodesk Eagle
o Proteus Simulator
o Virtronics Arduino Simulator
o ArduinoSim
Autodesk Eagle is an advanced simulator, which is used to design 2D and 3D models of PCB,
modular designs, multi-sheet schematics, real-time synchronization, etc.
Arduino Library:=>
The Library is considered as the advanced feature, which extends the capabilities of the Arduino
IDE. It means that the libraries provide extra functionality to the programming platform of
Arduino.
The libraries in Arduino are written in C or C++ (.cpp). These libraries allow us to manipulate
data and work with the hardware.
To implement any Library in the Arduino IDE, go to the Sketch -> Import Library.
There are several libraries available for download. We can also create our own library.
Standard Libraries:=>
EEPROM:=>
It stands for Electronic Erasable Programmable Read Only Memory. The EEPROM is
associated with the microcontroller present on the AVR or Arduino Boards. The EEPROM
library allows us to read the bytes stored in the memory when the power of the board is off.
The size of EEPROM varies in different boards, such as 1KB or 1024 bytes on the
ATmega328P. It can also be of 4KB or 4096 bytes on the Microcontroller ATmega2560, etc.
#include <EEPROM.h>
For example, EEPROM Read, EEPROM Clear, EEPROM Write, EEPROM Get, EEPROM
Update, EEPROM Put, EEPROM Iteration, etc.
Ethernet Library:=>
The Ethernet library works with the Arduino Ethernet shield and other related devices. The
Ethernet library allows us to connect the Arduino board to the Internet.
The SPI bus acts as an intermediate between the board and the shield.
#include <Ethernet.h>
#include <SPI.h>
Firmata Library:=>
For the programming environment, we can create custom firmware without producing our own
objects and protocols.
It is used to implement the firmware protocol, which communicates with the software on the host
computer.
GSM Library:=>
The GSM library exists on the IDE version 1.0.4 and up.
The GSM library allows us to perform the operations on the Arduino board similar to the GSM
phone, such as internet connection, send and receive messages, and to place voice calls.
#include <GSM.h>
It is a library that permits Arduino to communicate with LCDs, which are based on a compatible
chipset called Hitachi HD44780. Such chipsets are found on most types of text-based LCDs. It
works with either an 8-bit mode or 4-bit mode. Here, the bit mode signifies the data lines in
addition to the enable, rs, and rw control lines (optional).
#include <LiquidCrystal.h>
SD Library:=>
It allows writing to or reading from SD cards. For example, Arduino Ethernet Shield. The file
names include the paths separated by the forward slashes, which are passed to the SD Library.
But, SPI is used for the communication between the SD card and the Arduino.
#include <SPI.h>
#include <SD.h>
The examples are Dump files, List Files, Read Write, etc.
The TFT LCD library is included in the IDE version 1.0.5 and later. It allows the Arduino to
communicate with the TFT LCD screen. It further helps to draw images, shapes, lines, and text
to the screen.
The SD card slot present on the onboard screen can be used by implementing the SD library.
The TFT library for communication depends on the SPI library with the SD card and screen.
WiFi Library:=>
The WiFi library permits Arduino to establish a connection with the internet. It can either be a
server to receive the incoming connections or a client to perform outgoing connections.
The personal encryptions supported by the WiFi library are WPA2 and WEP except for WPA2
Enterprise. Arduino uses the SPI bus to communicate with the WiFi shield.
#include <WiFi.h>
We need to wait for the library to download. The downloading will depend on the connection
speed.
The 'INSTALLED' tag will appear in front of the library that is already installed on our
computer.
If we want to add our own library, we can select the desired folder from our computer. The
particular zip file containing the library can be imported in the Arduino.
It is shown below:
We can also recheck from the option Sketch -> Include library to see that the added libraries
are present or not on the list.
We are not required to unzip the downloaded library. The file will remain in the .zip format.
We can download the 3rd party libraries starting with the Arduino IDE version 1.0.5.
Arduino UNO comes with multiple variants, i.e., Arduino UNO R2, Arduino UNO R3, and
Arduino UNO SMD, although there are some differences among these revisions, but following
are common features
Arduino UNO is a development board based on the AT328P 8-bit RISC microcontroller
developed by Atmel (later Microchip Technology)
Arduino UNO comes with 14 Digital Input/Output pins out of which 6 pins can be used for
PWM i.e., pulse width modulation. It also comes with a built-in LED attached to its PIN 13, for
power, the board comes with USB-B and a Barrel Plug which supports 7 to 12V input voltage.
Power: This board operates on a 5V input voltage powered by USB, or it also comes with a
Power Jack called Barrel Plug, each I/O pin draws a 20 mA current, few pins give 3.3V at the
output while others provide 5V.
Shields are nothing but modules to extend the capabilities of Arduino, these shields are
pluggable to the development boards and sit on top of the Arduino.
There are dozens of shields available, here are the few ones with their functionality/uses.
Arduino Ethernet Shield: This shield allows you to enable Wi-Fi, GPS, Ethernet, etc., it’s a good
option for IoT-based projects.
Arduino Display Shield: This shield allows you to connect the LCDs with the Arduino board,
these displays include TFT, touchscreen displays, and many more. For creating beautiful user
interfaces.
Camera Shield: The camera shield allows you to enable your Arduino vision.
Motor Driver Shield: If you need to connect motors, for your robots, etc. Motor Driver Shield is
for you.
Joystick Shield: The Joystick shield allows us to connect a Joystick to an Arduino. Helpful for
controllers.
MicroSD Shield: This shield allows us to extend the storage of Arduino, allowing you to connect
a memory card for extra storage
We have already discussed a project of blinking an LED. Here, we will discuss a project of
blinking two LED's.
The concept of blinking two LED's is similar to the blinking of a single LED. As we know, we
can use the resistance of any value, so let's take the resistors of 470 Ohms. The resistors reduce
the amount of current reaching the LED, which saves the LED from being burnt.
We can also use other resistors depending on the circuit limit and requirements.
The long terminal is called Anode (positive charged), and the short terminal is called Cathode
(negative charged).
Components
Here, we will use the digital output pin number 13 and 7. The positive terminal of the red LED is
connected to the PIN 13, and the negative terminal (anode) is connected to the ground.
Similarly, the positive terminal (cathode) of the green LED is connected to PIN 7 and the
negative terminal is connected to the ground.
As mentioned, two resistors each of 470 Ohms, will be connected in series to the two LEDs in
the project.
The structure will represent the pinout diagram of the project. It is shown below:
Sketch
Open the Arduino IDE (Integrated Development Environment) and start with the coding, which
is given below:
void setup ()
pinMode ( 13, OUTPUT); // to set the OUTPUT mode of pin number 13.
void loop ()
We can modify the delay duration according to our choice or as per the requirements.
The sketch will be uploaded to the board after the correct compiling, as shown below:
Click on the Verify button present on the toolbar to compile the code.
The RX and TX LED on the board will light up after the successful uploading of the code.