0% found this document useful (0 votes)
34 views71 pages

Final IOT Manual

Uploaded by

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

Final IOT Manual

Uploaded by

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

Lab Manual

INTRODUCTION TO INTERNET OF
THINGS LAB
AIML 357/AIDS 357

THIRD YEAR
Department of Artificial Intelligence and
Machine Learning and Department of Artificial
Intelligence and Data Science
IOT Lab Manual – Lab 105

Experiment No. 1
Objective: Introduction to Arduino platform, introduction to various
sensors and actuators & its application

Theory:
Arduino is an open-source prototyping platform in electronics based on easy-to-use hardware
and software. 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 Arduino board can be programmed to do anything by simply programming the
microcontroller on board using a set of instructions for which, the Arduino board consists of a
USB plug to communicate with your computer and a bunch of connection sockets that can be
wired to external devices like motors, LEDs etc.

Power (USB / Barrel Jack)


Every Arduino board needs a way to be connected to a power source. The Arduino UNO can
be powered from a USB cable coming from your computer or a wall power supply that is
terminated in a barrel jack. Here, USB connection is labeled (1) and the barrel jack is labeled
(2). USB connection is helps to load code onto your Arduino board. NOTE: The recommended
voltage for most Arduino models is between 6 and 12 Volts.

Pins (5V, 3.3V, GND, Analog, Digital, PWM, AREF)


Pins on Arduino are places where we connect wires to construct a circuit using black plastic
'headers' that allows to plug a wire right into the board. The Arduino has several different kinds
of pins, each of which is labeled on the board and used for different functions.
• GND (3): Short for 'Ground'. There are several GND pins on the Arduino, any of which
can be used to ground your circuit.
2
IOT Lab Manual – Lab 105

• 5V (4) & 3.3V (5): As you might guess, the 5V pin supplies 5 volts of power, and the
3.3V pin supplies 3.3 volts of power.
• Analog (6): The area of pins under the 'Analog In' label (A0 through A5 on the UNO)
are Analog In pins. These pins can read the signal from an analog sensor (like a
temperature sensor) and convert it into a digital value that we can read.
• Digital (7): Across from the analog pins are the digital pins (0 through 13 on the UNO).
These pins can be used for both digital input (like telling if a button is pushed) and
digital output (like powering an LED).
• PWM (8): Notice tilde (~) symbol, next to some digital pins (3, 5, 6, 9, 10, and 11 on
the UNO). These pins act as normal digital pins, but can also be used for something
called Pulse-Width Modulation (PWM).
• AREF (9): Stands for Analog Reference. Most of the time you can leave this pin alone.
It is sometimes used to set an external reference voltage (between 0 and 5 Volts) as the
upper limit for the analog input pins.

Reset Button
the Arduino has a reset button (10). Pushing it will temporarily connect the reset pin to ground
and restart any code that is loaded on the Arduino.
Power LED Indicator
Tiny LED next to word 'ON' (11). This LED lights up whenever we plug Arduino into a power
source. If this light doesn't turn on, there's a good chance something is wrong. Time to re-check
your circuit!
TX RX LEDs
TX is short for transmit, RX is short for receive (used for serial communication).

Main IC
It is the brains of our Arduino. Main IC on Arduino is slightly different from board type, but is
usually from the ATmega line of IC's from the ATMEL company.

Voltage Regulator
Voltage regulator (14) controls amount of voltage that is let into the Arduino board. It will turn
away an extra voltage that might harm the circuit.

Arduino Programming Language


The Arduino Programming Language is basically a framework built on top of C++. It’s not a
real programming language.
A program written in the Arduino Programming Language is called sketch. A sketch is
normally saved with the .ino extension (from Arduino).
The main difference from “normal” C or C++ is that you wrap all your code into 2 main
functions.
One is called setup(), the other is called loop(). The first is called once, when program starts,
the second is repeatedly called while your program is running.
We don’t have a main() function like you are used to in C/C++ as the entry point for a program.
Once you compile your sketch, the IDE will make sure the end result is a correct C++ program
and will basically add the missing glue by pre-processing it.

Types of Arduino Boards


There are many types of Arduino boards available in the market which can be programmed
using the Arduino IDE. The reasons for different types of boards are different power supply
requirements, connectivity options, their applications etc.
3
IOT Lab Manual – Lab 105

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.

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.

Arduino Uno (R3)


The Uno is a huge option for your initial Arduino. It consists of 14-digital I/O pins, where 6-
pins can be used as PWM (pulse width modulation outputs), 6-analog inputs, a reset button, a
power jack, a USB connection and more. It includes everything required to hold up the
microcontroller; simply attach it to a PC with the help of a USB cable and give the supply to
get started with a AC-to-DC adapter or battery.

LilyPad Arduino Board


The Lily Pad Arduino board is a wearable e-textile technology expanded by Leah
"Buechley"and considerately designed by "Leah and SparkFun". Each board was imaginatively
designed with huge connecting pads & a smooth back to let them to be sewn into clothing using

4
IOT Lab Manual – Lab 105

conductive thread. This Arduino also comprises of I/O, power, and also sensor boards which
are built especially for e-textiles. These are even washable!

RedBoard Arduino Board


The RedBoard aAduino board can be programmed using a Mini-B USB cable using the
Arduino IDE. It will work on Windows 8 without having to modify your security settings.It is
more constant due to the USB or FTDI chip we used and also it is entirely flat on the back.
Creating it is very simple to utilize in the project design. Just plug the board, select the menu
option to choose an Arduino UNO and you are ready to upload the program. You can control
the RedBoard over USB cable using the barrel jack.

Arduino Mega (R3) Board


The Arduino Mega is similar to the UNO's big brother. It includes lots of digital I/O pins (from
that, 14-pins can be used as PWM o/ps), 6-analog inputs, a reset button, a power jack, a USB
connection and a reset button. It includes everything required to hold up the microcontroller;
simply attach it to a PC with the help of a USB cable and give the supply to get started with a
AC-to-DC adapter or battery.The huge number of pins make this Arduino board very helpful
for designing the projects that need a bunch of digital i/ps or o/ps like lots buttons.

5
IOT Lab Manual – Lab 105

Arduino Leonardo Board


The first development board of an Arduino is the Leonardo board. This board uses one
microcontroller along with the USB. That means, it can be very simple and cheap also. Because
this board handles USB directly, program libraries are obtainable which let the Arduino board
to follow a keyboard of the computer, mouse, etc.

Introduction to Sensors and Actuators:


Sensors and actuators are two critical components of every closed loop control system. Such a
system is also called a mechatronics system. Mechatronics system consists of a sensing unit, a
controller, and an actuating unit. Sensing unit consist of additional components such as filters,
amplifiers, modulators, and other signal conditioners. Controller accepts information from
sensing unit, makes decisions based on control algorithm, and outputs commands to actuating
unit. Actuating unit consists of an actuator and optionally a power supply and a coupling
mechanism.
6
IOT Lab Manual – Lab 105

What is a Sensors?
A Sensor is a converter that measures a physical quantity and converts it into a signal which
can be read by an observer or by an (today mostly electronic) instrument.

SENSORS
We frequently use different types of sensors in several electrical and electronic applications,
which are classified as chemical, pressure, temperature, position, force, proximity, thermal,
presence, flow, optical, automotive, sound, speed, magnetic, electric, heat, fiber-optic sensors,
analog and digital sensors. A sensor can be defined as an appliance that detects changes in
physical or electrical or other quantities and by this means, generally, produces an electrical or
optical signal output as an acknowledgement of the change in that specific quantity.

What is an Actuator:
An Actuator is a type of motor for moving or controlling a mechanism or system. It is operated
by a source of energy, typically electric current, hydraulic fluid pressure, or pneumatic
pressure, and converts that energy into motion. An actuator is the mechanism by which a
control system acts upon an environment.
Actuators are devices which drive a machine (robot) including its grippers. Muscles of a human
arm and hand. While human arm provides motion, hand is used for object manipulation. So,
actuators in robots (machine) provides motion while grippers manipulates objects. An actuator
system comprises of several subsystems, namely,
(i) Power supply; (ii) Power amplifier;
(iii) Servomotor; (iv) Transmission system.

Different Types of Sensors


The following is a list of different types of sensors that are commonly used in various
applications. All these sensors are used for measuring one of the physical properties like
Temperature, Resistance, Capacitance, Conduction, Heat Transfer etc.
1. Temperature Sensor 11. Humidity Sensor
2. Proximity Sensor 12. Position Sensor
3. Accelerometer 13. Magnetic Sensor (Hall Effect
4. IR Sensor (Infrared Sensor) Sensor)
5. Pressure Sensor 14. Microphone (Sound Sensor)
6. Light Sensor 15. Tilt Sensor
7. Ultrasonic Sensor 16. Flow and Level Sensor
8. Smoke, Gas and Alcohol Sensor 17. PIR Sensor
9. Touch Sensor 18. Touch Sensor
10. Color Sensor 19. Strain and Weight Sensor

7
VIPS-TC

ANALOG SENSORS

1. Accelerometers
Analog sensors that detect changes in position, velocity, orientation, shock, vibration, and tilt
by sensing motion are called as accelerometers. These analog accelerometers are again
classified into different types based on the variety of configurations and sensitivities.

These accelerometers are available as analog and digital sensors, based on the output signal. Analog
accelerometer produces a constant variable voltage based on the amount of acceleration applied to the
accelerometer

a. Small board size - Just 28mm X 23mm


b. Simple 5 pin interface (VCC, GND, Xout, Yout, Zout, Self Test)
IOT LAB
| [Document subtitle]
VIPS-TC

c. Needs no external components


d. Easy to mount on General purpose PCB, Breadboards and special PCBs
e. Low Current Consumption: 500 μA
f.Low Voltage Operation: 5V
g. High Sensitivity for small movements
h. Fast Turn On Time
i. Integral Signal Conditioning with Low Pass Filter
j. Robust Design, High Shocks Survivability

2. Light Sensors
Analog sensors that are used for detecting the amount of light striking the sensors are called
as light sensors. These analog light sensors are again classified into various types such as
photo-resistor, Cadmium Sulfide (CdS), and, photocell.

Light dependent resistor (LDR) can be used as analog light sensor which can be used to
switch on and off loads automatically based on the day light incident on the LDR. The
resistance of the LDR increases with decrease in light and decreases with increase in light.

3. Sound Sensors
Analog sensors that are used to sense sound level are called as sound sensors. These analog
sound sensors translate the amplitude of the acoustic volume of the sound into an electrical
voltage for sensing sound level. This process requires somecircuitry, and utilizes
microcontroller along with a microphone for creating an analog output signal.

4. Pressure Sensor
The analog sensors that are used to measure the amount of pressure applied to a sensor are
called as analog pressure sensors. Pressure sensor will produce an analog output signal that is
proportional to the amount of applied pressure. These piezoelectric sensors are one type of
pressure sensors that can produce an analog output voltage signal proportional to the pressure
applied to the piezoelectric sensor.

IOT LAB
| [Document subtitle]
VIPS-TC

5. Analog Temperature sensor


Temperature sensors are widely available as both digital and analog sensors. Typically used
analog temperature sensors are thermistors. There are different types of thermistors
that are used for different applications. Thermistor is a thermally sensitive resistor that is used
for detecting changes in temperature. If the temperature increases, then the electrical
resistance of thermistor increases. Similarly, if temperature decreases, then the resistance
decreases. It is used in various temperature sensor applications.

6. Water Level Sensor

Water Sensor water level sensor is an easy-to-use, cost-effective high level/drop recognition
sensor, which is obtained by having a series of parallel wires exposed traces measured
droplets/water volume to determine the water level. Easy to complete water to analog signal
conversion and output analog values can be directly read Arduino development board to
achieve the level alarm effect.
IOT LAB
| [Document subtitle]
VIPS-TC

DIGITAL SENSORS:

Electronic sensors or electrochemical sensors in which data conversion and data transmission
takes place digitally are called as digital sensors. These digital sensors are replacing analog
sensors as they can overcome the drawbacks of analog sensors. The digital sensor
consists of majorly three components: senor, cable, and transmitter. In digital sensors, the
signal measured is directly converted into digital signal output inside the digital sensor itself.
And this digital signal is transmitted through cable digitally. There are different types of
digital sensors that overcome disadvantages of analog sensors.

1. Digital Temperature and Humidity Sensor

DHT11 and DHT22 digital temperature sensor available for measurement of temperature
and humidity DHT11 sensor includes a resistive-type humidity measurement component, an
NTC temperature measurement component and a high- performance 8-bit microcontroller
inside, and provides calibrated digital signal output. It has high reliability and excellent long-
term stability

DHT22 includes a capacitive sensor wet component and a high-precision temperature


measurement device, and connected with a high-performance 8-bit microcontroller. The
sensor has excellent quality, fast response, strong anti- jamming capability, and high cost.
Standard single-bus interface, system integration quick and easy. Small size, low power
consumption, signal transmission distance up to 20 meters, making it the best choice of all
kinds of applications and even the most demanding applications. DHT22 has higher precision
and can replace the expensive imported SHT10 temperature and humidity sensor.
IOT LAB
| [Document subtitle]
VIPS-TC

2. Ultrasonic Sensor
Ultrasonic sensor distance measuring module is stable, measure the distance accurately. The
sensor with High precision, blind spots (3cm) super close. Its provides a full set of ranging
process

3. IR Sensor (Obstacle sensor)

IR Obstacle Sensor consists of a TSOP as a receiver and IR LED as a transmitter. TSOP as


a receiver provides flexibility of sensing light.The sensor is perfectly suited for Detecting
obstacle within line of sight. Interface with any device compatible with Digital Signal.
▪ Obstacle Avoider or Obstacle sensor for
robots and electronics with range between 3cms to 7cms
▪ 0.1th inch (2.54 mm) with Breadboard
compatiblity
▪ Obstacle sensing LED and Power LED
▪ Arduino, AVR, PIC and other microcontroller Compatible
▪ A compact form on a tiny board

4. Flame sensor)
Flame Detection Sensor Module is sensitive to the flame, but also can ordinary light. Usually
used as a flame Detects a flame or a light source of a wavelength in the range of 760nm
Flame detection distance, lighter flame test can be triggered within 0.8m, if the intensity of
flame is high , the detection distance will be increased.

IOT LAB
| [Document subtitle]
VIPS-TC

5. Gas Sensor

It is a hazardous gas detection apparatus for the family, the environment, suitable for ammonia,
aromatic compounds, Sulphur, benzene vapors, smoke and other gases harmful gas detection,
gas-sensitive element test. Air quality sensor is for detecting a wide range of gases, including
NH3, NOx, alcohol, benzene, smoke and CO2. Ideal for use in office or factory with simple
drive and monitoring circuit.

• Dual signal output (analog output, and TTL


level output)
• TTL output valid signal is low
• Analog output with increasing concentration, the higher the concentration, the
higher the voltage
• Sulphide, benzene, smoke and other harmful gases with high sensitivity
• Has a long life and reliable stability
• Rapid response recovery characteristics

6. Line Tracker Sensor

Line Tracker sensor consists of 3 IR transmitter and IR receiver pairs. This tracker sensor is
typically used for robots in line following task. It can be used for either dark or bright line
following. The tracker sensor have 3 digital outputs to user indicating the existence of the
line. Every sensor is provided with its own LEDs as indication of line detection
IOT LAB
| [Document subtitle]
VIPS-TC

7. PIR Motion sensor

The Passive Infrared Sensor (PIR) sensor module is used for motion detection. It can be used
as motion detector for security systems or robotics. It works on 5V DC and gives TTL output
which can be directly given to microcontroller or to relay through a transistor.It consists of
pyroelectric sensor and Fresnel lens that detects motion by measuring change in the infrared
levels emitted by the objects. It can detect motion up to 20ft. This module is very sensitive
to change in infrared levels subjected by human movement.

• Supply: 5V DC
• Detection range: 6meters
• Output: 3.3V
• Adjustable sensitivity levels (High or
Low)
• Settling time: 60 seconds
• Size: Length 32mm, Width 24mm, Height 26mm

ACTUATORS

1. Relay

Relay provides an electrical connection between two or more points in response to the
application of a control signal. Relays are basically electrically operated switches that come
in many shapes, sizes and power ratings suitable for all types of applications. Relays can
also have single or multiple contacts within a single package

2. DC Motor

A DC motor (Direct Current motor) is the most common type of motor. DC motors
normally have just two leads, one positive and one negative. If you connect these two leads
directly to a battery, the motor will rotate. If you switch the leads, the motor will rotate in
the opposite direction.
IOT LAB
| [Document subtitle]
VIPS-TC

3. Servo Motor

A Servo Motor is a small device that has an output shaft. This shaft can be positioned to
specific angular positions by sending the servo a coded signal. If the coded signal exists on
the input line, the servo will maintain the angular position of the shaft. If the coded signal
changes, the angular position of the shaft changes. In practice, servos are used in radio-
controlled airplanes to position control surfaces like the elevators and rudders. They are
also used in radio-controlled cars, puppets, and of course, robots.

4. Stepper Motor

A Stepper Motor or a step motor is a brushless, synchronous motor, which divides a full
rotation into several steps. Unlike a brushless DC motor, which rotates continuously when
a fixed DC voltage is applied to it, a step motor rotates in discrete step angles.

5. Seven Segment Display

IOT LAB
| [Document subtitle]
VIPS-TC

The seven segments display a very simple device. It is a combination of 8 LEDs (the
decimal point -DP- is the 8th), which can be arranged so that different combinations can be
used to make numerical digits.

6. LCD Display

An LCD is an electronic display module which uses liquid crystal to produce a visible
image. The 16×2 LCD display is a very basic module commonly used in DIYs and circuits.
The 16×2 translates display 16 characters Per line in 2 such lines. In this LCD each
character is displayed in a 5×7 pixel matrix

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 2(A)


Objective: Arduino IDE and Operators in IDE
Arduino Integrated Development Environment - or Arduino Software (IDE) - contains a text
editor for writing code, a message area, a text console, a toolbar with buttons for common
functions and a series of menus. It connects to Arduino hardware to upload programs and
communicate with them.

Writing Sketches
Programs written using Arduino Software (IDE) are called sketches. These sketches are
written in text editor and are saved with file extension. ino. Editor has features for
cutting/pasting and for searching/replacing text. Message area gives feedback while saving
and exporting and also displays errors. Console displays text output by Arduino Software
(IDE), including complete error messages and other information. Bottom right hand corner
of the window displays the configured board and serial port. Toolbar buttons allow you to
verify and upload programs, create, open, and save sketches, and open serial monitor.

NB: Versions of the Arduino Software (IDE) prior to 1.0 saved sketches with the extension
.pde. It is possible to open these files with version 1.0, you will be prompted to save the
sketch with the. ino extension on save.
Verify Checks your code for errors compiling it.

IOT LAB
| [Document subtitle]
VIPS-TC

Upload Compiles your code and uploads it to the configured board. If you are using an
external programmer with your board, you can hold down the "shift" key on your computer
when using this icon. The text will change to "Upload using Programmer"
New Creates a new sketch.
Open Presents a menu of all the sketches in your sketchbook. Clicking one will open it
within the current window overwriting its content.
Note: due to a bug in Java, this menu doesn't scroll; if you need to open a sketch late in the
list, use the File | Sketchbook menu instead.
Save Saves your sketch.
Serial Monitor Opens the serial monitor.
Additional commands are found within the five menus: File, Edit, Sketch, Tools, Help. The
menus are context sensitive, which means only those items relevant to the work currently
being carried out are available.

File
• New Creates a new instance of the editor, with the bare minimum structure of a sketch
already in place.
• Open Allows to load a sketch file browsing through the computer drives and folders.
• Open Recent Provides a short list of the most recent sketches, ready to be opened.

IOT LAB
| [Document subtitle]
VIPS-TC

• Sketchbook Shows the current sketches within the sketchbook folder structure;
clicking on any name opens the corresponding sketch in a new editor instance.
• Examples Any example provided by the Arduino Software (IDE) or library shows up
in this menu item. All the examples are structured in a tree that allows easy access by
topic or library.
• Close Closes the instance of the Arduino Software from which it is clicked.
• Save Saves the sketch with the current name. If the file hasn't been named before, a
name will be provided in a "Save as.." window.
• Save as... Allows to save the current sketch with a different name.
• Page Setup It shows the Page Setup window for printing.
• Print Sends the current sketch to the printer according to the settings defined in Page
Setup.
• Preferences Opens the Preferences window where some settings of the IDE may be
customized, as the language of the IDE interface.
• Quit Closes all IDE windows. The same sketches open when Quit was chosen will be
automatically reopened the next time you start the IDE.

Edit
• Undo/Redo Goes back of one or more steps you did while editing; when you go back,
you may go forward with Redo.
• Cut Removes the selected text from the editor and places it into the clipboard.
• Copy Duplicates the selected text in the editor and places it into the clipboard.
• Copy for Forum Copies the code of your sketch to the clipboard in a form suitable for
posting to the forum, complete with syntax coloring.
• Copy as HTML Copies the code of your sketch to the clipboard as HTML, suitable
for embedding in web pages.
• Paste Puts the contents of the clipboard at the cursor position, in the editor.
• Select All Selects and highlights the whole content of the editor.
• Comment/Uncomment Puts or removes the // comment marker at the beginning of
each selected line.
• Increase/Decrease Indent Adds or subtracts a space at the beginning of each selected
line, moving the text one space on the right or eliminating a space at the beginning.
• Find Opens the Find and Replace window where you can specify text to search inside
the current sketch according to several options.

IOT LAB
| [Document subtitle]
VIPS-TC

• Find Next Highlights the next occurrence - if any - of the string specified as the search
item in the Find window, relative to the cursor position.
• Find Previous Highlights the previous occurrence - if any - of the string specified as
the search item in the Find window relative to the cursor position.

Sketch
• Verify/Compile Checks your sketch for errors compiling it; it will report memory
usage for code and variables in the console area.
• Upload Compiles and loads the binary file onto the configured board through the
configured Port.
• Upload Using Programmer This will overwrite the bootloader on the board; you will
need to use Tools > Burn Bootloader to restore it and be able to Upload to USB serial
port again. However, it allows you to use the full capacity of the Flash memory for
your sketch. Please note that this command will NOT burn the fuses. To do so Tools
-> Burn Bootloader command must be executed.

IOT LAB
| [Document subtitle]
VIPS-TC

• Export Compiled Binary Saves a .hex file that may be kept as archive or sent to the
board using other tools.
• Show Sketch Folder Opens the current sketch folder.
• Include Library Adds a library to your sketch by inserting #include statements at the
start of your code. For more details, see libraries below. Additionally, from this menu
item you can access the Library Manager and import new libraries from .zip files.
• Add File Adds a supplemental file to the sketch (it will be copied from its current
location). The file is saved to the data subfolder of the sketch, which is intended for
assets such as documentation. The contents of the data folder are not compiled, so they
do not become part of the sketch program.

Tools
• Auto Format This formats your code nicely: i.e. indents it so that opening and closing
curly braces line up, and that the statements inside curly braces are indented more.
• Archive Sketch Archives a copy of the current sketch in .zip format. The archive is
placed in the same directory as the sketch.
• Fix Encoding & Reload Fixes possible discrepancies between the editor char map
encoding and other operating systems char maps.
• Serial Monitor Opens the serial monitor window and initiates the exchange of data
with any connected board on the currently selected Port. This usually resets the board,
if the board supports Reset over serial port opening.

IOT LAB
| [Document subtitle]
VIPS-TC

• Board Select the board that you're using. See below for descriptions of the various
boards.
• Port This menu contains all the serial devices (real or virtual) on your machine. It
should automatically refresh every time you open the top-level tools menu.
• Programmer For selecting a hardware programmer when programming a board or
chip and not using the onboard USB-serial connection. Normally you won't need this,
but if you're burning a bootloader to a new microcontroller, you will use this.
• Burn Bootloader The items in this menu allow you to burn a bootloader onto the
microcontroller on an Arduino board. This is not required for normal use of an
Arduino board but is useful if you purchase a new ATmega microcontroller (which
normally come without a bootloader). Ensure that you've selected the correct board
from the Boards menu before burning the bootloader on the target board. This
command also set the right fuses.

Help
Here you find easy access to a number of documents that come with the Arduino Software
(IDE). You have access to Getting Started, Reference, this guide to the IDE and other
documents locally, without an internet connection. The documents are a local copy of the
online ones and may link back to our online website.

IOT LAB
| [Document subtitle]
VIPS-TC

• Find in Reference This is the only interactive function of the Help menu: it directly
selects the relevant page in the local copy of the Reference for the function or command
under the cursor.

Sketchbook
The Arduino Software (IDE) uses the concept of a sketchbook: a standard place to store your
programs (or sketches). The sketches in your sketchbook can be opened from the File >
Sketchbook menu or from the Open button on the toolbar. The first time you run the
Arduino software, it will automatically create a directory for your sketchbook. You can view
or change the location of the sketchbook location from with the Preferences dialog.
Beginning with version 1.0, files are saved with a .ino file extension. Previous versions use
the .pde extension. You may still open .pde named files in version 1.0 and later, the software
will automatically rename the extension to .ino.

Tabs, Multiple Files, and Compilation


Allows you to manage sketches with more than one file (each of which appears in its own
tab). These can be normal Arduino code files (no visible extension), C files (.c extension),
C++ files (.cpp), or header files (.h).

Libraries
Libraries provide extra functionality for use in sketches, e.g. working with hardware or
manipulating data. To use a library in a sketch, select it from the Sketch > Import
Library menu. This will insert one or more #include statements at the top of the sketch and
compile the library with your sketch.

Serial Monitor
This displays serial sent from the Arduino board over USB or serial connector. To send data
to the board, enter text and click on the "send" button or press enter. Choose the baud rate
from the drop-down menu that matches the rate passed to Serial.begin in your sketch.

The types of Operators classified in Arduino are:


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

IOT LAB
| [Document subtitle]
VIPS-TC

Arithmetic Operators

There are six basic operators responsible for performing mathematical operations in Arduino,
which are listed below:
Assignment Operator ( = ): Used to set variable's value. It is quite different from equal symbol
(=) normally used in mathematics.
Addition ( + ): Used for addition of two numbers. For example, P + Q.
Subtraction ( - ): Used to subtract one value from the another. For example, P - Q.
Multiplication ( * ): Used to multiply two numbers. For example, P * Q.
Division ( / ): Used to determine result of one number divided with another. For example, P/Q.
Modulo ( % ): Used to calculate remainder after division of one number by another number.

Code 1: Add two numbers and print their result on serial monitor
int b;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
b = 5 + 2;
Serial.println(b);
}

Result: 7

Code 2: Run the below code to check working of arithmetic operators


int d;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
d = 5 - 2;
Serial.println(d);
d = d + 3;
Serial.println(d);
}

Result: 3

IOT LAB
| [Document subtitle]
VIPS-TC

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

Code 3: Use float datatype and divide operator to write a code.


float b;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
b = 20.0 / 3; // decimal value is used to force the compiler to print decimal value.
Serial.println(b);
}

Code 4: Write a code to verify BODMAS


int c;
void setup ( )
{
Serial.begin( 9600 );
}
void loop ( )
{
c = 2 * 3 / (2 + 1) + 4;
Serial.println(c);
}

Output: 6

Compound Operators
IOT LAB
| [Document subtitle]
VIPS-TC

Compound operators perform two or more calculations at once. Result of right operand is
assigned to left operand. Same condition will apply to all the compound operators, which are
listed below:

Let's consider a variable b.


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

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


• b--

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


• b-=

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


• b*=

For example, b * = 6. It means, b = b * 6.


• b/=

For example, b / = 5. It means, b = b / 5.


• b%=

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

Now, let's use the above operators with two variables, b and c.
o b + = c ( b = b + c)
o b - = c ( b = b - c)
o b * = c ( b = b * c)
o b / = c ( b = b / c)
o b % = c ( b = b % c)

Boolean Operators

The Boolean Operators are NOT (!), Logical AND (& &), and Logical OR (| |).
o Logical AND (& &): The result of the condition is true if both the operands in the condition
are true.
• if (a = = b & & b = = c)

Above statement is true if both conditions are true. If any of conditions is false, statement will
be false.
o Logical OR (| |): Result of condition is true, if either of variables in condition is true.
IOT LAB
| [Document subtitle]
VIPS-TC

• if (a > 0 | | b > 0)

The above statement is true, if either of above condition (a> 0 or b > 0) is true.
o NOT (!): It is used to reverse the logical state of the operand.

• For example, a! = 2.

The NOT operator returns value 1 or TRUE when specified operand is FALSE. It also reverses
the value of the specified expression.

Comparison Operators

The comparison operators are used to compare the value of one variable with the other. The
comparison operators are listed below:
• less than ( < ): The less than operator checks that the value of the left operand is less
than the right operand. The statement is true if the condition is satisfied.

Example: Consider the below code.


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

Output: 3

In above code, if any of two statements is correct, corresponding value of variable will be
printed. Here, only first condition is correct. Hence, value of b will be printed.
• greater than (>): Less than operator checks that value of left side of a statement is
greater than right side. Statement is true if the condition is satisfied. For example, a >
b. If a is greater than b, the condition is true, else false.

IOT LAB
| [Document subtitle]
VIPS-TC

• equal to (= =): It checks the value of two operands. If the values are equal, the condition
is satisfied. For example, a = = b. The above statement is used to check if the value of
a is equal to b or not.
• not equal to (! = ): It checks the value of two specified variables. If the values are not
equal, the condition will be correct and satisfied. For example, a! = b.
• less than or equal to (< =): The less or equal than operator checks that the value of left
side of a statement is less or equal to the value on right side. The statement is true if
either of the condition is satisfied. For example, a < = b. It checks the value of a is less
or equal than b.
• greater than or equal to (> =): The greater or equal than operator checks that the value
of the left side of a statement is greater or equal to the value on the right side of that
statement. The statement is true if the condition is satisfied. For example, a > = b. It
checks the value of a is greater or equal than b. If either of the conditions satisfies, the
statement is true.

Bitwise Operators

The Bitwise operators operate at the binary level. These operators are quite easy to use. There
are various bitwise operators. Some of the popular operators are listed below:
1. bitwise NOT (~): The bitwise NOT operator acts as a complement for reversing the bits.
For example, if b = 1, the NOT operator will make the value of b = 0.
• 0 0 1 1 // Input or operand 1 (decimal value 3)
• 1 1 0 0 // Output (reverses the input bits) decimal value is 12
2. bitwise XOR (^): The output is 0 if both the inputs are same, and it is 1 if the two input
bits are different. For example,
1. 1 0 0 1 // input 1 or operand 1
2. 0 1 0 1 // input 2
3. 1 1 0 0 // Output (resultant - XOR)
3. bitwise OR (|): Output is 0 if both of the inputs in the OR operation are 0. Otherwise, the
output is 1. The two input patterns are of 4 bits. For example,
1. 1 1 0 0 // input 1 or operand 1
2. 0 0 0 1 // input 2
3. 1 1 0 1 // Output ( resultant - OR)
4. bitwise AND (&): Output is 1 if both the inputs in the AND operation are 1. Otherwise,
the output is 0. The two input patterns are of 4 bits. For example,
1. 1 1 0 0 // input 1 or operand 1
2. 0 1 0 1 // input 2
3. 0 1 0 0 // Output ( resultant - AND)

IOT LAB
| [Document subtitle]
VIPS-TC

5. bitwise left shift ( < < ): The left operator is shifted by the number of bits defined by the
right operator.
6. bitwise right shift ( > > ): The right operator is shifted by the number of bits defined by
the left operator.

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 2(B)


Aim: Frequently used functions in Arduino IDE.
Functions allow structuring the programs in segments of code to perform individual tasks. The
typical case for creating a function is when one needs to perform the same action multiple times
in a program.
Standardizing code fragments into functions has several advantages −
• Functions help the programmer stay organized. Often this helps to conceptualize the
program.
• Functions codify one action in one place so that the function only has to be thought
about and debugged once.
• This also reduces chances for errors in modification, if the code needs to be changed.
• Functions make the whole sketch smaller and more compact because sections of code
are reused many times.
• They make it easier to reuse code in other programs by making it modular, and using
functions often makes the code more readable.
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.
The most common syntax to define a function is −

Function Declaration
A function is declared outside any other functions, above or below the loop function.
We can declare the function in two different ways −
The first way is just writing the part of the function called a function prototype above the loop
function, which consists of −
• Function return type
• Function name
• Function argument type, no need to write the argument name
Function prototype must be followed by a semicolon ( ; ).

IOT LAB
| [Document subtitle]
VIPS-TC

The following example shows the demonstration of the function declaration using the first
method.

Arduino IDE offers a wide range of functions and libraries to help you program your Arduino
microcontroller effectively. Here are some frequently used functions along with coding
examples:
1. pinMode(): Configures a pin as INPUT or OUTPUT.
pinMode(ledPin, OUTPUT);
Example: // LED connected to pin 13
const int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH); // Turn on the LED
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn off the LED
delay(1000); // Wait for 1 second
}

2. digitalWrite(): Writes a HIGH or LOW value to a digital pin.


digitalWrite(ledPin, HIGH);
Example: // LED connected to pin 13
const int ledPin = 13;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(ledPin, HIGH); // Turn on the LED
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn off the LED
delay(1000); // Wait for 1 second
}

3. digitalRead(): Reads the value from a digital pin (HIGH or LOW).


int buttonState = digitalRead(buttonPin);
Example: // Button connected to pin 2
const int buttonPin = 2;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(buttonPin);
Serial.println(buttonState);
delay(1000);

IOT LAB
| [Document subtitle]
VIPS-TC

4. analogWrite(): Writes an analog value (PWM) to a pin.


analogWrite(ledPin, brightness);

5. analogRead(): Reads the analog value from an analog pin (0-1023).


int sensorValue = analogRead(A0);
Example: // Analog sensor connected to analog pin 0
const int sensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(sensorPin);
Serial.println(sensorValue);
delay(1000);
}
6. delay(): Pauses the program for a specified number of milliseconds.
delay(1000); // Pause for 1 second
Example:
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000); // Wait for 1 second
digitalWrite(LED_BUILTIN, LOW);
delay(1000); // Wait for 1 second
}

7. Serial.begin(): Initializes serial communication.


Serial.begin(9600); // Initialize serial communication at 9600 bps
8. Serial.println(): Prints data to the Serial Monitor.
Serial.println("Hello, Arduino!");
Example:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Hello, World!");
delay(1000);
}

9. if() statement: Conditional execution based on a condition.

IOT LAB
| [Document subtitle]
VIPS-TC

if (temperature > 25) { // Code to execute when temperature is above 25°C }


10. for() loop: Repeats a block of code a specified number of times.
for (int i = 0; i < 5; i++) { // Code to repeat 5 times }
11. while() loop: Repeats a block of code as long as a condition is true.
while (buttonState == HIGH) { // Code to execute while the button is pressed }
12. Functions: Custom functions allow you to organize and reuse code.
void blinkLED(int pin, int duration)
{
digitalWrite(pin, HIGH);
delay(duration);
digitalWrite(pin, LOW);
delay(duration);
}

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 3
Objective: Introduction with running a blinking LED and fading LED with
PWM

Components Required
You will need the following components −
• 1 × Breadboard
• 1 × Arduino Uno
• 1 × LED
• 1 × 220Ω 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.

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.

IOT LAB
| [Document subtitle]
VIPS-TC

Arduino Code 1
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
*/

void setup() {
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever


void loop() {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage
level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage
LOW
delay(1000); // wait for a second
}

Result: PASTE SCREENSHOTS OF OUTPUT


pinMode(8, OUTPUT) − Before you can use one of Arduino’s pins, you need to tell Arduino
Uno R3 whether it is an INPUT or OUTPUT. We use a built-in “function” called pinMode()
to do this.
digitalWrite(8, HIGH) − When you are using a pin as an OUTPUT, you can command it to
be HIGH (output 5 volts), or LOW (output 0 volts).

Arduino Code 2 : To turn on and off the led for 7 times

#define LED 13
int count;
void setup()
{
pinMode(LED, OUTPUT);
}

IOT LAB
| [Document subtitle]
VIPS-TC

void loop()
{
while (count <7)
{
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(1000);
count = count +1;
}
}
Result: PASTE SCREENSHOTS OF OUTPUT

Code 3: Fading using loop


int led = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
pinMode(led, OUTPUT);
}

void loop() {
analogWrite(led, brightness);
brightness = brightness + fadeAmount;
if (brightness <= 0 || brightness >= 255) {
fadeAmount = -fadeAmount;
}
delay(500);
}

Result: PASTE SCREENSHOTS OF OUTPUT

Question 1: Design a program that will flash the LED connected to pin 13 four times.
Make the flash consist of 1 second on and 2 seconds off. Use pin 8 to reset the flashing so
that it will restart when pin 8 is grounded.

int ledPin = 13;


int resetPin = 8;
int flashCount = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(resetPin, INPUT_PULLUP);
}
void loop() {
if (digitalRead(resetPin) == LOW) {
flashCount = 0;
delay(1000);
}

IOT LAB
| [Document subtitle]
VIPS-TC

if (flashCount < 4) {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(2000);
flashCount++;
}
}

Result: PASTE SCREENSHOTS OF OUTPUT

Question 2: How can you modify an Arduino sketch to make an LED blink on and off for
exactly 7 times before stopping?

int ledPin = 13;


int blinkCount = 0;

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
if (blinkCount < 7) {
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
blinkCount++;
} else {
}
}

Result: PASTE SCREENSHOTS OF OUTPUT

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 4
Aim: Control Structure writing programs for if else, for and while.
A programming language's control structures allow you to take action based on certain
conditions. The Arduino control structures are very similar to the control structure of the C
language and include:

• if
• if...else
• for
• switch case
• while
• do... while
• break
• continue
• return
• goto

Conditional Statements
If statements and while statements are called conditional statements. They evaluate a particular
condition, and execute a series of statements in brackets if the condition is true { }. Here's an
example:
if (pin_b == LOW)
{
digitalWrite(ledPin, HIGH);// This tells the LED to turn on
}
“if” statement consists of word "if" followed by a condition in parentheses. If condition is true,
then statements between brackets that follow will be executed. In this case, if digital value of
pin_b is LOW, then program will set value of ledPin to HIGH. Statements between brackets
are executed only once. While loop is similar to if statement, but in this case, statements
between brackets are executed over and over until condition becomes false.

Here's an example:
while (pin_0 == LOW)
{
digitalWrite(ledPin, HIGH);
delay(100);
digitalWrite(ledPin, LOW);
delay(100);
switchValue = digitalRead(pin_0); // This stores a new value into the variable switchValue
}
In this example, the program will toggle the state the LED (i.e. blink) until a user presses a
switch causing the digital value at pin_0 to go HIGH.

EXPERIMENT 1: Using conditional statements to change brightness of an LED. Assume


LED to be connected to pin 2 of Arduino.

Hardware Required
• 1 x Arduino UNO • 1 X 10k ohm resistor
• 1 x breadboard • Jumper wires
• 1 x LED

IOT LAB
| [Document subtitle]
VIPS-TC

Wiring Diagram

1. Using For LOOP

const int ledPin = 2;


void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(ledPin, brightness);
delay(10);
}

for (int brightness = 255; brightness >= 0; brightness--) {


analogWrite(ledPin, brightness);
delay(10);
}
}

2. Using If-else

int ledPin = 2;
int brightness = 0;
int fadeAmount = 5;

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
analogWrite(ledPin, brightness);
IOT LAB
| [Document subtitle]
VIPS-TC

if (brightness <= 0) {
fadeAmount = 5;
} else if (brightness >= 255) {
fadeAmount = -5;
}

brightness += fadeAmount;
delay(30);
}

3. Using Do-while loop


const int ledPin = 2;
int brightness = 0;
int fadeAmount = 5;

void setup() {
pinMode(ledPin, OUTPUT);
}

void loop() {
do {
analogWrite(ledPin, brightness);
brightness += fadeAmount;
delay(50);
} while (brightness <= 255);

do {
analogWrite(ledPin, brightness);
brightness -= fadeAmount;
delay(50);
} while (brightness >= 0);
}

Wiring Diagram

IOT LAB
| [Document subtitle]
VIPS-TC

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 5
Aim: a. Measuring light with Lux and a photo resistor demonstration
b. Reading and writing digital and analog values. Digital and analog
read/write demonstration.

Theory
LDR stands for Light Dependent Resistor. LDR is a type of resistor that changes resistance as
light on its surface changes i.e., less light or more darkness on LDR surface causes its resistance
to increase. LDR is connected in series with a 10k resistor. LDR is used to detect light levels
and switch an LED on or off.

Working of LDR with Arduino Uno

• LDR gives out analog voltage when connected to VCC (5V), which varies with input
light intensity.
• i.e., greater the intensity of light, greater will be corresponding voltage from LDR.
• LDR gives out an analog voltage, as it is connected to analog input pin on Arduino.
• Arduino, with its built-in ADC (analog-to-digital converter), converts analog voltage
(from 0-5V) into a digital value in range of (0-1023).
• When there is sufficient light in its environment or on its surface, converted digital
values read from LDR through Arduino will be in range of 800-1023.

IOT LAB
| [Document subtitle]
VIPS-TC

Connection Diagram
• Here, 10k resistor R1 and LDR R2 form a voltage divider.
• i.e, voltage at junction of R1 and R2 is divided voltage from 5V that is across them.
• As light varies on LDR surface, so does its resistance which causes voltage between
GND and A0 to vary as well.

Arduino Uno LDR Breadboard Circuit

LDR Module Pin Description


Pins on sensor
• VCC - Positive power supply,
• GND - Ground
• DO - Digital output
• AO - Analog output

IOT LAB
| [Document subtitle]
VIPS-TC

Code 1: Working of LDR with Arduino Uno

void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
int sensorValue = analogRead(A0);
if (sensorValue > 700)
{
digitalWrite(LED_BUILTIN, HIGH);
}
else
{
digitalWrite(LED_BUILTIN, LOW);
}
delay(10);
}

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

Question 1: Working of LDR using While Statement to blink two LEDs for two different
conditions

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 6
Aim: To measure temperature and humidity using DHT sensor

Theory
DHT11 -Low-cost digital sensor for sensing temperature and humidity. It is easily interfaced
with any microcontroller such as Arduino, Raspberry Pi, etc… to measure humidity and
temperature instantaneously. It is available as a sensor and as a module. Difference between
sensor and module is of Pull-up resistor and a power-on LED. It has resistive humidity sensing
and negative temperature coefficient (NTC). 8 bit MCU is connected in it which is responsible
for its fast response. DHT11 sensor consists of a capacitive humidity sensing element and a
thermistor for sensing temperature. Humidity sensing capacitor has two electrodes with a
moisture-holding substrate as a dielectric between them. Change in capacitance value occurs
with change in humidity levels. IC measure, process this changed resistance values and change
them into digital form. For measuring temperature this sensor uses Negative Temperature
coefficient thermistor, which causes a decrease in its resistance value with an increase in
temperature. To get a larger resistance value even for smallest change in temperature, this
sensor is usually made up of semiconductor ceramics or polymers.

DHT Sensor Pin out

PIN 1,2,3,4 (from left to right)


• PIN 1- 3.3V-5V Power supply
• PIN 2- Data
• PIN 3- Null
• PIN 4- Ground

DHT Sensor Library


• Arduino supports a special library for DHT11 and DHT22 sensors
• Provides function to read temperature and humidity values from data pin
• dht.readHumidity()
• dht.readTemperature()
• Install DHT Sensor Library
• Go to sketch -> Include Library -> Manage Library

IOT LAB
| [Document subtitle]
VIPS-TC

Arduino and DHT Sensor Circuit Diagram

DHT 22Code
#include <DHT.h>
DHT dht(2, DHT22);
void setup() {
Serial.begin(9600);
dht.begin();
}

void loop() {
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("% Temperature: ");
Serial.print(temperature);
Serial.println("°C ");
delay(2000);
}

DHT 11Code
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
// DHT dht(2,DHT11)
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHT11 test!");
dht.begin();
}
void loop() {
delay(2000);
float humidity = dht.readHumidity();
IOT LAB
| [Document subtitle]
VIPS-TC

float temperature = dht.readTemperature();


if (isnan(humidity) || isnan(temperature))
//isnan = is NOT A NUMBER which return true when it is not a
number
{
Serial.println("Failed to read from DHT sensor!");
return;
}

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 7
Aim: Custom functions that can be created for specitic Needs. Using a RGB
LED create a custom function program.

Theory
RGB - Stands for "Red Green Blue." RGB refers to three hues of light that can be mixed
together to create different colors. Combining red, green, and blue light is standard method of
producing color images on screens, such as TVs, computer monitors, and smartphone screens.
Types of RGB led’s: Common cathode and Common anode. In common cathode RGB led,
cathode of all led’s is common and PWM signals is given to anode of led’s. In common anode
RGB led, anode of all led’s is common and PWM signals is given to cathode of led’s.

How does an RGB LED work?


• RGB LED can emit different colors by mixing 3 basic colors red, green and blue.
• Consists of 3 separate LEDs red, green and blue packed in a single case.
• Comprises of 4 leads, one lead for each of 3 colors and one common cathode or anode
depending on RGB LED type.
• Cathode will be connected to ground and 3 anodes will be connected through 220 Ohms
resistors to 3 digital pins on Arduino Board that can provide PWM signal.
• Using PWM for simulating analog output will provide different voltage levels to LEDs
to get desired colors

RGB Sensor Pin out

IOT LAB
| [Document subtitle]
VIPS-TC

PIN 1,2,3,4 (from left to right)


• Pin D5 - R
• Pin D4 - G
• Pin D3 - B

Arduino and RGB Sensor Circuit Diagram

RGB LED Code


#define LED1RED 5
#define LED1BLUE 3
#define LED1GREEN 4
void setup() {
pinMode(LED1RED, OUTPUT);
pinMode(LED1BLUE, OUTPUT);
pinMode(LED1GREEN, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED1RED, HIGH);
Serial.println("LED1RED ");
delay(1000);
digitalWrite(LED1RED, LOW);
IOT LAB
| [Document subtitle]
VIPS-TC

Serial.println("LED1RED");
delay(1000);
digitalWrite(LED1BLUE, HIGH);
Serial.println("LED1BLUE");
delay(1000);
digitalWrite(LED1BLUE, LOW);
Serial.println("LED1BLUE");
delay(1000);
digitalWrite(LED1GREEN, HIGH);
Serial.println("LED1GREEN");
delay(1000);
digitalWrite(LED1GREEN, LOW);
Serial.println("LED1GREEN");
delay(1000);
}

Using RGB sensor to create functions for special needs such as setcolor in the following
case:
int redPin= 7;
int greenPin = 6;
int bluePin = 5;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
setColor(255, 0, 0); // Red Color
delay(1000);
setColor(0, 255, 0); // Green Color
delay(1000);
setColor(0, 0, 255); // Blue Color
delay(1000);
setColor(255, 255, 255); // White Color
delay(1000);
setColor(170, 0, 255); // Purple Color
delay(1000);
}
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 8
Aim: To understand the working and programming of Ultrasonic Sensor.

Theory
Ultrasonic sensors measure distance by using ultrasonic waves. Sensor head emits an ultrasonic
wave and receives wave reflected back from target. Ultrasonic sensors measure distance to
target by measuring time between emission and reception. Optical sensor has a Tx and Rx,
whereas an ultrasonic sensor uses a single ultrasonic element for both emission and reception.
In a reflective model ultrasonic sensor, a single oscillator emits and receives ultrasonic waves
alternately. This enables miniaturization of the sensor head.

HC-SR04 Ultrasonic Module has 4 pins, Ground, VCC, Trig and Echo. Ground and VCC pins
of module needs to be connected to Ground and 5 volts pins on Arduino Board respectively
and trig and echo pins to any Digital I/O pin on Arduino Board. To generate ultrasound, set
Trig on a High State for 10 us to send out an 8 cycle sonic burst which will travel at speed
sound and will be received in Echo pin. Echo pin will output time in microseconds sound wave
travelled.

Ultrasonic Sensor Pin out

PIN 1,2,3,4 (from left to right)


• Ground – G
• 12 – trig
• 11 – echo
• 5Volt – Vcc

IOT LAB
| [Document subtitle]
VIPS-TC

Ultrasonic Sensor Code


#define trigPin 11
#define echoPin 12
#define ledPin 13
void setup() {
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
pinMode(ledPin,OUTPUT);
}
void loop() {
long duration , distance;
digitalWrite(trigPin,LOW);
delayMicroseconds(2);
digitalWrite(trigPin,HIGH);
delayMicroseconds(10);
digitalWrite(trigPin,LOW);
duration = pulseIn(echoPin,HIGH);
distance = (duration/2) / 29.1;
if(distance<10)
{
digitalWrite(ledPin,HIGH);
}else{
digitalWrite(ledPin,LOW);
}
Serial.print(distance);
Serial.println("cm");
delay(1500);
}

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 9
Aim: To understand the working and programming of Servo Motor.

Theory
A servo motor is a self-contained electrical device, that rotate parts of a machine with high
efficiency and with great precision. Output shaft of this motor can be moved to a particular
angle, position and velocity that a regular motor does not have. Servo Motor utilizes a regular
motor and couples it with a sensor for positional feedback. Servo motor is a closed-loop
mechanism that incorporates positional feedback in order to control the rotational or linear
speed and position. Motor is controlled with an electric signal, either analog or digital, which
determines the amount of movement which represents the final command position for the shaft.

Servo Motor Pin out

• Servo motors have three wires: power,


ground, and signal.
• Power wire is typically red, and connected
to 5V pin on Arduino board.
• Ground wire is typically black or brown
and connected to ground pin on board.
• Signal pin is typically yellow or orange
and should be connected to PWM pin on
board.

Servo Motor Code 1


#include <Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
for (pos = 0; pos <= 180; pos += 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1)
{
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
IOT LAB
| [Document subtitle]
VIPS-TC

}
}

Servo Motor Code 2


#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup() {
Serial.begin(9600);
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
int val;
while (Serial.available()>0)
{
val = Serial.parseInt();
if(val!=0)
{
Serial.println(val);
myservo.write(val);
}
delay(15);
}

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 10
Aim: Adding an LCD screen and sketch walkthrough

Theory
The LiquidCrystal library allows you to control LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you can usually tell them by
the 16-pin interface. The LCDs have a parallel interface, meaning that the microcontroller has
to manipulate several interface pins at once to control the display.
The interface consists of the following pins:
A register select (RS) pin that controls where in the LCD's memory you're writing data to. You
can select either the data register, which holds what goes on the screen, or an instruction
register, which is where the LCD's controller looks for instructions on what to do next.
A Read/Write (R/W) pin that selects reading mode or writing mode
An Enable pin that enables writing to the registers
8 data pins (D0 -D7). The states of these pins (high or low) are the bits that you're writing to a
register when you write, or the values you're reading when you read.
There's also a display contrast pin (Vo), power supply pins (+5V and GND) and LED Backlight
(Bklt+ and BKlt-) pins that you can use to power the LCD, control the display contrast, and
turn on and off the LED backlight, respectively.

The process of controlling the display involves putting the data that form the image of what
you want to display into the data registers, then putting instructions in the instruction register.
The LiquidCrystal Library simplifies this for you so you don't need to know the low-level
instructions. Hitachi-compatible LCDs can be controlled in two modes: 4-bit or 8-bit. The 4-
bit mode requires seven I/O pins from the Arduino, while the 8-bit mode requires 11 pins. For
displaying text on the screen, you can do most everything in 4-bit mode, so example shows
how to control a 16x2 LCD in 4-bit mode.

Arduino and LCD Pin out


Name Description Arduino Pin*
VSS Ground GND.1
VDD Supply voltage 5V
V0 Contrast adjustment (not simulated)
RS Command/Data select 12
RW Read/Write. Connect to Ground. GND.1

IOT LAB
| [Document subtitle]
VIPS-TC

E Enable 11
D0 – D3 Parallel data 0 - 3 (optional) †
D4 Parallel data 4 10
D5 Parallel data 5 9
D6 Parallel data 6 8
D7 Parallel data 7 7
A Backlight anode 5V / 6‡
K Backlight cathode GND.1

Wiring Diagram

IOT LAB
| [Document subtitle]
VIPS-TC

Simple Hello Program


#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
void setup() {
lcd.begin(16, 2);
// you can now interact with the LCD, e.g.:
lcd.print("Hello World!");
}

void loop() {
// ...
}

Wiring Diagram of connecting an LDR with LCD display

Code
/* The circuit:
* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 10
* LCD D5 pin to digital pin 9
* LCD D6 pin to digital pin 8
* LCD D7 pin to digital pin 7
* LCD R/W pin to ground
* LCD VSS pin to ground
* LCD VCC pin to 5V
* 10K resistor: * ends to +5V and ground * wiper to LCD VO pin (pin 3)
*/

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11 , 12);
IOT LAB
| [Document subtitle]
VIPS-TC

void setup() {
lcd.begin(16, 2);
lcd.setCursor(0,1);
lcd.write("LIGHT: ");
}
void loop()
{
int sensorValue = analogRead(A0);
lcd.print("Room: ");
if (sensorValue > 700)
{
lcd.print("Light!");
}
else
{
lcd.print("Dark ");
}
delay(100);
}

Result
PASTE YOUR SCREENSHOT OF THE SUCCESSFUL RUN OF PROGRAM
INCLUDING HARDWARE CONNECTION AND ARDUINO IDE

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 11
Aim: Design an IoT application using any controller (Arduino Uno or Node
MCU – ESP 8266), any sensor (IR sensor, RBG LED, Ultrasonic Sensor,
DHT11, BMP290, LDR, LUX) and using any other accessories as required.

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 12
Aim: Upload data from a single sensor to ThingSpeak using ESP8266 (Node
MCU)

Components Required:
• ESP8266 (NodeMCU) development board
• DHT11 temperature and humidity sensor
• Breadboard and jumper wires
• USB cable for powering the NodeMCU
• A computer with Arduino IDE installed

Theory of DHT 11
The DHT11 is a low-cost digital humidity and temperature sensor that uses a capacitive
humidity sensor and a thermistor to measure the surrounding air's conditions. Its low price and
compact size make it an attractive option for various applications, such as climate control
systems, weather stations, and home automation. The sensor features a single-wire digital
interface, making it easy to add to microcontroller-based projects. The data provided by the
DHT11 sensor includes relative humidity and temperature readings, and it has a wide operating
voltage range of 3.3V-5V.

To install the ESP32 board in your Arduino IDE, follow the following instructions:
i. In your Arduino IDE, go to File> Preferences

ii. Enter the following into the “Additional Board Manager URLs” field:
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-
pages/package_esp32_index.json

IOT LAB
| [Document subtitle]
VIPS-TC

Then, click the “OK” button


iii.Open the Boards Manager. Go to Tools > Board > Boards Manager

iv. Search for ESP32 and press install button for the “ESP32 by Espressif Systems”

IOT LAB
| [Document subtitle]
VIPS-TC

v. That’s it. It should be installed after a few seconds

vi. Create an Account on ThingSpeak: Visit the ThingSpeak website


(https://thingspeak.com) and create an account. Note down your ThingSpeak channel ID
and API key, which will be used later to send data.
vii. Wire the components as shown in figure.
viii. Install Required Libraries Launch the Arduino IDE and install the necessary libraries
by going to "Sketch" -> "Include Library" -> "Manage Libraries." Search for and install
the following libraries: "DHT sensor library" by Adafruit, "ESP8266WiFi" by ESP8266
Community
Connection Diagram

IOT LAB
| [Document subtitle]
VIPS-TC

Code Snippet
#include <ESP8266WiFi.h>
#include <DHT.h>

#define DHTPIN D4
#define DHTTYPE DHT11

const char* ssid = "YOUR_WIFI_SSID";


const char* password = "YOUR_WIFI_PASSWORD";
const char* server = "api.thingspeak.com";
const String apiKey = "YOUR_API_KEY";

DHT dht(DHTPIN, DHTTYPE);

WiFiClient client;

void setup() {
Serial.begin(115200);
delay(10);
dht.begin();
connectToWiFi();
}

void loop() {
delay(2000);
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();

if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

String url = "/update?api_key=" + apiKey + "&field1=" +


String(temperature) + "&field2=" + String(humidity);

if (client.connect(server, 80)) {
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
client.stop();
Serial.println("Data sent to ThingSpeak successfully!");
} else {
Serial.println("Connection to ThingSpeak failed!");
}
}

void connectToWiFi() {
Serial.print("Connecting to WiFi...");
IOT LAB
| [Document subtitle]
VIPS-TC

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {


delay(100);
}

Serial.println("Connected to WiFi!");
}

ix. Modify Wi-Fi and ThingSpeak Details: Replace "YOUR_WIFI_SSID" with the name
of your Wi-Fi network, "YOUR_WIFI_PASSWORD" with your Wi-Fi password, and
"YOUR_API_KEY" with your ThingSpeak API key.
x. Upload the Sketch
xi. Monitor the Serial Output: After the upload is complete, open the serial monitor by
clicking "Tools" -> "Serial Monitor" in the Arduino IDE. Make sure the baud rate is set
to 115200. You should see the NodeMCU connecting to the Wi-Fi network and sending
data to ThingSpeak. Check the serial monitor for any error messages.
xii. Verify Data on ThingSpeak: Go to your ThingSpeak channel and open the corresponding
channel view. You should see the temperature and humidity data being updated in real-
time.

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 13
Aim: Interface DHT11 (Humidity Sensor) Using NodeMCU

Components Required
• Breadboard
• Micro USB Cable
• ESP8266 NodeMCU
• DHT11 Humidity and Temperature sensor
• Jumper Wires
• Arduino IDE

Wiring: Wire the components as follows:

• Connect the VCC pin of the DHT11 sensor to the 3.3V pin of the NodeMCU.
• Connect the GND pin of the DHT11 sensor to the GND pin of the NodeMCU.
• Connect the data pin of the DHT11 sensor to any GPIO pin of the NodeMCU.
• Connect the NodeMCU to your computer using a USB cable.

Code
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT11

DHT dht(DHTPIN, DHTTYPE);


void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
delay(2000);

IOT LAB
| [Document subtitle]
VIPS-TC

float temperature = dht.readTemperature();


float humidity = dht.readHumidity();

if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" °C\t");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
}

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 14
Aim: Interface RGB Led Using NodeMCU

Components Required
• Breadboard
• Micro USB Cable
• ESP8266 NodeMCU
• RGB Led sensor
• Jumper Wires
• Arduino IDE

Wiring: Wire the components as follows:

• GND pin of module – GND pin of NodeMCU.


• R pin (red light) of module – digital-2 pin of NodeMCU.
• G pin (green light) of module – digital-1 pin of NodeMCU.
• B pin (blue color) of module – digital-0 pin of NodeMCU.
• Connect the NodeMCU to your computer using a USB cable.

Code
#define RED_PIN 12 // Digital pin 2 of NodeMCU
#define GREEN_PIN 13 // Digital pin 1 of NodeMCU
#define BLUE_PIN 14 // Digital pin 0 of NodeMCU
IOT LAB
| [Document subtitle]
VIPS-TC

void setup() {
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
}

void loop() {
setColor(255, 0, 0); // Red
delay(1000);
setColor(0, 255, 0); // Green
delay(1000);
setColor(0, 0, 255); // Blue
delay(1000);
setColor(255, 255, 255); // White
delay(1000);
}

void setColor(int red, int green, int blue) {


analogWrite(RED_PIN, red);
analogWrite(GREEN_PIN, green);
analogWrite(BLUE_PIN, blue);
}

IOT LAB
| [Document subtitle]
VIPS-TC

Experiment No. 15
Aim: Create an echo server with the Ethernet Shield over Arduino.

Components Required
- Arduino Uno Board
- Ethernet Shield (W5100)
- Ethernet Cable
- Computer with Arduino IDE installed
- USB Cable for Arduino

Wiring: Wire the components as follows:


1. Connect the Ethernet Shield to the Arduino board.
2. Connect the Arduino board to your computer using the USB cable.

Installing Necessary Libraries


1. Open the Arduino IDE on your computer.
2. Go to "Sketch" -> "Include Library" -> "Manage Libraries..."
3. Search for "Ethernet" and install the latest version.

Code:

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.


byte mac [] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Set the IP address of the server


IPAddress ip(192, 168, 1, 177);

// Create a server object


EthernetServer server(23);

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// start the Ethernet connection and the server:


IOT LAB
| [Document subtitle]
VIPS-TC

Ethernet.begin(mac, ip);
server.begin();
Serial.print("Server is at ");
Serial.println(Ethernet.localIP());
}

void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the
response
client.println("Refresh: 5"); // refresh the page automatically every 5 seconds
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");

// output the value of each analog input pin


for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
} else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");

IOT LAB
| [Document subtitle]
VIPS-TC

}
}

Procedure:
1. Connect the Arduino to your computer using the USB cable.
2. Select the appropriate board and port from the "Tools" menu.
3. Click the upload button to upload the code to the Arduino.
4. Once the code is uploaded, open the serial monitor in the Arduino IDE.
5. Note the IP address assigned to the server (displayed in the serial monitor).
6. Open a web browser and enter the IP address in the address bar.
7. The browser should display analog readings from the Arduino.

Result:
This lab practical demonstrates the implementation of an Echo Server using Arduino and
Ethernet Shield. Students should understand the code, the role of the server, and how to test
the communication between the server and a client.

IOT LAB
| [Document subtitle]

You might also like