r22 Iot Lab Manual Final1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

INTERNET OF THINGS LAB

INTRODUCTION TO RASPBERRY PI

RASPBERRY PI:

The Raspberry Pi is a low cost, single board computer credit-card sized


computer that plugs into a computer monitor or TV, and uses a standard
keyboard and mouse. It’s capable of doing everything you’d expect a desktop
computer to do, from browsing the internet and playing high-definition
video, to making spreadsheets, word-processing, and playing games.

Raspberry pi verses Arduino:

Department of Information & Technology Page 1


INTERNET OF THINGS LAB

Raspberry Pi4 Model B:

• Raspberry Pi is a small single board computer. By connecting


peripherals like Keyboard, mouse, display to the Raspberry Pi, it will
act as a mini personal computer.
• Raspberry Pi Foundation officially provides Debian based Raspbian
OS. Also, they provide NOOBS OS for Raspberry Pi. We can install
several Third-Party versions of OS like Ubuntu, Arch-Linux, RISC OS,
Windows 10 IOT Core, etc.
• Raspbian OS is official Operating System available for free to use. This
OS is efficiently optimized to use with Raspberry Pi.
• Raspberry Pi is more than computer as it provides access to the on-
chip hardware i.e. GPIOs for developing an application. By accessing
GPIO, we can connect devices like LED, motors, sensors, etc and can
control them too.
• It has ARM based Broadcom Processor SoC along with on-chip GPU
(Graphics Processing Unit).
• Raspberry Pi also provides on-chip SPI, I2C, and UART modules.

There are different versions of raspberry pi available as listed below:

• Raspberry Pi 1 Model A
• Raspberry Pi 1 Model A+
• Raspberry Pi 1 Model B
• Raspberry Pi 1 Model B+
• Raspberry Pi 2 Model B
• Raspberry Pi 3 Model B
• Raspberry Pi 4 Model B
Department of Information & Technology Page 2
INTERNET OF THINGS LAB

• Raspberry Pi Zero

Raspberry Pi 4 Model B Board Description:

The Processor

while the Raspberry Pi 3 was built around the Broadcom BCM2837


processor, a quad-core Arm Cortex-A53 clocked at 1.4GHz, the new board is
built around the Broadcom BCM2711, a 64-bit quad-core Arm Cortex-A72
clocked at 1.5GHz.

USB Ports

Raspberry Pi comes with four (TWO 3.0 + TWO 3.0) ports. The USB ports on
Raspberry Pi can provide a current up to 100mA. The VLI VL805 which
provides a USB 3.0 Hub over a PCI Express bus.

Ethernet Ports:

Raspberry Pi comes with a standard RJ45 Ethernet port. We can connect an


Ethernet cable or a USB WiFi adapter to provide Internet connectivity. which
had a maximum throughput limited to around 300Mbps—is now provided
using the Broadcom BCM54213PE on a separate bus to the USB traffic.

The Raspberry Pi 4 board has both ‘real’ Gigabit Ethernet and two USB 3.0
ports as well as a couple more ‘legacy’ USB 2 ports.

Department of Information & Technology Page 3


INTERNET OF THINGS LAB

Wireless Support

Wireless support is provided in an RF shielded module by the same Cypress


CYW43455 chip as we saw on the Raspberry Pi 3, Model B+. Offering dual-
band 2.4GHz and 5GHz IEEE 802.11.b/g/n/ac wireless networking, as well
as Bluetooth 5.0 and Bluetooth LE

The Memory

For completeness the final big bit of silicon—located just to the right of the
main processor package—is the LPDDR4 SDRAM for the board which comes
in the shape of a Micron FBGA-packaged chip

Unlike any previous board, the new Raspberry Pi 4 is available in three


different models, each offering a different memory option. The new board
can come with either 1GB, 2GB or 4GB or 8GB of RAM.

Power Input:

Raspberry Pi has a micro-USB connector for power input

HDMI Output:

The HDMI port on Raspberry Pi provides both video and audio output. We
can connect the Raspberry Pi to a monitor using an HDMI cable. For
monitors that have a DVI (Digital Video interface) port but no HDMI port, we
can use an HDMI to DVI adapter/cable.

Composite Video Output: Raspberry Pi comes with a composite video


output with an RCA jack that supports both PAL and NTSC video output.

Department of Information & Technology Page 4


INTERNET OF THINGS LAB

The RCA jack can be used to connect old televisions that have an RCA input
only.

GPIO Pins:

Raspberry Pi comes with a number of general-purpose input/output pins.


There are four types of pins on Raspberry Pi- true GPIO pins, I2C interface
pins, SPI interface pins and serial Rx and Tx pins.

Display Serial Interface (DSI):

The DSI interface can be used to connect an LCD panel to Raspberry Pi.

Camera Serial Interface (CSI):

This interface can be used to connect a camera module toRaspberry Pi.

Status LEDs: Raspberry Pi has five status LEDs

StatusLED Function
ACT SDcard access
PWR 3.3VPowerispresent
FDX FullduplexLAN connected
LNK Link/Networkactivity
100 100MbitLANconnected

SD Card Slot:

Raspberry Pi does not have a built-in operating system and storage. SD card
slot on the Raspberry Pi 3 is located just below the Display Serial Adapter on
the other side. We can plug-in an SD card loaded with a Linux image to the
SD card slot.

Department of Information & Technology Page 5


INTERNET OF THINGS LAB

RASPBERRY PI 4 GPIO PINOUT

Raspberry Pi 4 has come up with more advanced features than the previous
Raspberry Pi model. It was launched in June 2019 and has come up with a
much-improved processing speed of about 90% as compared to the previous
version due to the inclusion of 4GB and 8GB RAM memory. Its General-
Purpose Input Output (GPIO) pins have also maintained the previous
standard set by the Raspberry Pi models, and are now more functional and
performing flawlessly.

The Raspberry Pi 4 has 40 GPIO pins that can be configured to read inputs
or write outputs.

Raspberry Pi 4 GPIO Pins

Here, we will be able to learn the functioning of each pin, which helps you to
do things on Raspberry Pi 4. There are 40 pins in this model and among
them, 26 are GPIO pins.

The Raspberry Pi model includes two 5V pins, two 3.3V pins, eight ground
pins and two reserved pins.

5V pins: The 5V pins are used to output the 5V power supply provided by
the Type-C port. The pins are numbered 2 and 4 on the Raspberry Pi 4
device.

3.3V pins: The 3.3V pins provide a 3.3V power supply to the external
components, numbered 1 and 17.
Department of Information & Technology Page 6
INTERNET OF THINGS LAB

Ground pins: The ground pins are used to close the electric circuits. The
ground pins help you to protect your board from burning and play an
important part in a circuit. The ground pins are numbered
6,9,14,20,25,30,34 and 39.

Reserved Pins: These pins are used to perform communication between I2C
and EEPROM. If you are new to Raspberry Pi, you are advised not to
connect anything with these pins, which are 27 and 28 number pins.

GPIO Pins

These are the pins on your Raspberry Pi that perform various functions and
each pin is assigned a different task. Some pins are used as inputs, while
others are used as outputs. Input voltages ranging from 1.8V to 3V are
considered high voltage, while voltages less than 1.8V are considered low
voltage. You need to keep the voltage of the power supply below 3V to
protect your Raspberry Pi from burning.

Department of Information & Technology Page 7


INTERNET OF THINGS LAB

Pulse Width Modulation

The GPIO pins are used for Pulse Width Modulation (PWM), which is the
process of converting a Digital signal to an Analog signal. All pins can
perform software PWM, but only a few can perform hardware PWM,
including GPIO pins 12, 13, 18, and 19.

Serial Peripheral Interface Pins on Raspberry Pi 4

You can use Serial Peripheral Interface (SPI) pins to communicate between
devices such as sensors or actuators on the Raspberry Pi. The Raspberry Pi
sends data to a device via the Master Out Slave Pin (MOSI), and the same
device communicates with the Raspberry Pi via the Master In Slave Out
(MISO) pin. SP communication necessitates using five GPIO pins for GND,
SCLK, MOSI, MISO, and CE. The CE pin is used to enable or disable circuit
integration, whereas the SCLK pin serves as a clock for SPI communication.
The Raspberry Pi’s SPI communication pins are listed below.

For SPIO select GPIO9 as MISO, GPIO10 as MOSI, GPIO11 as SCLK, GPIO8
as CE0 and GPIO7 as CE1.

For the case of SPI1 pins, select GPIO19 as MISO, GPIO20 as MOSI, GPIO21
as SCLK, GPIO18 as CE0, GPIO17 as CE1, and GPIO16 as CE2.

Inter-Integrated Circuit Pins on Raspberry Pi 4

Using the Inter-Integrated Circuit (I2C) pins, the Raspberry Pi can control
other peripheral devices attached to it. The communication is possible using
the pins Serial Data (SDA) and Serial Clock (SCL). The data is forwarded
using the SDA pin and the processing speed of data is controlled using the
SCL pin. There is another type of data called “Electrically erasable
programmable read-only memory (EEPROM)” data, which is in small
quantities

In Raspberry Pi, the GPIO2 pin is responsible for transferring data using
SDA, and GPIO3 controls data speed by working as SCL. For the case of
EEPROM, the GPIO0 pin is used for data transferring while the GPIO1 pin is
used as a clock to control the speed of data.

UART Pins on Raspberry Pi 4: A Universal Asynchronous Receiver


Transmitter (UART) is a type of communication in which data is transferred
sequentially bit by bit. You need a transmitter and a receiver to perform

Department of Information & Technology Page 8


INTERNET OF THINGS LAB

UART communication. For UART communication, the Raspberry Pi 4 has


two default pins. The GPIO14(TX) pin is a transmitter to send data to
another device, while the GPIO15(RX) pin is a receiver to receive data from
another device.

There are four more additional pins you can use for UART communication.
However, you should need to enable them to use them. Among these pins,
three are of type PL011 (main UART for models without Bluetooth) while the
UART1 is of type mini UART (UART for models with Bluetooth). The following
is the list of pins that are using UART communication:

UART GPIO Pins (TXD/RXD)


0 14/15
1 14/15
2 0/1
3 4/5
4 8/9
5 12/13

Raspberry Pi Python Basics

Python RPi.GPIO API Library

• One of the famous libraries in launching input and output pins is the
RPi.GPIO libraryin python programming.
• Use the RPi.GPIO module as the driving force behind our Python GPIO
examples. This set of Python files and source is included with
Raspbian OS –NOOBS, (Linux based)

How to Setup RPi.GPIO

• This library is available on Raspbian operating system by default and


you don’t need to install it.
• In order to us RPi.GPIO in Python script, you need to put this
statement at the top of your file: import RPi.GPIO as GPIO
• That statement "includes" the RPi.GPIO module, and goes a step
further by providing a local name -- GPIO -- which we'll call to
reference the module from here on.

Department of Information & Technology Page 9


INTERNET OF THINGS LAB

Pin Numbering Declaration

• After including the RPi.GPIO module, the next step is to determine


which of the two pin- numbering schemes
o GPIO.BOARD:Board numbering scheme. The pin numbers
follow the pin numbers on header P1.
o GPIO.BCM:Broadcom chip-specific pin numbers. These pin
numbers follow the lower-level numbering system defined by the
Raspberry Pi's Broadcom-chip brain.
• To specify in your code which number-system is being used, use the
GPIO.setmode() function.

Example:

GPIO.setmode(GPIO.BCM)#will activate the Broadcom-chip specific pin


numbers.

Note: Both the import and setmode lines of code are required, if you want to
use Python.

Setting a Pin Mode:

• If you've used Arduino, you're probably familiar with declare a "pin


mode" before you can use it as either an input or output.
• In Raspberry Pi to set a pin mode, use the
o GPIO.setup(pin number, pinmode) function.

Example: if you want to set pin 18 as an output, write: GPIO.setup(18,


GPIO.OUT)

Note: Remember that the pin number will change if you're using the board
numbering system (instead of 18, it'd be 12).

o GPIO.setmode(GPIO.BCM); Using pins BCM numbers

Basic Commands

• GPIO.setup(pin, GPIO.IN); Determines the pin as input


• GPIO.setup(pin, GPIO.OUT); Determines the pin as an output
• GPIO.input(pin): Reading input pin
• GPIO.output(pin, state): Writing on the output pin.

Department of Information & Technology Page 10


INTERNET OF THINGS LAB

1. A) Calculating Distance using the HC-SR04 distance sensor with


Raspberry Pi

Components required:

• Raspberry Pi 4
• Micro SD Card
• Power Supply
• HC-SR04 Ultrasonic Sensor
• 1k OHM Resistor
• 2k OHM Resistor
• Breadboard
• Jumper Wires

Working Process:

Wiring HC-SR04 Distance Sensor to Raspberry Pi is a relatively simple


process as most pins of the distance sensor map directly to a pin on the
Raspberry Pi.

The only slightly complicated part of wiring the device to the Raspberry Pi is
the voltage divider that connect for the echo pin.

The reason for adding a voltage divider is to drop the voltage going to the
GPIO pins down to 3.3v from 5v. To achieve this by utilizing a 1k Ω resistor
and a 2k Ω resistor.

Connections:

• VCC Connects to Pin 2 (5v)


• Trig Connects to Pin 7 (GPIO 4) Echo Connects to R1 (1k Ω)
• R2 (2k Ω) Connects from R1 to Ground Wire from R1 and R2 connects
to Pin 11
• GND connects to Pin 6 (Ground)

Department of Information & Technology Page 11


INTERNET OF THINGS LAB

• Run a wire from the ground pin (Pin 6) to the ground/negative rail on
the breadboard.
• Run a wire from 5v pin (Pin 2) to the VCC pin on the HC-SR04
distance sensor.
• Run a wire from pin 7 to the TRIG pin on the distance sensor.
• Run a 1k Ω resistor from the ECHO pin on the distance sensor to a
spot on the breadboard.
• Run a 2k Ω resistor from the 1k Ω resistor to the ground/negative rail
on the Raspberry Pi.
• Run a wire from between the 1k Ω resistor and the 2k Ω resistor to
pin 11 on the Raspberry Pi.

Source Code:

import RPi.GPIO as GPIO

import time

try:

GPIO.setmode(GPIO.BOARD)

PIN_TRIGGER = 7

PIN_ECHO = 11

GPIO.setup(PIN_TRIGGER, GPIO.OUT)

GPIO.setup(PIN_ECHO, GPIO.IN)

GPIO.output(PIN_TRIGGER, GPIO.LOW)

print "Waiting for sensor to settle"

Department of Information & Technology Page 12


INTERNET OF THINGS LAB

time.sleep(2)

print "Calculating distance"

GPIO.output(PIN_TRIGGER, GPIO.HIGH)

time.sleep(0.00001)

GPIO.output(PIN_TRIGGER, GPIO.LOW)

while GPIO.input(PIN_ECHO) ==0:

pulse_start_time = time.time()

while GPIO.input(PIN_ECHO) ==1:

pulse_end_time = time.time()

pulse_duration = pulse_end_time - pulse_start_time

distance = round(pulse_duration * 17150, 2)

print "Distance:",distance,"cm"

finally:

GPIO.cleanup()

OUTPUT:

Waiting for sensor to settle

Calculating distance

Distance: 29.69 cm

Department of Information & Technology Page 13


INTERNET OF THINGS LAB

1. B) BASIC LED FUNCTIONALITY USING RASPBERRY PI

AIM: LED Functionality (Blinking of LED) using RASPBERRY PI

Required Components:

• Raspberry Pi Board with OS installed on it


• One LED
• One Resistor (220 Ohm)
• M to F Jumper Wires
• Breadboard
• Keyboard
• Mouse
• Monitor
• Power Adapter
• Micro HDMI to HDMI Cable

Procedure:

1. Attach the LED to the breadboard


2. Attach Blue color jumper wire one end to long leg of LED and connect
other end to GPIO Pin number 6 (one of the Ground Pin) of Raspberry
Pi
3. Attach 220 Ohm resistor to other free leg of LED
4. Attach White color jumper wire one end to other free leg of resistor
and connect other end to GPIO Pin number 8 of Raspberry Pi
5. Now connect Keyboard, Mouse, Monitor, and finally Power Adapter to
the Raspberry Pi
6. Write the Python code by using Thonny IDE available in Programming
Tab
7. Then Save the Code with .py extension in any location by clicking on
Save Option in IDE
8. Finally Click on Run Option in IDE
9. You will see the output in Shell Panel.

Source Code:

import RPi.GPIO as G

import time

G.setmode(G.BOARD)
Department of Information & Technology Page 14
INTERNET OF THINGS LAB

G.setup(8, G.OUT)

while True:

G.output(8, True)

print (“LED is ON”)

time.sleep(2)

G.output(8, False)

print (“LED is OFF”)

time.sleep(2)

OUTPUT:

Department of Information & Technology Page 15


INTERNET OF THINGS LAB

Department of Information & Technology Page 16


INTERNET OF THINGS LAB

2. INTRODUCTION TO ARDUINO

Arduino:

Arduino is a prototype platform (open-source) based on an easy-to-use


hardware and software. It consists of a circuit board, Arduino consists of
both a physical programmable circuit board (often referred to as a
microcontroller) and a piece of software, or IDE (Integrated Development
Environment), which is used to write and upload the computer code to the
physical board.

key features:

• Arduino boards are able to read analog or digital input signals from
different sensors and turn it into an output such as activating a
motor, turning LED on/off, connect to the cloud and many other
actions.
• Able to control the board functions by sending a set of instructions to
the microcontroller on the board via Arduino IDE (referred to as
uploading software).
• Arduino does not need an extra piece of hardware (called a
programmer) in order to load a new code onto the board. You can
simply use a USB cable.
• The Arduino IDE uses a simplified version of C++, so making it easier
to learn to program.

Arduino Boards:

A wide range of boards is manufactured by Arduino. These have different


sizes, different microcontrollers, and different processing capabilities.

There are entry level boards like the UNO, LEONARDO, NANO etc; boards
with enhanced feature like the MEGA, PRO, ZERO etc; boards for Internet of
Things like the YUN, TIAN etc; and wearable boards like the LILYPAD,
GEMMA etc.

Depending on the need of application and the processing requirements,


users can choose from any of these.

Department of Information & Technology Page 17


INTERNET OF THINGS LAB

Fig 1: Arduino UNO Board

Fig 2: Layout of Arduino UNO Board

Components on the Arduino board:

Power (USB / Barrel Jack)

The Arduino UNO board can be powered through

• A USBcable
• An external AC-DC adapter (output voltage of the adapter must be
fixed and within the range of 7V to 12V). Adapter needs to be plugged
into the power jack.
• A battery (Fixed voltage, the voltage must be in the range of 7V to
12V). Battery terminals must be connected between VIN and GND
pins on the board.

Department of Information & Technology Page 18


INTERNET OF THINGS LAB

Microcontroller:

Arduino have two types of microcontrollers one is the main controller


ATmega328P and the second one is Atmega16u2.

ATmega328P microcontroller: This is the brain of the board. This is used


to control Arduino logic and as processing unit of the board. The
Atmega328P has 32kB In-System Programmable Flash Memory, 1kB
EEPROM, and 2kB internal SRAM.

ATmega16u2, which is responsible for Arduino serial interface.

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

Crystal oscillator helps the microcontroller to calculate time and


synchronize the internal operations. Time factors play a crucial role in
receiving and sending signals to Arduino and its peripherals. Based on
crystal oscillator frequency microcontrollers can make decisions fast. 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

Ceramic Resonators

Main purpose of ceramic resonators in Arduino is to generate clock signals


for ATmega328P microcontroller.

Arduino Reset

To reset Arduino board, i.e., start the program from the beginning or when
uploading new program. Reset can work in two ways. First, by using the
Reset button on the board, second, you can connect an external reset
button to the Arduino pin labeled as RESET.

Pins (3.3, 5, GND, Vin)

• 3.3V − Supplies 3.3 volts of power


• 5V − Supplies 5 volts of power

Department of Information & Technology Page 19


INTERNET OF THINGS LAB

Most of the components used with Arduino board works fine with 3.3 volt
and 5 volts.

• GND (Ground) − There are several GND pins on the Arduino, any of
which can be used to ground your circuit. The ground pin acts as a
pin with zero voltage.
• Vin − It is the input voltage. This pin also can be used to power the
Arduino board from an external power source, like AC mains power
supply.

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. The analog pins can be used as digital I/O pins as well
if there is no analog input to be measured.

ICSP pin

The In-Circuit Serial Programming pin allows the user to program using the
firmware of the Arduino board. Is 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. Means, for slaving the output device to the
master of the SPI bus.

Power LED indicator

The ON status of LED should light up when plug the Arduino into a power
source to indicate that the board is powered up correctly. If this light does
not turn on, then there is something wrong with the connection.

TX and RX

On the 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. 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.

Department of Information & Technology Page 20


INTERNET OF THINGS LAB

Digital I/O

The Arduino UNO board has 14 digital I/O pins (of which 6 provide PWM
(Pulse Width Modulation) (pins 3,5,6,9,10 and 11) output. These pins can be
configured to work as inputdigital 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 used to set an external reference


voltage (between 0 and 5 Volts) as the upper limit for the analog input pins.
I.e. is used to feed a reference voltage to the Arduino UNO board from the
external power supply.

USB

It allows the board to connect to the computer. It is essential for the


programming of the Arduino UNO board.

Department of Information & Technology Page 21


INTERNET OF THINGS LAB

2.1 ARDUINO - INSTALLATION

The following steps shown 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 Arduino board and a USB cable. For Arduino
UNO, Arduino Duemilanove, Nano, Arduino Mega 2560, or Diecimila, you
will need a standard USB cable (A plug to B plug), as shown in the following
image.

Fig: USB Cable

Step 2 − Download Arduino IDE Software

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.

Step 3 − Power up your board.

The Arduino UNO automatically draw power from either, the USB
connection to the computer or an external power supply. Connect the
Arduino board to your computer using the USB cable. The power LED
(labeled ON) 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.

Department of Information & Technology Page 22


INTERNET OF THINGS LAB

Step 5 − Open your first project

Once the software starts, you have two options −

Department of Information & Technology Page 23


INTERNET OF THINGS LAB

• Create a new project.


• Open an existing project example.

To create a new project, select File → New.

To open an existing project example, select File → Example → Basics →


Blink.

Department of Information & Technology Page 24


INTERNET OF THINGS LAB

Here, we are selecting just one of the examples with the name Blink. It turns
the LED on and off with some time delay.

Step 6 − Select your Arduino board

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.

Step 7 − Select your serial port

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.

Department of Information & Technology Page 25


INTERNET OF THINGS LAB

Step 8 − Upload the program to your board

Before going to know how to upload the program to the board, we must
know 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 sketches.

E − Used to save your sketch.

F − Serial monitor used to receive serial data from the board and send the
serial data to the board.

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.

Department of Information & Technology Page 26


INTERNET OF THINGS LAB

2. USING ARDUINO

a) Calculate the distance using a distance sensor.


b) Basic LED functionality.
c) Calculate temperature using a temperature sensor.

2. A) Calculate the distance using a distance sensor

Hardware Requirements

• Arduino UNO board


• USB cable connecter for Arduino UNO
• Ultra-Sonic HC-SR04
• Jumper wires male to female

Software requirements

• Arduino software

Arduino

It is an open-source electronics platform. It consists ATmega328 8-bit


Microcontroller. It can be able to read inputs from different sensors & we
can send instructions to the microcontroller in the Arduino. It provides
Arduino IDE to write code & connect the hardware devices like Arduino
boards & sensors.

Ultrasonic Sensor

An ultrasonic Sensor is a device used to measure the distance between the


sensor and an object without physical contact. The Ultra Sonic HC-SR04
emits ultrasound at 40,000Hz that travels in the air. If there is an object or
obstacle in its path, then it collides and bounces back to the Ultra Sonic
module. This device works based on time-to-distance conversion.

Working Principle of Ultrasonic Sensor:

We know that the speed of sound in air is nearly 344 m/s or 0.034 cm/µs,

So, the known parameters are time and speed (constant). Using these
parameters, we can calculate the distance traveled by the sound wave.

Formula: Distance = Speed * Time

Department of Information & Technology Page 27


INTERNET OF THINGS LAB

the “duration” variable stores the time taken by the sound wave traveling
from the emitter to the receiver. That is double the time to reach the object,
whereas the sensor returns the total time including sender to object and
object to receiver. Then, the time taken to reach the object is half of the time
taken to reach the receiver.

So, we can write the expression as,

Distance = Speed of Sound in Air * (Time Taken / 2)

Setup:

• Connect the Echo pin of the sensor to the D2 pin of the Arduino.
• Connect the Trig pin of the sensor to the D3 pin of the Arduino.
• Navigate to Tools and select board and port.
• Verify and compile the code, then upload the code to the Arduino Uno
R3 board.
• Monitor the output in the Serial monitor (Set the baud rate as 9600).
To open Serial monitor Tools>Serial Monitor

Source Code

const int trigPin = 3; // attach pin D3 Arduino to pin Trig of HC-SR04


const echoPin = 2; // attach pin D2 Arduino to pin Echo of HC-SR04

long duration; // Variable to store time taken to the pulse to reach


receiver int distance; // Variable to store distance calculated using
formula

void setup ()

pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT


pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT

Serial.begin(9600); // Serial Communication is starting with 9600 of


baud rate speed

// The text to be printed in serial monitor Serial.println("Distance


measurement using Arduino Uno.");

delay (500);

Department of Information & Technology Page 28


INTERNET OF THINGS LAB

void loop ()

digitalWrite(trigPin, HIGH); // turn on the Trigger to generate pulse


delayMicroseconds(10); // keep the trigger "ON" for 10 ms to generate pulse
for 10 ms.digitalWrite(trigPin, LOW); // Turn off the pulse trigger to stop
pulse generation

// If pulse reached the receiver echoPin become high Then pulseIn() returns
the time taken by the pulse to reach the receiver

duration = pulseIn(echoPin, HIGH);

distance = duration * 0.034 / 2; // Expression to calculate distance


using time Serial.print("Distance: ");

Serial.print(distance); // Print the output in serial monitor Serial.println("


cm");

delay (100);

OUTPUT:

Department of Information & Technology Page 29


INTERNET OF THINGS LAB

2.B) BASIC LED FUNCTIONALITY USING ARDUINO

AIM: LED Blinking Using Arduino

Components Required

• 1 X LED
• 1 X Resistor, 330 Ohm
• Breadboard
• Arduino UNO R4 or earlier versions.
• Jumper wires

LED

LEDs (Light Emitting Diodes) takes a voltage that is given to a PN Junction


Diode, electrons, and holes recombine in the PN Junction and release energy
in the form of light (Photons).

Blinking an LED

Blinking an LED in which we control an LED using Arduino. LED blinking


refers to the process of continuously turning an LED (Light Emitting Diode)
and off in a repetitive pattern.

Setup:

• LED Connections: Connect the LED to the breadboard. The LED has
two legs, the longer of which is the anode (positive) and the shorter of
which is the cathode (negative).
• Resistor Connection: Insert one end of the resistor into the same row
of the breadboard as the LED’s Anode. The resistor’s other end should
be connected to the Arduino’s digital output pin.
• Ground (GND) Connection: Connect a jumper wire from the same row
as the LED’s cathode to any Arduino board GND (Ground) pin. This
connects the circuit to the ground of the Arduino.

Source Code

int LEDpin = 13;

void setup() {

pinMode(LEDpin, OUTPUT);

Department of Information & Technology Page 30


INTERNET OF THINGS LAB

void loop() {

digitalWrite(LEDpin, HIGH);

delay(2000);

digitalWrite(LEDpin, LOW);

delay(2000);

OUTPUT:

Department of Information & Technology Page 31


INTERNET OF THINGS LAB

2. C) CALCULATE TEMPERATURE USING ARDUINO

AIM: Calculate Temperature using Temperature Sensor with Arduino

Components Required

• 1 X DHT11 Sensor
• 1 X Resistor, 330 Ohm
• Breadboard
• Arduino UNO R4 or earlier versions.
• Jumper wires

DHT11 Sensor

DHT11 Module features a temperature & humidity sensor complex with a


calibrated digital signal output. DHT11 can measure temperature from 0°C
to 50°C with a ±2.0°C accuracy, and humidity from 20 to 80% with a 5%
accuracy.

DHT11 Module Pinout

The DHT11 module has a total of 3 pins. In which two are for power and one
is for communication. The pinout of a DHT11 Sensor module is as follows:

+(VCC)pin provides power to the sensor. Despite the fact that the supply
voltage of the module ranges from 3.3V to 5.5V, a 5V supply is
recommended. With a 5V power supply, the sensor can be placed up to 20
meters away. With 3.3V supply voltage, the sensor can be placed just 1
meter away; otherwise, the line voltage drop will cause measurement errors.

DATApin is used for communication between the sensor and the


microcontroller

– (GND) is the ground pin.

Department of Information & Technology Page 32


INTERNET OF THINGS LAB

Setup: Connections are relatively simple. Begin by connecting the + (VCC)


pin to the Arduino’s 5V output and the – (GND) pin to ground. Finally,
connect the Out pin to digital pin #8.

Installing DHT library

The DHT sensors has their own proprietary single-wire data transfer
protocol. This protocol requires precise timing. using the DHT library, which
handles almost everything.

To install the library, navigate to Sketch > Include Library > Manage
Libraries… Wait for the Library Manager to download the libraries index and
update the list of installed libraries.

Filter your search by entering ‘DHT sensor library’ then find DHT Sensor
Library by Adafruit. Click on that and then choose Install all.

Department of Information & Technology Page 33


INTERNET OF THINGS LAB

SOURCE CODE

#include <dht11.h>

#define DHT11PIN 4

DHT dht11(DHT11PIN, DHT11);

void setup ()

Serial.begin(9600);

dht11.begin();

void loop()

delay(2000);

//Read data and store it to variables hum and temp

float hum = dht.readHumidity();

float tempC= dht.readTemperature();


Department of Information & Technology Page 34
INTERNET OF THINGS LAB

float tempF= dht.readTemperature(true);

//Print temp and humidity values to serial monitor

Serial.print("Humidity: ");

Serial.print(hum);

Serial.print(" %, Temp: ");

Serial.print(tempC);

Serial.println("0C ");

Serial.print(tempF);

Serial.println("0F"); }

OUTPUT:

Department of Information & Technology Page 35


INTERNET OF THINGS LAB

3. USING NODE MCU

3. A) Calculate the distance using a distance sensor.

Component’s Required

• HC-SR04 Ultrasonic Sensor


• ESP32 development board
• Breadboard
• Jumper wires

HC-SR04 Ultrasonic Sensor Pinout:

HC-SR04 Ultrasonic Sensor have the following pins,

• VCC - Powers the sensor (5V)


• Trig- Trigger Output Pin
• Echo- Echo Input Pin
• GND- Common GND

HC-SR04 Ultrasonic Sensor Working principle:

• The ultrasound transmitter (trig pin) emits a high-frequency sound


(40 kHz).
• The sound travels through the air. If it finds an object, it bounces
back to the module.
• The ultrasound receiver (echo pin) receives the reflected sound (echo).

Formula to find distance using Ultrasonic Sensor HC-SR04:

distance to an object = ((speed of sound in the air) *time)/2

Note: Speed of sound in the air at 20ºC (68ºF) = 343m/s

Integrating HC-SR04 Ultrasonic Sensor with ESP32:

Connecting the Trig pin to GPIO 5 and the Echo pin to GPIO 18, but you can
use any other suitable pins.

Department of Information & Technology Page 36


INTERNET OF THINGS LAB

Installing the ESP32 Board in Arduino IDE:

There’s an add-on for the Arduino IDE that allows to program the ESP32
using the Arduino IDE and its programming language.

• In your Arduino IDE 2.0, go to File > Preferences.

• Copy and paste the following line to the Additional Boards Manager
URLs field.
o https://raw.githubusercontent.com/espressif/arduino-
esp32/gh-pages/package_esp32_index.json

Note: if you already have the ESP8266 boards URL, you can separate the
URLs with a comma, as follows:

Department of Information & Technology Page 37


INTERNET OF THINGS LAB

o http://arduino.esp8266.com/stable/package_esp8266com_i
ndex.json,

• Open the Boards Manager. You can go to Tools > Board > Boards
Manager… or you can simply click the Boards Manager icon in the
left-side corner

• Search for ESP32 and press the install button for esp32 by Espressif
Systems

Department of Information & Technology Page 38


INTERNET OF THINGS LAB

Uploading the Sketch:

• On the top drop-down menu, select the “unknown” board. A new


window, as shown below, will open.

You should select your ESP32 board model and the COM port. In our
example, we’re using the DOIT ESP32 DEVKIT V1 board. Click OK when
you’re done.

• Now, you just need to click on the Upload button

Department of Information & Technology Page 39


INTERNET OF THINGS LAB

• After a few seconds, the upload should be complete

SOURCE CODE

const int trigPin = 5; const int echoPin = 18;

//define sound speed in cm/uS #define SOUND_SPEED 0.034

#define CM_TO_INCH 0.393701

long duration;

float distanceCm;

float distanceInch;

void setup() {

Serial.begin(115200); // Starts the serial communication

pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

pinMode(echoPin, INPUT); // Sets the echoPin as an Input

void loop() {

// Clears the trigPin

digitalWrite(trigPin, LOW);

delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds

Department of Information & Technology Page 40


INTERNET OF THINGS LAB

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds

duration = pulseIn(echoPin, HIGH);

// Calculate the distance

distanceCm = duration * SOUND_SPEED/2;

// Convert to inches

distanceInch = distanceCm * CM_TO_INCH;

// Prints the distance in the Serial Monitor

Serial.print("Distance (cm): ");

Serial.println(distanceCm);

Serial.print("Distance (inch): ");

Serial.println(distanceInch);

delay(1000);

OUTPUT

Department of Information & Technology Page 41


INTERNET OF THINGS LAB

3 B. Basic LED functionality Using ESP-32 (Node MCU)

AIM: LED Blinking Using ESP-32 (Node MCU)

Components Required

• 1 X LED
• 1 X 100Ω Resistor
• Breadboard
• ESP32 Development Board.
• Jumper wires

LED

LEDs (Light Emitting Diodes) takes a voltage that is given to a PN Junction


Diode, electrons, and holes recombine in the PN Junction and release energy
in the form of light (Photons).

ESP32

The ESP32 is an advanced IoT microcontroller board possessing WiFi and


Bluetooth Low Energy capabilities, as well as limited compatibility with the
Arduino Core.

Blinking an LED

Blinking an LED in which we control an LED using ESP32. LED blinking


refers to the process of continuously turning an LED (Light Emitting Diode)
ON and OFF in a repetitive pattern.

Setup:

• Connect the negative pin (cathode) of the LED, indicated as the flat
edge of the LED to ground, shown as the blue wire.
• Connect the positive pin (anode) of the LED, indicated as the rounded
edge of the LED to a 100Ω resistor.
• Connect the free end of the resistor to pin D5 on the ESP32, shown as
the red wire

SOURCE CODE

const int ledPin = 5;

void setup() {
Department of Information & Technology Page 42
INTERNET OF THINGS LAB

// setup pin 5 as a digital output pin

pinMode (ledPin, OUTPUT);

void loop() {

digitalWrite (ledPin, HIGH); // turn on the LED

delay(500); // wait for half a second or 500 milliseconds

digitalWrite (ledPin, LOW); // turn off the LED

delay(500); // wait for half a second or 500 milliseconds

OUTPUT:

Department of Information & Technology Page 43


INTERNET OF THINGS LAB

3. C. Calculate Temperature Using ESP32 (Node MCU)

AIM: Calculate Temperature using Temperature Sensor Using ESP32


(Node MCU)

Components Required

• 1 X DHT11 Sensor
• 1 KΩ Pullup Resistor
• Breadboard
• ESP32 DevKit Development Board
• Jumper wires
• Micro USB Cable

DHT11 Sensor

DHT11 Module features a temperature & humidity sensor complex with a


calibrated digital signal output. DHT11 can measure temperature from 0°C
to 50°C with a ±2.0°C accuracy, and humidity from 20 to 80% with a 5%
accuracy.

DHT11 Module Pinout

The DHT11 module has a total of 3 pins. In which two are for power and one
is for communication. The pinout of a DHT11 Sensor module is as follows:

+(VCC) pin provides power to the sensor. Despite the fact that the supply
voltage of the module ranges from 3.3V to 5.5V, a 5V supply is
recommended. With a 5V power supply, the sensor can be placed up to 20
meters away. With 3.3V supply voltage, the sensor can be placed just 1
meter away; otherwise, the line voltage drop will cause measurement errors.

DATA pin is used for communication between the sensor and the
microcontroller.

Department of Information & Technology Page 44


INTERNET OF THINGS LAB

– (GND) is the ground pin.

Setup:

Connections are relatively simple.

• Begin by connecting the + (VCC) pin to the VIN of ESP32 Board.


• Now, the Data pin is connected to GPIO 16 of ESP32, which is labelled
as RX2 on the ESP32 DevKit Board
• The third pin is not connected to anything. Finally, the GND pin is
connected to any GND pin of ESP32.

Installing DHT library

The DHT sensors has their own proprietary single-wire data transfer
protocol. This protocol requires precise timing. using the DHT library, which
handles almost everything.

Its need to download a couple of libraries so that ESP32 will properly


communicate with DHT11 Sensor. First is main DHT11 Sensor Library.

• Go to Tools -> Manage Libraries… in Arduino IDE

In the search bar, enter ‘DHT’. Scroll through the options and install ‘DHT
sensor library’ by Adafruit.

Department of Information & Technology Page 45


INTERNET OF THINGS LAB

• The next library is associated with the Adafruit itself. Search for
‘adafruit unified’, scroll down and install ‘Adafruit Unified Sensor’
library.

SOURCE CODE:

#include "DHT.h"
#define DHT11PIN 16
DHT dht(DHT11PIN, DHT11);
void setup()
{
Serial.begin(115200);
/* Start the DHT11 Sensor */
dht.begin();
}

Department of Information & Technology Page 46


INTERNET OF THINGS LAB

void loop()
{
float humi = dht.readHumidity();
float temp = dht.readTemperature();
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print("ºC ");
Serial.print("Humidity: ");
Serial.println(humi);
delay(1000);
}

OUTPUT:

Department of Information & Technology Page 47


INTERNET OF THINGS LAB

4. INSTALLING OS ON RASPBERRY PI

Aim: Installation using image file

Required Components:

• Raspberry Pi Board
• USB power adapter like the official Raspberry Pi 4 power supply
• microSD card (at least 8GB, but preferably 16 or 32GB)
• USB card reader
• Keyboard (wired or perhaps one of the best wireless keyboards)
• Mouse
• Monitor or TV
• Micro HDMI to HDMI cable

Step 1: Set up your SD card

• If you have an SD card that doesn’t have the Raspberry Pi OS


operating system on it yet, or if you want to reset your Raspberry Pi,
to do so, you need a computer that has an SD card port — most
laptop and desktop computers have one.
• The Raspberry Pi OS operating system via the Raspberry Pi Imager
• Using the Raspberry Pi Imager is the easiest way to install Raspberry
Pi OS on your SD card.
• Download and launch the Raspberry Pi Imager
• Visit the Raspberry Pi downloads page

Department of Information & Technology Page 48


INTERNET OF THINGS LAB

• Click on the link for the Raspberry Pi Imager that matches your
operating system

• When the download finishes, click it to launch the installer


• When you launch the installer, your operating system may try to block
you from running it. For example, on Windows may receive the
following message:

• If this pops up, click on More info and then Run anyway
• Follow the instructions to install and run the Raspberry Pi Imager
• Insert your SD card into the computer or laptop SD card slot

Department of Information & Technology Page 49
INTERNET OF THINGS LAB

• In the Raspberry Pi Imager, select the OS that you want to install and
the SD card you would like to install it on

Note: You will need to be connected to the internet the first time for the
Raspberry Pi Imager to download the OS that you choose. That OS will then
be stored for future offline use. Being online for later uses means that the
Raspberry Pi imager will always give you the latest version.

• Select Raspberry Pi OS (32-bit) from the OS menu (there are


otherchoices, but for most uses, 32-bit is the best).

• Click Choose storage and pick the SD card you’re using

Department of Information & Technology Page 50


INTERNET OF THINGS LAB

• Click the settings button or hit CTRL + SHIFT + X to enter settings

• Fill in settings fields as follows and then hit Save. All of these fields
are technically optional, but highly recommended so that can get your
Raspberry Pi set up and online as soon as you boot it. If you don't set
a username and password here, you'll have to go through a setup
wizard that asks you to create them on first boot.
• Set hostname: the name of your Pi. It could be "raspberry pi" or
anything you like.
• Enable SSH: Allow SSH connections to the Pi. Recommended.
• Use password authentication / public key: method of logging in via
SSH
• Set username and password: Pick the username and password you'll
use for the Pi
Department of Information & Technology Page 51
INTERNET OF THINGS LAB

• Configure wireless LAN: set the SSID and password of Wi-Fi network
• Wireless LAN country: If you're setting up Wi-Fi, you must choose
this.
• Set locale settings: Configure keyboard layout and time zone (probably
chosen correctly by default)

• Then simply click the WRITE button


• Wait for the Raspberry Pi Imager to finish writing

• Once you get the following message, you can eject your SD card

Department of Information & Technology Page 52


INTERNET OF THINGS LAB

Step-2: Booting Your Raspberry Pi for the First Time

After you're done writing the Raspberry Pi OS to a microSD card, it's time for
the moment of truth.

• Insert the microSD card into the Raspberry Pi.


• Connect the Raspberry Pi to a monitor, keyboard and mouse.
• Connect an Ethernet cable if you plan to use wired Internet.
• Plug the Pi in to power it on.

Department of Information & Technology Page 53


INTERNET OF THINGS LAB

Step-3: Using the Raspberry Pi First-Time Setup Wizard

If you chose a username and password in Raspberry Pi Imager settings,


before writing the microSD card, you will get the desktop on first boot. But,
if you did not, you'll be prompted to create a username and password and
enter all the network credentials by a setup wizard on first boot. If that
happens, follow these steps to finish setting up your Raspberry Pi.

• Click Next on the dialog box.

• Set your country and language and click Next. The default choices
may already be the correct ones

• Enter a username and password you wish to use for your primary
login. Click Next

Department of Information & Technology Page 54


INTERNET OF THINGS LAB

• Toggle Reduce the size of the desktop" to on if the borders of the


desktop are cut off. Otherwise, just click Next.

• Select the appropriate Wi-Fi network on the screen after, provided that
you are connecting via Wi-Fi. If you don't have Wi-Fi or are using
Ethernet, you can skip this.

Department of Information & Technology Page 55


INTERNET OF THINGS LAB

• Enter your Wi-Fi password (unless you were using Ethernet and
skipped)

• Click Next when prompted to Update Software. This will only work
when you are connected to the Internet, and it can take several
minutes. If you are not connected to the Internet, click Skip.

• Click Restart

Department of Information & Technology Page 56


INTERNET OF THINGS LAB

If you wish to change these settings later, you can find the region and
password settings, along with many other options, by clicking on the Pi icon
in the upper left corner of the screen and navigating to Preferences ->
Raspberry Pi Configuration. You can configure Wi-Fi by clicking on the Wi-Fi
/ network icon on the taskbar

Department of Information & Technology Page 57


INTERNET OF THINGS LAB

5. INSTALLING GPIO ZERO LIBRARY ON RASPBERRY PI

5. A) AIM: Installing GPIO Zero Library on Raspberry PI

Required Components:

• Raspberry Pi Board with OS installed on it


• Keyboard
• Mouse
• Monitor
• Power Adapter
• Micro HDMI to HDMI Cable

Procedure:

GPIO Zero is installed by default in the Raspberry Pi OS desktop image, and


the Raspberry Pi Desktop image for PC/Mac, both available from
raspberrypi.org. Follow these guides to installing on Raspberry Pi OS Lite
and other operating systems.

• GPIO Zero is packaged in the apt repositories of Raspberry Pi OS,


Debian and Ubuntu

Using apt:

• First, update your repositories list:


o pi@raspberrypi:~$ sudo apt update
• Then install the package for Python 3
o pi@raspberrypi:~$ sudo apt install python3-gpiozero
• or Python 2
o pi@raspberrypi:~$ sudo apt install python-gpiozero

Using pip:

• First, install pip using get-pip and then type


o pi@raspberrypi:~$ sudo pip3 install gpiozero
• or for Python 2
o pi@raspberrypi:~$ sudo pip install gpiozero

Department of Information & Technology Page 58


INTERNET OF THINGS LAB

5. B) Blinking an LED connected to one of the GPIO Pin

AIM: Blinking an LED connected to one of the GPIO Pin using GPIO-
Zero

Required Components:

• Raspberry Pi Board with OS & GPIO Zero library installed on it


• One LED
• One Resistor (220 Ohm)
• M to F Jumper Wires
• Breadboard
• Keyboard
• Mouse
• Monitor
• Power Adapter
• Micro HDMI to HDMI Cable

Procedure:

• Attach the LED to the breadboard


• Attach Blue color jumper wire one end to long leg of LED and connect
other end to GPIO Pin number 6 (one of the Ground Pin) of Raspberry
Pi
• Attach 220 Ohm resistor to other free leg of LED
• Attach White color jumper wire one end to other free leg of resistor
and connect other end to GPIO Pin number 17 of Raspberry Pi
• Now connect Keyboard, Mouse, Monitor, and finally Power Adapter to
the Raspberry Pi
• Write the Python code by using Thonny IDE available in Programming
Tab
• Then Save the Code with .py extension in any location by clicking on
Save Option in IDE
• Finally Click on Run Option in IDE

Source Code:

from gpiozero import LED

from time import sleep led = LED(17)

Department of Information & Technology Page 59


INTERNET OF THINGS LAB

while True:

led.on()

sleep(1)

led.off()

sleep(1)

OUTPUT

Department of Information & Technology Page 60


INTERNET OF THINGS LAB

5. C) Controlling Brightness of LED using the in-built PWM of Raspberry


Pi

AIM: Controlling Brightness of LED (0 to 100 where 100 is the


maximum brightness) using the in-built PWM wavelength.

Required Components:

• Raspberry Pi 4 controller.
• Monitor/Laptop.
• And other connecting wires such as (Ethernet Cable, HDMI Cable, &
powering cable for both Raspberry Pi and Monitor, etc.)
• LED of any color.
• Jumper Wire.
• Bread-board.
• Resistor 100 Ohm

Process:

Controlling the brightness of an LED continually by-passing various delays


with PWM (Pulse Width Modulation), to control its brightness from 0 to 100
by applying PWM signal via Board pin 11

Connection:

• Attach the LED to the breadboard


• Attach Blue color jumper wire one end to long leg of LED and connect
other end to GPIO Pin number 6 (one of the Ground Pin) of Raspberry
Pi
• Attach 100 Ohm resistor to other free leg of LED
• Attach White color jumper wire one end to other free leg of resistor
and connect other end to GPIO Pin number 11 of Raspberry Pi
• Now connect Keyboard, Mouse, Monitor, and finally Power Adapter to
the Raspberry Pi
• Write the Python code by using Thonny IDE available in Programming
Tab
• Then Save the Code with .py extension in any location by clicking on
Save Option in IDE
• Finally Click on Run Option in IDE

Department of Information & Technology Page 61


INTERNET OF THINGS LAB

SOURCE CODE:

import RPi.GPIO as GPIO

import time

GPIO.setmode(GPIO.BOARD)

GPIO.setup(11, GPIO.OUT)

p = GPIO.PWM(11, 100) //11 is pin number and 100 is max range of PWM.

p.start(0) //Starting point of PWM signal you can select any value between 0
to 100.

while True:

for x in range (0, 100, 1): //Increasing brightness of LED from 0 to


100

p.ChangeDutyCycle(x)

time.sleep(0.1)

for x in range (100, 0, -1): //fading brightness of LED from 100 to 0

p.ChangeDutyCycle(x)

time.sleep(0.1)

OUTPUT:

Department of Information & Technology Page 62


INTERNET OF THINGS LAB

6. INTERFACING DHT SENSOR WITH RASPBERRY PI

AIM: Interfacing DHT Sensor with Raspberry PI

Components Required

• 1 X DHT11 Sensor
• Breadboard
• Raspberry Pi 4 Model B
• Jumper wires
• Power Supply
• Computer

DHT11 Sensor

DHT11 Module features a temperature & humidity sensor complex with a


calibrated digital signal output. DHT11 can measure temperature from 0°C
to 50°C with a ±2.0°C accuracy, and humidity from 20 to 80% with a 5%
accuracy.

DHT11 Module Pin-Out

The DHT11 module has a total of 3 pins. In which two are for power and one
is for communication. The pin-out of a DHT11 Sensor module is as follows:

+(VCC) pin provides power to the sensor. Despite the fact that the supply
voltage of the module ranges from 3.3V to 5.5V, a 5V supply is
recommended. With a 5V power supply, the sensor can be placed up to 20
meters away. With 3.3V supply voltage, the sensor can be placed just 1
meter away; otherwise, the line voltage drop will cause measurement errors.

DATA pin is used for communication between the sensor and the
microcontroller.

– (GND) is the ground pin.

Department of Information & Technology Page 63


INTERNET OF THINGS LAB

SETUP:

Connect the VCC and GND pins of the DHT11 Sensor to +5V and GND of
Raspberry Pi and then connect the Data OUT of the Sensor to the GPIO4 i.e.
Physical Pin 7 of the Raspberry Pi.

Installing DHT library using Adafruit_DHT library

Here we are using a library called Adafruit_DHT provided by Adafruit for


installing; we need to first install this library into Raspberry Pi.

• First step is to download the library from GitHub. Enter the following
command to download the files related to the Adafruit_DHT library

o git clone https://github.com/adafruit/Adafruit_Python_DHT.git

• All the contents will be downloaded to a folder called ‘Adafruit_Python


_DHT’. Open this directory using cd Adafruit_Python_DHT. To see the
contents of this folder, use ‘ls’ command.

• In that folder, there is file called ‘setup.py’. We need to install this file
using the following command.

o sudo python setup.py install

Department of Information & Technology Page 64


INTERNET OF THINGS LAB

SOURCE CODE

import sys

import Adafruit_DHT

import time

while True:

humidity, temperature = Adafruit_DHT.read_retry(11, 4)

print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature,


humidity)

time.sleep(1)

OUTPUT:

Department of Information & Technology Page 65


INTERNET OF THINGS LAB

ADDITIONAL EXPERIMENTS

TRAFFIC LIGHT SYSTEM USING ARDUINO

Components Required

• Jumper wires
• 5 mm LED: Red
• 5 mm LED: Green
• Breadboard (generic)
• Arduino UNO
• 5 mm LED: Yellow
• Arduino IDE

Working

The LED have been powered by Arduino UNO (Board). It contains a code
which uploaded to the board. And once it simulated LED Start's blinking
like a traffic light. In this 15 Second will for Red Light 6 Second for Yellow
Light (In my Project Blue) and 20 Second for Green Light.

Connections

• Hook the GND pin (Negative Pin) of all led to Pin GND of Arduino.
• Connect Red LED VCC Pin (Positive Pin) to Pin 9 of Arduino.
• Connect Yellow LED VCC Pin (Positive Pin) to Pin 8 of Arduino.
• Connect Green LED VCC Pin (Positive Pin) to Pin 7 of Arduino

SOURCE CODE:

int red = 9;

int yellow = 8;

int green = 7;

void setup(){

pinMode(red, OUTPUT);

pinMode(yellow, OUTPUT);

pinMode(green, OUTPUT);

Department of Information & Technology Page 66


INTERNET OF THINGS LAB

void loop(){

digitalWrite(red, HIGH);

delay(15000);

digitalWrite(red, LOW);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

Department of Information & Technology Page 67


INTERNET OF THINGS LAB

digitalWrite(green, HIGH);

delay(20000);

digitalWrite(green, LOW);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

digitalWrite(yellow, HIGH);

delay(1000);

digitalWrite(yellow, LOW);

delay(500);

Department of Information & Technology Page 68


INTERNET OF THINGS LAB

OUTPUT:

Department of Information & Technology Page 69


INTERNET OF THINGS LAB

INTEGRATION OF SERVO MOTOR WITH ARDIUNO


COMPONENTS REQUIRED

• An Arduino board connected to a computer via USB


• A servo motor
• Jumper wires

SERVO MOTOR

Servo motors are devices that can turn to a specified position. Usually, they
have a servo arm that can turn 180 degrees. Using the Arduino, if we specify
a servo to go to a specified position and it will go there.

Servo motors were first used in the Remote Control (RC) world, usually to
control the steering of RC cars or the flaps on a RC plane. With time, they
found their uses in robotics, automation

A servo motor has everything built in: a motor, a feedback circuit, and most
important, a motor driver. It just needs one power line, one ground, and one
control pin

CONNECTIONS

• The servo motor has a female connector with three pins. The darkest
or even black one is usually the ground. Connect this to the Arduino
GND.
• Connect the power cable that in all standards should be red to 5V on
the Arduino.
• Connect the remaining line on the servo connector to a digital pin on
the Arduino

The following code will turn a servo motor to 0 degrees, wait 1 second, then
turn it to 90, wait one more second, turn it to 180, and then go back.

SOURCE CODE

#include <Servo.h> // Include the Servo library

int servoPin = 3; // Declare the Servo pin

Servo Servo1; // Create a servo object

void setup () {
Department of Information & Technology Page 70
INTERNET OF THINGS LAB

Servo1.attach(servoPin); // We need to attach the servo to the used


pin number

void loop () {

Servo1.write(0); // Make servo go to 0 degrees

delay (1000);

Servo1.write(90); // Make servo go to 90 degrees

delay (1000);

Servo1.write(180); // Make servo go to 180 degrees

delay (1000);

OUTPUT

Department of Information & Technology Page 71

You might also like