FIOT Unit-4

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

FUNDAMENTALS OF INTERNET OF

THINGS
UNIT-3

Introduction to Python programming


Python is developed by Guido van Rossum. Guido van Rossum started implementing Python in 1989
Interesting fact: Python is named after the comedy television show Monty Python’s Flying Circus. It
is not named after the Python snake.

Python is a general-purpose high level programming language and suitable for providing a
solid foundation to the reader in the area of cloud computing.

The main characteristics of Python are:


1) Multi-paradigm programminglanguage.
2) Python supports more than one programming paradigms including object- oriented
programming and structured programming.
3) InterpretedLanguage.
4) Python is an interpreted language and does not require an explicit compilationstep.
5) The Python interpreter executes the program source code directly, statement by
statement, as a processor or scripting engine does.
6) Interactive Language
7) Python provides an interactive mode in which the user can submit commands at the
Python prompt and interact with the interpreterdirectly.

Python
Benefits

Python - Setup
Datatypes

Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes.

There are various data types in Python. Some of the important types are listed below.

Python Numbers

Integers, floating point numbers and complex numbers falls under Python numbers category.
They are defined as int, float and complex class in Python. We can use the type() function to
know which class a variable or a value belongs to and the isinstance() function to check if an
object belongs to a particular class.

Script.py

1. a = 5

2. print(a, "is of type", type(a))

3. a = 2.0

4. print(a, "is of type", type(a))

5. a = 1+2j

6. print(a, "is complex number?", isinstance(1+2j,complex))

Integers can be of any length, it is only limited by the memory available. A floating point
number is accurate up to 15 decimal places. Integer and floating points are separated by decimal
points. 1 is integer, 1.0 is floating point number. Complex numbers are written in the form, x +
yj, where x is the real part and y is the imaginary part. Here are someexamples.

>>> a = 1234567890123456789

>>> a

1234567890123456789

>>> b = 0.1234567890123456789

>>> b

0.12345678901234568
>>> c = 1+2j

>>> c

(1+2j)

Python List

List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type. Declaring a list is pretty
straight forward. Items separated by commas are enclosed within brackets [].

>>> a = [1, 2.2, 'python']

We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts
form 0 in Python.

Script.py
1. a = [5,10,15,20,25,30,35,40]
2. # a[2] = 15
3. print("a[2] = ", a[2])
4. # a[0:3] = [5, 10, 15]
5. print("a[0:3] = ", a[0:3])
6. # a[5:] = [30, 35, 40]
7. print("a[5:] = ", a[5:])

Lists are mutable, meaning; value of elements of a list can be altered.


>>> a = [1,2,3]
>>> a[2]=4
>>> a
[1, 2, 4]

Python Tuple
Tuple is an ordered sequences of items same as list. The only difference is that tuples are
immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and
are usually faster than list as it cannot change dynamically. It is defined within parentheses ()
where items are separated bycommas.

>>> t = (5,'program', 1+3j)

Script.py
t = (5,'program', 1+3j)
# t[1] = 'program'
print("t[1] = ", t[1])
# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])
# Generates error
# Tuples are immutable
t[0] = 10

Python Strings
String is sequence of Unicode characters. We can use single quotes or double quotes to represent
strings. Multi-line strings can be denoted using triple quotes, ''' or """.

>>> s = "This is a string"


>>> s = '''a multiline

Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
Script.py

a ={5,2,3,1,4}
# printing setvariable
print("a = ", a)
# data type of variable a
print(type(a))

We can perform set operations like union, intersection on two sets. Set have unique values. They
eliminate duplicates. Since, set are unordered collection, indexing has no meaning. Hence the
slicing operator [] does not work. It is generally used when we have a huge amount of data.
Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In
Python, dictionaries are defined within braces {} with each item being a pair in the
form key:value. Key and value can be of anytype.

>>> d = {1:'value','key':2}

>>> type(d)

<class 'dict'>

We use key to retrieve the respective value. But not the other way around.

Script.py
d ={1:'value','key':2}
print(type(d))
print("d[1] = ",d[1]);
print("d['key'] = ", d['key']);
# Generates error
print("d[2] = ",d[2]);

Python if...else Statement

Every value in Python has a datatype. Since everything is an object in Python programming, data
types are actually classes and variables are instance (object) of these classes. Decision making is
required when we want to execute a code only if a certain condition is satisfied.

The if…elif…else statement is used in Python for decision making.

Python if Statement

Syntax

if test expression:
statement(s)

Here, the program evaluates the test expression and will execute statement(s) only if the text
expression is True.
If the text expression is False, the statement(s) is not executed. In Python, the body of
the if statement is indicated by the indentation. Body starts with an indentation and the first
unindented line marks the end. Python interprets non-zero values as True. None and 0 are
interpreted as False.

Python if Statement Flowchart


Example: Python if Statement

# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num >0:
print(num, "is a positive number.")
print("This is also always printed.")

When you run the program, the output willbe:


3 is a positivenumber
This is alwaysprinted
This is also always printed.

In the above example, num > 0 is the test expression. The body of if is executed only if this
evaluates to True.
When variable num is equal to 3, test expression is true and body inside body of if is executed. If
variable num is equal to -1, test expression is false and body inside body of if is skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless
of the testexpression.

Python if...else Statement

Syntax

if test expression:
Body of if
else:
Body of else

The if..else statement evaluates test expression and will execute body of if only when test
condition is True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.

Python if..else Flowchart

Example of if...else

# Program checks if the number is positive or negative


# And displays an appropriate message
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
In the above example, when num is equal to 3, the test expression is true and body of if is
executed and body of else is skipped.

If num is equal to -5, the test expression is false and body of else is executed and body of if is
skipped.

If num is equal to 0, the test expression is true and body of if is executed and body of else is
skipped.
Python if...elif...else Statement

Syntax

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

The elif is short for else if. It allows us to check for multiple expressions. If the condition
for if is False, it checks the condition of the next elif block and so on. If all the conditions
are False, body of else is executed. Only one block among the several if...elif...else blocks is
executed according to the condition. The if block can have only one else block. But it can have
multiple elifblocks.

Flowchart of if...elif...else

Example of if...elif...else

# In this program,
# we check if the number is positive or
# negative or zero and
# display an appropriate message
num = 3.4
# Try these two variations as well:
# num = 0
# num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

When variable num is positive, Positive number is printed.

If num is equal to 0, Zero is printed.


If num is negative, Negative number is printed

Python Nested if statements

We can have a if...elif...else statement inside another if...elif...else statement. This is called
nesting in computer programming. Any number of these statements can be nested inside one
another. Indentation is the only way to figure out the level of nesting. This can get confusing, so
must be avoided if we can.

Python Nested if Example

# In this program, we input a number


# check if the number is positive or
# negative or zero anddisplay
# an appropriate message
# This time we use nested if

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1

Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Output 3
Enter a number: 0
Zero

Python for Loop


The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called traversal.
Syntax of for Loop
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Flowchart of for Loop

Syntax
# Program to find the sum of all numbers stored in a list
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
# variable to store the sum
sum = 0

# iterate over the list


for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)

when you run the program, the output will be:


The sum is 48

The range() function


We can generate a sequence of numbers using range() function. range(10) will generate numbers
from 0 to 9 (10 numbers). We can also define the start, stop and step size as range(start,stop,step
size). step size defaults to 1 if not provided. This function does not store all the values in emory,
it would be inefficient. So it remembers the start, stop, step size and generates the next number
on thego.
To force this function to output all the items, we can use the function list().
The following example will clarify this.
# Output: range(0, 10)
print(range(10))
# Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
# Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
# Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))
We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an
example.

# Program to iterate through a list using indexing


genre = ['pop', 'rock', 'jazz']
# iterate over the list using index
for i in range(len(genre)):
print("I like", genre[i])

When you run the program, the output will be:


I likepop
I likerock
I likejazz

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true. We generally use this loop when we don't know beforehand, the number of
times to iterate.

Syntax of while Loop in Python

while
test_expression:
Body of while

In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression evaluates to True. After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False. In Python, the body of the while
loop is determined through indentation. Body starts with indentation and the first unindented line
marks the end. Python interprets any non-zero value as True. None and 0 are interpreted asFalse.

Introduction to Raspberry Pi
: Raspberry Pi
Raspberry Pi is a low-cost mini-computer with the physical size of a credit card. Raspberry Pi runs various flavors of
Linux and can perform almost all tasks that a normal desktop computer can do. Raspberry Pi also allows interfacing
sensors and actuators through the general purpose
I/O pins. Since Raspberry Pi runs Linux operating system, it supports Python "out of the box". Raspberry Pi is a
low-cost mini-computer with the physical size of a credit card. Raspberry Pi runs various flavors of Linux and can
perform almost all tasks that a normal desktop computer can do. Raspberry Pi also allows interfacing sensors and
actuators through the general purpose I/O pins. Since Raspberry Pi runs Linux operating system, it supports Python
"out of the box".

Raspberry Pi

Linux on Raspberry Pi

1. Raspbian: Raspbian Linux is a Debian Wheezy port optimized for RaspberryPi.


2. Arch: Arch is an Arch Linux port for AMDdevices.
3. Pidora: Pidora Linux is a Fedora Linux optimized for RaspberryPi.
4. RaspBMC: RaspBMC is an XBMC media-center distribution for RaspberryPi.
5. OpenELEC: OpenELEC is a fast and user-friendly XBMC media-centerdistribution.
6. RISC OS: RISC OS is a very fast and compact operatingsystem.

Raspberry Pi GPIO
Raspberry Pi Interfaces

1. Serial: The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins for
communication with serialperipherals.
2. SPI: Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for
communicating with one or more peripheraldevices.
3. I2C: The I2C interface pins on Raspberry Pi allow you to connect hardware modules.
I2C interface allows synchronous data transfer with just two pins - SDA (data line) and
SCL (clockline).

Raspberry Pi Example: Interfacing LED and switch with Raspberry Pi

from time import sleeP import

RPi.GPIO asGPIO

GPIO.setmode(GPIO.BCM)

#Switch Pin GPIO.setup(25,GPIO.IN)

#LEDPin

GPIO.setup(18,GPIO.OUT)

state=false
deftoggleLED(pin):

state = not state

GPIO.output(pin,state)
whileTrue:

try:
if (GPIO.input(25) ==True):

toggleLED

exceptKeyboardInterrupt:

exit()

Interfacing Raspberry Pi with basic peripherals

How to Interface a Push Button with Raspberry Pi

In this project, we will see how to connect a simple Push Button to Raspberry Pi and how
to accept input from the GPIO Pins of Raspberry Pi. Interfacing a Push Button with
Raspberry Pi is very easy and the idea behind the project is to understand the concepts
behind the interface
Outline

• Overview
• GPIO of Raspberry Pi as Input
• Basics of Push Button
• Interfacing a Push Button with Raspberry Pi
• Circuit Diagram
• Components Required
• Circuit Design
• Code
• Working
• Applications

Overview

As I have already mentioned in the How to Blink an LED using Raspberry Pi and Python Project, the GPIO
pins of the Raspberry Pi is an important feature as they enable the Raspberry Pi to interface with external
Physical Components like LEDs, Motors, Buttons, etc.

The GPIO Pins or General Purpose Input Output Pins, as the name suggests, can be configured as either
Output Pin or an Input Pin.

If it is setup as an Output Pin, like in case of the LED Blinking Tutorial, the GPIO Pin drives an Output
Device like an LED. On the contrary, if the GPIO Pin is configured as an Input Pin, it will read the
incoming data from an external device, like a Button, in this scenario.

Before continuing, read HOW TO BLINK AN LED USING RASPBERRY PI?

GPIO of Raspberry Pi as Input

From the above statements, it is clear that if the Raspberry Pi wants to read the value from an external
device, the corresponding GPIO pin must be declared as an Input Pin.

But when a GPIO Pin of the Raspberry Pi is declared as Input, it must be ‘tied’ to High or Low or else it is
called as a Floating Input Pin. A Floating Input is a pin which is defined as input and left as it is.

Any Digital Input Pin is very sensitive and catches even the slightest changes and will pick up the stray
capacitances from your finger, breadboard, air etc.

In order to avoid this, a Digital Input Pin must be tied to VCC or GND with the help of Pull-up or Pull-
down resistors.
The following image shows an input pulled High and Low with the help of pull-up and pull-down resistors.
In case of pull-up, the input will always read HIGH and when the button is pushed, it will read LOW.

n contrast, when an input pin is pulled-down, it will always read LOW and when the button is pressed, it
will read HIGH.

This type of setup ensures that you can take reliable readings from the Switch or Button. Make sure that pin
is not set as Output and pulled-High or pulled-Low as you might make a serious damage to the pins.

Basics of Push Button


Push Button is simplest of devices and it is the basic input device that can be connected to any controller or
processor like Arduino or Raspberry Pi.

A push button in its simplest form consists of four terminals. In that, terminals 1 and 2 are internally
connected with each other and so are terminals 3 and 4. So, even though you have four terminals,
technically, you have only two terminals to use.
The above image shows a simple pushbutton and also highlights the internal connection.

Interfacing a Push Button with Raspberry Pi

As mentioned in the “GPIO as Input” section, when a GPIO pin is declared as Input, it must be connected to
VCC or GND with the help of either a Pull-up resistor or a Pull-down resistor.

But, modern boards like Arduino and Raspberry Pi have a feature of Internal Pull-up or Internal Pull-down.
With the help of this feature, you need not physically connect a pull-up or pull-down resistor to the input
pin but configure it using the software.

Using this feature, the Pin will be pulled-High or Low from the inside of the chip.

While defining a GPIO pin of the Raspberry Pi as Input, add an additional statement in the program to
activate the internal pull-up or pull-down.

In this project, by interfacing a Push Button with Raspberry Pi, we will read the status of the Input Pin and
accordingly, turn ON or OFF an LED.

Circuit Diagram
The following images show the circuit diagram of the Raspberry Pi Push Button Interface. The first image
is based on the Fritzing Parts.
To get a clearer picture of the connections, the following wiring diagram from Fritzing will be helpful.
Components Required
• Raspberry Pi
• Push Button
• 5mm LED
• 100Ω Resistor (1/4 Watt)
• Mini Breadboard
• Connecting Wires
• Power Supply

Circuit Design
First, instead of using a four terminal push button, I have used a two terminal push button. This won’t make
any difference. One terminal of the push button is connected to GND and the other terminal is connected to
Physical Pin 16 (GPIO23) of Raspberry Pi.

A 5mm LED is used as an output device. The anode of the LED (long lead) is connected to Physical Pin 18
(GPIO24) of Raspberry Pi. The cathode of the LED (short lead) is connected to one terminal of a 100Ω
Resistor.

The other terminal of the Resistor is connected to GND.


Code
Python is used as the programming language for this project. The Python Script is given below.

import
RPi.GPIO
as GPIO
import time
button = 16
led = 18
def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led, GPIO.OUT)
def loop():
while True:
button_state = GPIO.input(button)
if button_state == False:
GPIO.output(led, True)
print('Button Pressed...')
while GPIO.input(button) == False:
time.sleep(0.2)
else:
GPIO.output(led, False)
def endprogram():
GPIO.output(led, False)
GPIO.cleanup()
if __name__ == '__main__':

setup()

try:
loop()

except KeyboardInterrupt:
print 'keyboard interrupt detected'
endprogram()

import RPi.GPIO as GPIO


import time

button = 16
led = 18

def setup():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(led, GPIO.OUT)

def loop():
while True:
button_state = GPIO.input(button)
if button_state == False:
GPIO.output(led, True)
print('Button Pressed...')
while GPIO.input(button) == False:
time.sleep(0.2)
else:
GPIO.output(led, False)

def endprogram():
GPIO.output(led, False)
GPIO.cleanup()

if __name__ == '__main__':

setup()

try:
loop()

except KeyboardInterrupt:
print 'keyboard interrupt detected'
endprogram()

Working

The working of Raspberry Pi Push Button interface is very easy to understand. When the Python script is
run, the Raspberry Pi initializes the Button Pin as input with internal pull-up and LED Pin as output.

Now, it waits for a change in state of the Input pin, which happens only when the button is pressed. If the
button is pushed, Raspberry Pi will detect a LOW on the corresponding pin and activates the LED.

Applications
• Interfacing a Push Button with Raspberry Pi might not seem as a big project but it definitely helps
us in understanding the concept of reading from Input pins.
• A similar concept can be applied to other input devices like different types of Sensors (PIR Sensor,
Ultrasonic Sensor, Touch Sensor, and so forth).
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Implementation of IoT with Raspberry Pi

Raspberry Pi 2 IoT: Thingspeak & DHT22 Sensor


Display temperature and humidity data in real-time using a Raspberry Pi 2, a DHT22 sensor and the ThingSpeak IoT
platform.

Things used in this project


Hardware components

Raspberry Pi 2 Model B × 1

DHT22 Temperature Sensor × 1

Breadboard (generic) × 1

10kΩ Resistor × 1

Male/Female Jumper Wires × 3


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Introduction
This project uses a Raspberry Pi 2 to collect temperature and humidity data from a DHT22 sensor,
which is then uploaded to the ThingSpeak Internet of Things platform to be displayed in real-time.

This write-up is primarily intended to serve as documentation for the project, but may also be of
use as a tutorial for others. It assumes a beginner skill level and that you are running the Raspberry
Pi without a screen (referred to as a headless setup). It is broken into three main parts, with an
optional fourth:

• Part 1: Setting up the Raspberry Pi 2

• Part 2: Configuring the Adafruit DHT22 Sensor

• Part 3: Getting Started with ThingSpeak

• Part 4: Running an Email Notification Script (Optional)

Part 1: Setting up the Raspberry Pi 2


The instructions provided below are for Mac OSX. Instructions for other operating systems can be
found in the official documentation for the Raspberry Pi
(RPi): https://www.raspberrypi.org/documentation/

Step 1. Download Operating System Image

Download the latest Raspbian "lite" image from: https://www.raspberrypi.org/downloads/raspbian/

After downloading the .zip file, unzip it to get the image file (.img) that will be written to the
micro SD card.

Step 2. Write Image to SD Card

In order to locate the disk identifier of your SD card (e.g. disk4), open a terminal and run:
diskutil list

Using this disk identifier, unmount the SD card to prepare for copying data to it:
diskutil unmountDisk /dev/disk<disk# from diskutil>
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Copy the data to your SD card:


sudo dd bs=1m if=image.img of=/dev/rdisk<disk# from diskutil>

Where image.img is the filename of the latest Raspian image, e.g.:


sudo dd bs=1m if=2016-09-23-raspbian-jessie-lite.img of=/dev/rdisk<disk# from diskutil>

Insert the SD card to the Raspberry Pi, and provide power using either a micro USB cable or DC
adapter.

Update

A much simpler method of writing the image to an SD card is to use the program Etcher. It can be
downloaded from: https://etcher.io/

Once the program is opened, all you need to do is select the image, confirm the SD card drive, and
hit Flash! Voila! You're all done.

Etcher

Step 3: Enabling SSH

The most recent Raspbian releases (Dec 2016 onwards) have SSH disabled by default. To enable
SSH, you must create a new file called "ssh" on the SD card. It is important to make sure your file
doesn't have an extension like .txt, etc.

In macOS you can easily create this file by opening up a Terminal window and typing:
touch ssh
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Next, drag and drop this extensionless file into the root directory of your SD card and you're done!
When the Raspberry Pi boots up, it will detect the SSH file and enable access.

Step 4: Configure the Raspberry Pi

On a headless setup, the command line of the Raspberry Pi can be accessed remotely from another
computer or device on the same network using SSH (Secure Shell).

In this case, the RPi is connected to the local network via ethernet, and Internet Sharing is enabled.
Instructions on how to enable Internet Sharing are listed below:

• Open Sharing preferences (choose Apple menu > System Preferences, then click Sharing).

• Select the Internet Sharing checkbox.

• Click the “Share your connection from” pop-up menu, then choose Wi-Fi as the Internet
connection you want to share.

• Select how you want to share your Internet connection to the Raspberry Pi in the “To
computers using” list. In this case, the Internet connection will be shared over Ethernet.

Once connected via ethernet, the RPi will typically bind to an IP address in the 192.168.2.* range.
You can find its IP by using Nmap to scan the local network. An active IP address with an open
port 22 (SSH connects via this port) is your likely target.
nmap 192.168.2.*

• Note: If required, install Nmap using Homebrew:


/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install nmap

Once the local IP address of the RPi has been found, open terminal and establish an SSH
connection using the default username/password combination of "pi" and "raspberry":
ssh pi@192.168.2.#
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

• Note: If you encounter the warning: "WARNING: REMOTE HOST IDENTIFICATION HAS
CHANGED!", you simply need to clear out the known_hosts file. Run the following code and
remove the line of code pertaining to the IP address associated with the RPi.
sudo nano /Users/<username>/.ssh/known_hosts

Step 5: Update the Raspberry Pi

Upon first login to SSH, it is suggested to update/upgrade the Raspberry Pi using the following
commands:
sudo apt-get update
sudo apt-get dist-upgrade
df -h #to check space
sudo apt-get clean #to removed archived .deb files

If you would like to change default password for pi user, you can access the Raspberry Pi Software
Configuration Tool by running the command below and selecting option 2:
sudo raspi-config

raspi-config Configuration Tool

Step 6: Setting up Wifi

Official guide: https://www.raspberrypi.org/documentation/configuration/wireless/wireless-cli.md

If you intend to have the RPi connect to the Internet using a wireless USB dongle, you must enter
the details of your wifi connection in the wpa_supplicant.conf file.

To do so, run:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Then enter the details in the following format:


network={
ssid="ESSID"
psk="Your_wifi_password"
}

If you' like your Raspberry Pi to roam and connect to open networks, append the following to
your wpa_supplicant.conf:
network={
key_mgmt=NONE
priority=-999
}

Finally, reboot your Raspberry Pi and discover its new IP address using Nmap, or by logging into
your router and searching for the IP address associated with the "raspberrypi" hostname. Over a
Wi-Fi connection, the RPI will usually bind to an address within the 192.168.1.* range.
sudo reboot
ssh pi@192.168.1.*

Part 2: Configuring the Adafruit DHT22 Sensor


The DHT22 is a basic, low-cost digital temperature and humidity sensor, which uses a capacitive
humidity sensor and a thermistor to measure the surrounding air and output a digital signal on the
data pin.

Step 1: Wiring Diagram

As shown in the diagram below, the DHT22 requires Pin 1 to be connected to a 3.3V source, Pin 2
to the desired General-purpose input/output (GPIO) pin on the RPi, and Pin 4 to ground (GND). A
10kΩ resistor is placed between Pin 1 and Pin 2. Pin 3 in not used.
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

DHT22 Wiring Diagram

By examining the GPIO header in the figure below, we are able to determine that the
corresponding connections on the Raspberry Pi are as follows:

• Pin 1: 3.3 V

• Pin 6: GND

• Pin 16: GPIO 23 (other GPIO pins can be selected)


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Raspberry Pi 2 GPIO header pinout diagram. Source: pinout.xyz

With the correct pins identified, the circuit can be physically built and may end up looking similar to the diagram
below:

Breadboard wiring diagram of the DHT22 sensor and Raspberry Pi 2


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Step 2: Download the Adafruit DHT Library

With the wiring complete, the next step is to download Adafruit’s DHT library to the RPi, which is
required to read the temperature values from the sensor. This also requires that we first download
some Python and git packages:
sudo apt-get install python-dev
sudo apt-get install python-pip
sudo apt-get install git
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
sudo python setup.py install

Once the DHT library is installed, the next step is to write the script to gather the data from the
sensors and upload it to the Internet. To accomplish this, we will utilize the ThingSpeak Internet of
Things platform.

Part 3: Getting Started with ThingSpeak


Official guide: https://www.mathworks.com/help/thingspeak/getting-started-with-thingspeak.html

ThingSpeak is an Internet of Things (IoT) platform enabling the collection, storage, analysis, and
visualization of data gathered from sensors such as the Arduino and Raspberry Pi.

ThingSpeak stores data in Channels, each of which can have up to 8 data fields, as well as location
and status fields. Data can be sent to ThingSpeak at a rate of at every 15 seconds or longer.

ThingSpeak Configuration

Step 1. Sign up for new User Account

• http://thingspeak.com/users/sign_up

Step 2. Create a new Channel

• Select "Channels", "My Channels", and then "New Channel".

Step 3: Enter Channel Information


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

• Name: Raspberry Pi + DHT22 Temperature & Humidity Sensor

• Description: DHT22 temperature & humidity sensor driven by a Raspberry Pi 2 running a Python
script.

• Field 1: Humidity (%)

• Field 2: Temperature (°C)

Step 4: Record Write API Key

• Once the Channel is created, click on "API Keys" and note down the "Write API Key". We will use
this value later in our script.

Step 5: Script Creation

Create a folder in the /home/pi directory on the Raspberry Pi, then an empty Python script file by
running:
mkdir ThingSpeak
cd ThingSpeak
sudo nano dht22.py

Next, copy the code listed below (or from the attached dht22.py at the end of this tutorial). Enter
your API code to the "myAPI" variable. Press Ctrl+X to exit the editor, and select "Y" to save the
file when prompted.
"""
dht22.py
Temperature/Humidity monitor using Raspberry Pi and DHT22.
Data is displayed at thingspeak.com
Original author: Mahesh Venkitachalam at electronut.in
Modified by Adam Garbo on December 1, 2016
"""
import sys
import RPi.GPIO as GPIO
from time import sleep
import Adafruit_DHT
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504
import urllib2
myAPI = "<your API code here>"
def getSensorData():
RH, T = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 23)
return (str(RH), str(T))
def main():
print 'starting...'
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
try:
RH, T = getSensorData()
f = urllib2.urlopen(baseURL +
"&field1=%s&field2=%s" % (RH, T))
print f.read()
f.close()
sleep(300) #uploads DHT22 sensor values every 5 minutes
except:
print 'exiting.'
break
# call main
if __name__ == '__main__':
main()

Next, to test whether the script runs properly, you can use the following code:
sudo python dht22.py

If successful, you should see two lines as shown below:


pi@raspberrypi:~/ThingSpeak $ python dht22.py
starting...
5

In this case, the number "5" represents the entry made in the ThingSpeak channel. This will
increment each time the script uploads data.

Step 6: Running the Script at Startup


KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

If you plan on having your Raspberry Pi run automatically, a good idea is to have it start when the
RPi is powered on. One method of doing so is to add a cron job. The command below will start the
script and make the status outputs be directed to “null” (i.e. ignored), which ensures it runs in the
background. It will also check every 5 minutes to see if the script is running, and restart it if
necessary.
crontab -e
*/5 * * * * pgrep -f dht22.py || nohup python /home/pi/ThingSpeak/dht22.py > test.out

Another method of ensuring that the script is always running is to take the command from above,
enter it into its own script add a cron job that will periodically check and restart the script if
necessary. This can be accomplished by adding the following cronjob task and using
the check_script.sh file attached to this project:
crontab -e
*/5 * * * * sh /home/pi/ThingSpeak/script_check.sh &>/dev/null

More discussion on restarting a script can be found


here: http://unix.stackexchange.com/questions/107939/how-to-restart-the-python-script-
automatically-if-it-is-killed-or-dies

• Note: If you are using Sublime Text to edit your code, make sure to not re-indent using tabs, as
it may break Python's structure and render the script inoperable.

Step 7: Verify ThingSpeak Channel Data Uploads

If your script is working as intended, you should be able to see data uploading in real time. You
can increase the frequency at which the script uploads data to verify it is working properly, rather
than waiting the default 5 minutes.

ThingSpeak has a number of customizable features for the way the data is displayed, which you
can read more about here:

https://www.mathworks.com/help/thingspeak/create-a-chart.html
KG Reddy College of Engineering & Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Chilkur (Village), Moinabad (Mandal), R. R Dist, TS-501504

Example of temperature & humidity data being uploaded to a ThingSpeak channel.

You might also like