Professional Documents
Culture Documents
IoT Lab MANUAL - R20 Regulations - VCE - 17-8-22
IoT Lab MANUAL - R20 Regulations - VCE - 17-8-22
IoT Lab MANUAL - R20 Regulations - VCE - 17-8-22
Week-1
Experiment 1: Read your name and print Hello message with name using Python
Programming
Experiment 2: Read two numbers and print their sum, difference, product and
division using Python Programming
Experiment 3: Word and Characters and Space count of a given string using
Python Programming
Week-2
Experiment 5: Print name n times where name and n are read from standard input
using WHILE loops using Python Programming
Experiment 6: Print name n times where name and n are read from standard input
using FOR loop using Python Programming
Experiment 8: Print current time for 10 times with an interval of 10 seconds using
Python Programming
1
Week-3
Experiment 9: Read a file line by line and print the word count of each line using
Python Programming
Week-4
Experiment 14: IR Sensor to Detect Object with LED using Raspberry Pi3
Week-5
Experiment 16: PIR Sensor Motion Detection (Cloud Based) using Raspberry Pi3
Week-6
Experiment 17: DHT11 Temperature & Humidity Sensor using Raspberry Pi3
Experiment 18: DHT11 Temperature & Humidity Sensor (Cloud Based) using
Raspberry Pi3
Week-7
Experiment 19: Temperature & Humidity of CPU Data (Cloud Based) using
Raspberry Pi3
Week-8
Experiment 22: Ph Sensor for detect moisture levels in soil using Raspberry Pi3
2
Week-9
Experiment 23: Implement an Intruder system that sends an alert to the given E-
mail using Raspberry Pi
Week-10
Experiment 24: Get an alarm from a remote area (through LAN) if smoke is
detected.
Week-11
Week-12
Week-13
3
IOT LAB EXPERIMENTS
Week-1
Experiment 1: Read your name and print Hello message with name using
Python Programming
$sudo nano hello.py
print("Hello", name)
Hello "subrahmanyam"
Experiment 2: Read two numbers and print their sum, difference, product
and division using Python Programming
$sudo nano ASMD.py
#SUBTRACTION
x = int(input("Enter a first number"))
y = int(input("Enter a second number"))
print("The subtraction of these 2 numbers=", x - y,"\n")
#MULTIPLICATION
x = int(input("Enter a first number"))
y = int(input("Enter a second number"))
print("The multiplication of these 2 numbers=", x * y,"\n")
#DIVISION
x = int(input("Enter a first number"))
y = int(input("Enter a second number"))
print("The DIVISION of these 2 numbers=", x / y,"\n")
4
$sudo python3 ASMD.py
Experiment 3: Word and Characters and Space count of a given string using
Python Programming
$sudo nano WCP.py
wordCount=0
charCount=0
wordCount=len(split_str)
charCount+=len(word)
print("Total words in the given string ",wordCount)
print("Total characters in the given string ",charCount)
print("Number of space in the given string ",(wordCount-1))
5
Experiment 4: Area of a given shape (rectangle, triangle and circle) reading
shape and appropriate values from a standard input using Python
Programming
$sudo nano RTC.py
import math
r=float(input("Enter the radius"))
ac=math.pi* r*r
print("The area of circle is", ac)
s=float(input("Enter the side of the square"))
sq=s*s
print("The area of square is", sq)
l=float(input("Enter the length of the rectable"))
b=float(input("Enter the breadth of the rectable"))
ar=l*b
print("The are of the rectangle", ar)
base=float(input("Enter the base of the traingle"))
h=float(input("Enter the height of the traingle"))
t=(1/2)*base*h
print("The are of the traingle",t)
6
Week-2
Experiment 5: Print name n times where name and n are read from standard
input using WHILE loops using Python Programming
$sudo nano printname.py
Experiment 6: Print name n times where name and n are read from standard
input using FOR loop using Python Programming
7
Student
Student
Student
import time
from datetime import datetime
#For 10 times
for x in range(10):
# Get current time
now = datetime.now()
# Make a string of it
current_time = now.strftime("%H:%M:%S")
# Print it
print(current_time)
8
Week-3
Experiment 9: Read a file line by line and print the word count of each line
using Python Programming
$ sudo nano file.py
file_name = input("Enter file name:")
word_count = 0
i = 0
str1 = ""
print("Contents of file " + file_name + " are:")
file1.close()
9
Experiment 10: LED Blinking ON/OFF using Raspberry Pi3
We will need the following tools to complete the project:
The first step in this project is to design a simple LED circuit. Then we will make the
LED circuit controllable from the Raspberry Pi by connecting the circuit to the general
purpose input/output (GPIO) pins on the Raspberry Pi.
10
Step3- To find the pin number refer to this diagram showing the physical pin
numbers on the Raspberry Pi.
11
Step4- Writing the Python Software to blink the LED
import time #time factor is for time taken for LED of/off
Output:
LED is ON
LED IS OFF
12
Experiment 11: Multiple LED Blinking ON/OFF using Raspberry Pi3
We will need the following tools to complete the project:
The first step in this project is to design a simple LED circuit. Then we will make the
LED circuit controllable from the Raspberry Pi by connecting the circuit to the general
purpose input/output (GPIO) pins on the Raspberry Pi.
13
Step3- To find the pin number refer to this diagram showing the physical pin
numbers on the Raspberry Pi.
14
Step4- Writing the Python Software to blink the LED
import time #time factor is for time taken for LED of/off
while True:
Output:
LED is ON
LED IS OFF
15
Experiment 12: Buzzer Beep with Raspberry Pi3
We will need the following tools to complete the project:
Step1
Introduction to Buzzer
A buzzer is a small yet efficient component to add sound features to our project/system.
It is very small and compact 2-pin structure hence can be easily used on breadboad, Perf Board
and even on PCBs which makes this a widely used component in most electronic applications.
There are two types of buzzers that are commonly available. The one shown here is a simple
buzzer which when powered will make a Continuous Beeeeeeppp.... sound, the other type is
called a readymade buzzer which will look bulkier than this and will produce a Beep. Beep.
Beep.
Sound due to the internal oscillating circuit present inside it. But, the one shown here is most
widely used because it can be customized with help of other circuits to fit easily in our
application.
Step2
This buzzer can be used by simply powering it using a DC power supply ranging from 4V to 9V.
A simple 9V battery can also be used, but it is recommended to use a regulated +5V or +6V DC
supply.
The buzzer is normally associated with a switching circuit to turn ON or turn OFF the buzzer at
required time and require interval.
16
Step3
2 Negative Identified by short terminal lead. Typically connected to the ground of the
circuit
Step4
Rated Voltage: 6V DC
Operating Voltage: 4-8V DC
Rated current: <30mA
Sound Type: Continuous Beep
Resonant Frequency: ~2300 Hz
Small and neat sealed package
Breadboard and Perf board friendly
Step5
Applications of Buzzer
17
Step6
18
Step8 - Program:
import time #time factor is for time taken for LED of/off
while True:
Output:
Buzzer is ON
Buzzer is OFF
19
Week-4
Step1
Introduction to IR Sensor
IR Sensors emit and receive Infrared radiation. They are often used as Proximity Sensors
i.e. detect and alarm if an object is close to the sensor.
Step2
1]Mobile Phones.
Almost all mobile phones nowadays have IR Sensors in them. Usually, they will be
placed near the earpiece on the phone.
When the user make or receives a phone call, the IR Sensor detects how far the phone is
from the user’s ear. If it is close to the ear, the phone’s display will be turned off so that
you do not touch anything on the screen accidently.
2]Automobiles
Another important application is in automobiles. All modern cars are equipped with
reverse parking sensor that sense how far you can reverse your car without hitting
anything. These reverse sensors are implemented using IR Sensors.
20
Step3
IR Sensors emit and receive Infrared radiation. They are often used as Proximity Sensors
i.e. detect and alarm if an object is close to the sensor.
Now that we have seen a little bit about the IR Sensor Module and its connections, we
will proceed with interfacing IR Sensor with Raspberry Pi.
The Raspberry Pi IR Sensor Interface can be converted into a Proximity Detector, where
the application will detect if the object is too close to the sensor.
21
Step4
Circuit Diagram
The following image shows the connection diagram of Interfacing IR Sensor with Raspberry Pi.
You have already seen the circuit diagram of the IR Sensor Module.
22
Step5
Applications
As mentioned in the earlier sections, Proximity Sensor or Obstacle Detection is the main
application of interfacing IR Sensor with Raspberry Pi. Some of the common applications
include:
23
Car Reverse Sensor
24
Step6- Writing the Python Software to blink the LED
Step7: Program
import RPi.GPIO as GPIO #import RPi.GPIP module
import time #time factor is for time taken for LED of/off
while True:
else:
Output:
25
Experiment 14: Infrared Sensor(IR) Sensor to Detect Object with LED
blinking automatically using Raspberry Pi3
We will need the following tools to complete the project:
Circuit Diagram
The following image shows the connection diagram of Interfacing IR Sensor with Raspberry Pi.
26
Step6- Writing the Python Software to blink the LED
Program
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.IN)
GPIO.setup(10,GPIO.OUT)
while True:
if GPIO.input(8)==0:
GPIO.output(10,True)
time.sleep(0.1)
else:
GPIO.output(10,False)
time.sleep(0.1)
Output:
27
Week-5
Experiment 15: Passive Infrared Sensor (PIR) Sensor motion Detection using
Raspberry Pi3
Passive Infrared Sensor (PIR – Introduction)
Passive infrared (PIR) sensors are devices that are used to detect motion. Sometimes they
are referred to as pyroelectric sensors. As the name suggests, the devices are passive
sensors, which means that the sensor does not use energy to detect infrared light.
A pyroelectric sensor consists of an electrically polarized crystal that generates an electric
charge when exposed to infrared radiation. All animals emit infrared radiation, so PIR
sensors can be used to detect the motion of humans and other large animals.
PIR sensor is used for detecting infrared heat radiations. This makes them useful in the
detection of moving living objects that emit infrared heat radiations.
The output (in terms of voltage) of PIR sensor is high when it senses motion; whereas it
is low when there is no motion (stationary object or no object).
PIR sensors are used in many applications like for room light control using human
detection, human motion detection for security purpose at home, etc.
The sensing element consists of crystals that respond to changes in infrared energy. The sensing
element is split into two parts – sensing element A and sensing element B:
When nothing is moving, the two sensing elements detect the same infrared levels and cancel
each other out. When an infrared emitting object like a dog moves into the sensor’s field of view,
sensing element A detects the infrared light first. This causes a positive differential change
between the two sensing elements because the infrared light level hitting sensor element B is still
low.
28
When the object passes the sensor, the infrared light level hitting sensor element B will be
higher than element A, which causes a negative differential change between the two sensing
elements.
This potential difference is detected and amplified by an onboard logic chip (the BISS0001), and
turned into a digital signal that can be detected by the Raspberry Pi.
PIR sensor can detect animal/human movement in a requirement range. PIR is made of a
pyroelectric sensor, which is able to detect different levels of infrared radiation. The detector
itself does not emit any energy but passively receives it.
The pyroelectric sensor sees the moving human body for a while and then does not see it, so the
infrared radiation of human body constantly changes the temperature of the pyroelectric material.
So that it outputs a corresponding signal, which is the alarm signal.
Plastic optical reflection system or plastic Fresnel lens used as a focusing system for infrared
radiation.
29
Experiment:
The module has three pins: Ground and VCC for powering the module. The Digital Out
Pin gives a high logic level as a target moves within the sensor’s range.
30
Step4- Writing the Python Software to blink the LED
Program1:
import time
import requests
GPIO.setmode(GPIO.BCM)
pirPin = 4 #pin=7
GPIO.setup(PirPin, GPIO.IN)
time.sleep(1)
while True:
if GPIO.input(pirPin):
print("Motion Detected")
time.sleep(1)
print("No one")
Output:
No One
No One
No One
Motion detected when any person in move, the PIR sensor
detect motion.
31
Program: 2
GPIO.setwarnings(False)
GPIO.setup(PIR_input, GPIO.IN)
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, GPIO.LOW)
while True:
if(GPIO.input(PIR_input)):
GPIO.output(LED, GPIO.HIGH)
else:
GPIO.output(LED, GPIO.LOW)
32
GND = Pin 6
VCC = Pin 1
DATA = Pin 7
33
Week-6
1. Raspberry Pi3
2. LAN cable
3. Jumper wires
4. Breadboard
5. DHT11 Temperature and Humidity Sensor
Introduction to DHT11
By interfacing the DHT11 Sensor with Raspberry Pi, you can build your own IoT
Weather Station. All you need to implement such IoT Weather is a Raspberry Pi, a
DHT11 Humidity and Temperature Sensor and a Computer with Internet Connectivity.
DHT11 Temperature and Humidity Sensor is one of the popular sensor modules used
by hobbyists for implementing in a lot of IoT Projects. This sensor along with
Raspberry Pi can also be used in:
34
Circuit Diagram
All you need to do is to 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.
35
Installing DTH11 Library
Since we are using a library called Adafruit_DHT provided by Adafruit for this project, we need
to first install this library into Raspberry Pi.
First step is to download the library from GitHub. But before this, I have created a folder called
‘library’ on the desktop of the Raspberry Pi to place the downloaded files. You don’t have to do
that.
Now, enter the following command to download the files related to the Adafruit_DHT library.
In that folder, there is file called ‘setup.py’. We need to install this file using the
following command.
36
Step4- Writing the Python Software to blink the LED
while True:
time.sleep(1)
Output:
37
Experiment 18: DHT11 Temperature & Humidity Sensor (Cloud Based) using
Raspberry Pi3
To view / edit the python program using following command:
pin = 2
while True:
humidity, temperature=Adafruit_DHT.read_retry (Adafruit_DHT.
DHT11,pin)
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C
Humidity={1:0.1f}%'.format(temperature,
humidity))
else:
print('Failed to get reading. Try again')
time.sleep(2)
f = urllib.request.urlopen("https://api.thingspeak.com/
update?api_key=1DOQ3MODXLTSQXEZ&field1=%S&field2=%S" %
(temperature, humidity))
print (f.read())
f.close()
38
Week-7
Experiment 19: Temperature of CPU Data (Cloud Based) using Raspberry Pi3
https://www.youtube.com/watch?v=legRoQAxSug
while True:
templfile-open('/sys/class/thermal/thermal_zone0/temp')
cpu_temp_raw=tempFile.read()
tmpFile.close()
cpu_temp=round(float(cpu_temp_raw)/1000,1)
print cpu_temp
time.sleep(1)
47.8
47.8
47.2
47.2
47.3
47.8
47.2
47.2
39
Experiment 20: Smoke Sensor using Raspberry Pi3
Components Needed
Raspberry Pi board
MQ-2 Smoke Sensor
MCP3002 Analog-to-digital Converter Chip
Experiment:
40
Python Code
The code to read the value of a smoke sensor with a Raspberry Pi is shown below.
import time
import botbook_mcp3002 as mcp #
smokeLevel= 0
def readSmokeLevel():
global smokeLevel
smokeLevel= mcp.readAnalog()
def main():
while True: #
readSmokeLevel() #
print ("Current smoke level is %i " % smokeLevel) #
if smokeLevel > 120:
print("Smoke detected")
time.sleep(0.5) # s
if_name_=="_main_":
main()
Ouput:
$sudo python3 smoke.py
Smoke detected
Smoke detected
41
Experiment 21: Sound Sensor using Raspberry Pi3
https://www.instructables.com/Sound-Sensor-Raspberry-Pi/
1. Raspberry Pi3
2. LAN cable
3. Jumper wires
4. Breadboard
5. Sound Sensor
VCC <-> 5V
GND <-> GND
D0 <-> GPIO 17
42
Python Code for Sound Detect using Raspberry Pi3
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
#GPIO SETUP
channel = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
def callback(channel):
if GPIO.input(channel):
print "Sound Detected!"
else:
print "Sound Detected!"
# infinite loop
while True:
time.sleep(1)
Output:
Sound detected
Sound detected
Sound detected
Sound detected
Sound detected
Sound detected
43
Week-8
Experiment 22: Ph Sensor for detect moisture levels in soil using Raspberry Pi3
Aim: Soil moisture sensors measure the volumetric water content in soil with
Raspberry Pi3
Hardware Component:
1. Raspberry Pi X1
2. Soil Moisture Sensor with A-D breakout board X1
3. Female to Female Jumper wires X5
Software Components
EXPERIMENT
In this project we will be integrating the Soil Moisture Sensor with the
Raspberry Pi. To connect the sensor to the Pi an Analog to Digital
conversion is required as the sensor produces analog output.
To convert the Analog to Digital we use a breakout board which comes
along with the sensor. There are 5 connections that are to be made. 3
connections are to the Pi and the other 2 are to the soil sensor.
The Analog to digital (A-D) breakout board converts the analog output of
the sensor to digital for the pi to understand it. So we have to connect the
digital pin i.e. D0 to the GPIO of the raspberry pi. The pin A0 is kept open
as we are not using it for this project.
The sensitivity of the sensor can be changed by varying the potentiometer
present on the A-D breakout board. The connections are made as follows:
Vcc – 5V
Gnd – Ground
Signal (D0) – GPIO 21
44
When the connections are made and the Pi is powered up, a red light on the
A-D breakout board turns on indicating that the board is ready to be used.
For testing purposes take the sensor and dip it in water.
When around half of the sensor is in the water another light on the breakout
board turns on indicating the presence of water. To check the presence of
moisture in the soil insert the sensor (about 3/4th of the sensor) into the soil
and find out whether moisture is present or not.
CIRCUIT DIAGRAM
45
Program:
channel = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
def callback(channel):
if GPIO.input(channel):
print("No water detected")
else:
print("Water Detected")
while True:
sleep(1)
Result:
pi@raspberrypi:~/MOISTURE $ sudo python3 moisture.py
Water Detected
Water Detected
Water Detected
Water Detected
No water detected
Water Detected
Water Detected
No water detected
Water Detected
Water Detected
No water detected
Water Detected
Water Detected
Water Detected
Water Detected
46
Week-9
Experiment 23: Implement an Intruder system that sends an alert to the given E-
mail using Raspberry Pi
https://circuitdigest.com/microcontroller-projects/raspberry-pi-iot-intruder-alert-system
Hardware Component:
Raspberry Pi
Pi Camera
PIR Sensor
LED
Bread Board
Resistor (1k)
Connecting wires
Power supply
Experiment
Raspberry Pi based Intruder Alert System, which not only alert you through an
email but also sends the picture of Intruder when it detects any.
In this IoT based Project, we will build a Home Security System using PIR Sensor
and PI Camera. This system will detect the presence of Intruder and quickly alert
the user by sending him a alert mail. This mail will also contain the Picture of the
Intruder, captured by Pi camera. Raspberry Pi is used to control the whole system.
This system can be installed at the main door of your home or office and you can
monitor it from anywhere in the world using your Email over internet.
Working of this Project is very simple. A PIR sensor is used to detect the presence
of any person and a Pi Camera is used to capture the images when the presence it
detected.
Whenever anyone or intruder comes in range of PIR sensor, PIR Sensor triggers
the Pi Camera through Raspberry Pi. Raspberry pi sends commands to Pi camera
to click the picture and save it. After it, Raspberry Pi creates a mail and sends it to
the defined mail address with recently clicked images. The mail contains a
message and picture of intruder as attachment. Here we have used the message
“Please find the attachment”, you can change it accordingly in the Code given at
the end.
47
Circuit Description:
In this Intruder Alert System, we only need to connect Pi Camera module and PIR
sensor to Raspberry Pi 3. Pi Camera is connected at the camera slot of the
Raspberry Pi and PIR is connected to GPIO pin 18. A LED is also connected to
GPIO pin 17 through a 1k resistor.
We are using Python language here for the Program. Before coding, user needs to
configure Raspberry Pi. You should below two tutorials for Getting Started with
Raspberry Pi and Installing & Configuring Raspbian Jessie OS in Pi:
48
After successfully installing Raspbian OS on Raspberry Pi, we need to install Pi
camera library files for run this project in Raspberry pi. To do this we need to
follow given commands:
After it, user needs to enable Raspberry Pi Camera by using Raspberry Pi Software
Configuration Tool (raspi-config):
$ sudo raspi-config
Then select Enable camera and Enable it.
Then user needs to reboot Raspberry Pi, by issuing sudo reboot, so that new setting
can take. Now your Pi camera is ready to use.
Now after setting up the Pi Camera, we will install software for sending the mail.
Here we are using ssmtp which is an easy and good solution for sending mail using
command line or using Python Script. We need to install two Libraries for sending
mails using SMTP:
49
After installing libraries, user needs to open ssmtp.conf file and edit this
configuration file as shown in the Picture below and then save the file. To save and
exit the file, Press ‘CTRL+x’, then ‘y’ and then press ‘enter’.
We can also test it by sending a test mail by issuing below command, you shall get
the mail on the mentioned email address if everything is working fine:
$echo "Hello saddam" | mail -s "Testing..." saddam4201@gmail.com
Python Code
import RPi.GPIO as gpio
import picamera
import time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
from email.mime.image import MIMEImage
fromaddr = "raspiduino4201@gmail.com" # change the email
address accordingly
toaddr = "saddam4201@gmail.com"
mail = MIMEMultipart()
mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Please find the attachment"
led=17
pir=18
HIGH=1
LOW=0
gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(led, gpio.OUT) #initialize GPIO Pin as outputs
50
gpio.setup(pir, gpio.IN) #initialize GPIO Pin as input data=""
def sendMail(data):
mail.attach(MIMEText(body, 'plain'))
print data
dat='%s.jpg'%data
print dat
attachment = open(dat, 'rb')
image=MIMEImage(attachment.read())
attachment.close()
mail.attach(image)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "your password")
text = mail.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
def capture_image():
data= time.strftime("%d_%b_%Y|%H:%M:%S")
camera.start_preview()
time.sleep(5)
print data
camera.capture('%s.jpg'%data)
camera.stop_preview()
time.sleep(1)
sendMail(data)
gpio.output(led , 0)
camera = picamera.PiCamera()
camera.rotation=180
camera.awb_mode= 'auto'
camera.brightness=55
while 1:
if gpio.input(pir)==1:
gpio.output(led, HIGH)
capture_image()
while(gpio.input(pir)==1):
time.sleep(1)
else:
gpio.output(led, LOW)
time.sleep(0.01)
51
Week-10
Experiment 24: Get an alarm from a remote area (through LAN) if smoke is
detected.
https://www.youtube.com/watch?v=lCcXiFnYCuY
Introduction
A fire sensor is a device that is used to detect fire or flame. It is very important
to use this type of sensors where there is a chance of a fire occurring. We can
use even for our household purposes also where there might be any chances
of occurring fire accidents. So let's get headed towards the project and
understand the working in detail along with the circuit diagram and codes.
Hardware Equipment:
1. Raspberry Pi
2. Fire sensor
3. USB Cable
4. JUMping wires
Hardware Connections:
Fire sensor with Raspberry pi3 and send notifications of your mobile use by
notification service. The fire sensor detect flame and send notification to our
mobile.
A0
52
The fire #sensor has four pins which are A0(analog pin), ground, VCC(can be
3.3v/5v depending on the module), and D0( digital output pin). In addition to these
pins, the module has LEDs for power and D0 output. The D0 led glows when the
sensor detects fire. Also, we have a #potentiometer in the fire sensor which allows
voltage to flow as per the required amount while functioning.
We connect these pins with a raspberry pi board with different pins on it. The D0
pin of the fire sensor is connected to the Raspberry Pi GPIO. The ground and VCC
pin of the fire sensor is connected to the respective terminals of the Raspberry Pi
board.
In the fire sensor, the fourth pin is the analog pin(A0) which can not be connected
to the Raspberry Pi directly. So if one wants to use the analog pin an external
analog to digital converter is required for the Raspberry Pi GPIO
53
Step2: Pushbullet Website
www.pushbullet.com
settings create access tokens click on (get API copy & paste in code)
Output
Fire detected
54
Week-11
https://maker.pro/raspberry-pi/projects/how-to-create-a-telegram-bot-with-a-
raspberry-pi
Introduction:
Learn how to use a Raspberry Pi and the Telegram app to create a bot to help you with tasks
around the house. n this article, we will create a telegram bot capable of sending and receiving
messages from a Raspberry Pi. We’ll program the Raspberry Pi to obtain the time and date. We
will also be able to control the GPIO pins of the Raspberry Pi, by connecting the two LEDs on
the Raspberry Pi GPIO pins.
Telegram is a messaging app like WhatsApp, but Telegram can create the bots. It has an API bot
that not only allows the human to talk to it, but also machines. With this tutorial, you can use
Telegram to control anything in your home or even feed your dog when you’re away.
We have finished creating the bot. Now, we need to write some code for the Raspberry Pi that
will make it respond to messages from the bot. Before that, hook up the connections for the
Raspberry Pi.
55
Similarly, connect the positive lead of the green LED to GPIO 20 of the Raspberry Pi and the
negative lead of the green LED to the ground through the 220-ohm resistor.
56
Full Telegram Bot With Raspberry Pi Code
import datetime # Importing the datetime library
import telepot # Importing the telepot library
from telepot.loop import MessageLoop # Library function to communicate
with telegram bot
import RPi.GPIO as GPIO # Importing the GPIO library to use the GPIO pins
of Raspberry pi
from time import sleep # Importing the time library to provide the delays
in program
def handle(msg):
chat_id = msg['chat']['id'] # Receiving the message from telegram
command = msg['text'] # Getting text from the message
print ('Received:')
print(command)
# Comparing the incoming message to send a reply according to it
if command == '/hi':
bot.sendMessage (chat_id, str("Hi! MakerPro"))
elif command == '/time':
bot.sendMessage(chat_id, str("Time: ") + str(now.hour) + str(":") +
str(now.minute) + str(":") + str(now.second))
elif command == '/date':
bot.sendMessage(chat_id, str("Date: ") + str(now.day) + str("/") +
str(now.month) + str("/") + str(now.year))
elif command == '/red_1':
bot.sendMessage(chat_id, str("Red led is ON"))
GPIO.output(red_led_pin, True)
elif command == '/red_0':
bot.sendMessage(chat_id, str("Red led is OFF"))
GPIO.output(red_led_pin, False)
elif command == '/green_1':
bot.sendMessage(chat_id, str("Green led is ON"))
GPIO.output(green_led_pin, True)
elif command == '/green_0':
bot.sendMessage(chat_id, str("Green led is OFF"))
GPIO.output(green_led_pin, False)
# Insert your telegram token below
bot = telepot.Bot('542543102:AAE7xb6_XGAn9Yh-4PPJmfK5YK9TEA4')
print (bot.getMe())
# Start listening to the telegram bot and whenever a message is received,
the handle function will be called.
MessageLoop(bot, handle).run_as_thread()
print ('Listening....')
while 1:
sleep(10)
57
Week 12
Build a simple IoT Home automation project using Raspberry Pi without writing a single line of
Python Code. Use Cayenne to remotely control a Relay connected to the Raspberry Pi which will
turn a LED Bulb ON/OFF based on user input. As cayenne is a cloud platform, we can control
the LED bulb from anywhere in the world as long as the Pi is connect to the Internet.
Step1:
Create your Cayenne myDevices Account here: https://accounts.mydevices.com/
As this is your first login, you will be redirected by default to create a new project.
Select Raspberry Pi then in step2 before clicking next, make sure your Pi is up and running
and is connected to the Internet.
Now click next
Step2:
Open the terminal in Raspberry Pi and copy & paste the commands given in the Caynne
dashboard.
While installing, the cayenne dashboard will get remote access to your Pi and shows the status of
the installation.
58
Step3:
As soon as the installation process completes, the online dashboard will automatically appear.
Your Raspberry Pi is now ready to use.
Now click "Add new" and then select the “device option” from the submenu.
Select Relay is an actuator select actuators from device list and the select Relay and it shows
Relay switch.
Leave the Widget name and device as default. For Connectivity option you need to select it as
integrated GPIO. Next you need to set the channel, which is essentially the GPIO pin that will
be interfaced with the Relay Module. Now Select channel 17.
.
Finally choose the widget type as button and click add actuator.
59
Step4
Once the widget is configured and created you will be redirected to the dashboard overview.
This is where toggle button for controlling the relay will appear. The next step is to interface the
Raspberry Pi to a Relay and then connect the CFL in normally open configuration.
Step5
Jumper wire connection from Relay to Rasbperry Pi.
Connect the VCC pin of the Relay to a 5V pin of the Rasbperry Pi.
GIT pin of Relay to any GND pins of the Rasbperry Pi.
IN1 pin of Relay to GPIO 17 pin of the Rasbperry Pi.
Output
Clicking the Toggle button on the Dashboard indeed actuates the relay which in turn switches the
CFL to ON state. If we select ON the LED bulb automatically On. The LED bulb will be
glowing.
It is an IoT based Home Automation project using Raspberry Pi without writing even a single
line of Python code.
***
60