Raspberry Pi

10,167 views 104 slides Jan 12, 2021
Slide 1
Slide 1 of 104
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104

About This Presentation

on successful go through of this complete PPT, the learners can be able to understand the Raspberry PI, Raspberry Pi Interfaces(Serial, SPI,I2C) Programming, Python programming with Raspberry PI with the focus of Interfacing external gadgets
Controlling output Reading input from pins.


Slide Content

By
Mr.S.Selvaraj
Asst. Professor(SRG) / CSE
Kongu Engineering College
14ITO01–Internetof Things
Unit IV –IoT Devices (RaspberryPi)

OUTLINE
•Introduction to Raspberry PI
•Interfaces (Serial,SPI,I2C) Programming
•Python programming with Raspberry PI with
focus of
–Interfacing external gadgets
–Controlling output
–Reading input from pins
•Connecting IoT to Cloud
21/12/2021 IoT Devices -Raspberry Pi

Introduction to Raspberry Pi
•What is an IoT Device?
•Basic building blocks of an IoT Device
•Exemplary Device: Raspberry Pi
•Raspberry Pi interfaces
•Programming Raspberry Pi with Python
•Other IoTdevices
31/12/2021 IoT Devices -Raspberry Pi

What is an IoT Device?
–A "Thing" in Internet of Things (IoT) can be any
object that has a unique identifier and which can
send/receive data (including user data) over a network
(e.g., smart phone, smart TV, computer, refrigerator,
car, etc. ).
–IoTdevices are connected to the Internet and send
information about themselves or about their
surroundings (e.g. information sensed by the
connected sensors) over a network (to other devices or
servers/storage) or allow actuation upon the physical
entities/environment around them remotely
41/12/2021 IoT Devices -Raspberry Pi

IoT Device Examples
–A home automation device that allows remotely monitoring
the status of appliances and controlling the appliances.
–An industrial machine which sends information aboutsits
operation and health monitoring data to a server.
–A car which sends information about its location to a
cloud-based service.
–A wireless-enabled wearable device that measures data
about a person such as the number of steps walked and
sends the data to a cloud-based service.
51/12/2021 IoT Devices -Raspberry Pi

Basic building blocks of an IoTDevice
•Sensing
Sensors can be either on-board the IoTdevice or attached to the device.
Actuation
IoTdevices can have various types of actuators attached that allow
taking
actions upon the physical entities in the vicinity of the device.
Communication
Communication modules are responsible for sending collected data to
other devices or cloud-based servers/storage and receiving data from
other devices and commands from remote applications.
Analysis & Processing
Analysis and processing modules are responsible for making sense of
the collected data
61/12/2021 IoT Devices -Raspberry Pi

Block diagram of an IoTDevice
71/12/2021 IoT Devices -Raspberry Pi

Exemplary Device: Raspberry Pi
•RaspberryPiisalow-costmini-computerwiththe
physicalsizeofacreditcard.
•RaspberryPirunsvariousflavorsofLinuxand
canperformalmostalltasksthatanormaldesktop
computercando.
•RaspberryPialsoallowsinterfacingsensorsand
actuatorsthroughthegeneralpurposeI/Opins.
•SinceRaspberryPirunsLinuxoperatingsystem,
itsupportsPython"outofthebox"
81/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Statusleds
STATUSLED FUNCTION
ACT SDcard access
PWR 3.3V Poweris present
FDX Full DuplexLAN connected
LNK Link/Network activity
100 100 Mbit LANconnected
91/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Board
101/12/2021 IoT Devices -Raspberry Pi

Linux on Raspberry Pi
•Raspbian
–RaspbianLinux is a DebianWheezy port optimized for Raspberry Pi.
•Arch
–Arch is an Arch Linux port for AMD devices.
•Pidora
–PidoraLinux is a Fedora Linux optimized for Raspberry Pi.
•RaspBMC
–RaspBMCis an XBMC media-centerdistribution for Raspberry Pi.
•OpenELEC
–OpenELECis a fast and user-friendly XBMC media-center
distribution.
•RISC OS
–RISC OS is a very fast and compact operating system
111/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi GPIO headers
121/12/2021 IoT Devices -Raspberry Pi

RasbianLinux Desktop
131/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi frequently used
commands
Command Function Example
cd change directory cd/home/pi
cat show file contents cat file.txt
ls list files and folders ls/home/pi
locate search for a file locate file.txt
lsusb list usbdevices lsusb
pwd print name for present working
directory
pwd
mkdir make directory mkdir/home/pi/new
mv move(rename) file mv sourcefile.txt destfile.txt
rm remove file rmfile.txt
reboot reboot device sudoreboot
shutdown shutdown device sudoshutdown –h now
141/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi frequently used
commands
Command Function Example
grep Print lines matching a patterngrep–r “pi”/home/
df Reportfile system disk space usagedf-Th
ipconfig Configure a network interfaceipconfig
netstat Print network connections, routing
tables, interface statistics
Netstat-lntp
tar Extract/create archive Tar –xzffoo.tar.gz
wget Non-interactive network downloaderWget
http://example.com/filr.tar.
gz
151/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Interfaces
•Serial Interface / UART Interface
–Universal Asynchronous Receiver and
Transmitter(UART)
•SPI
–Serial Peripheral Interface (SPI)
•I2C
–Inter-Integrated Circuits (I2C)
161/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Interfaces
•Serial
–TheserialinterfaceonRaspberryPihasreceive(Rx)
andtransmit(Tx)pinsforcommunicationwithserial
peripherals.
•SPI
–SerialPeripheralInterface(SPI)isasynchronous
serialdataprotocolusedforcommunicatingwithone
ormoreperipheraldevices.
•I2C
–TheI2CinterfacepinsonRaspberryPiallowyouto
connecthardwaremodules.
–I2Cinterfaceallowssynchronousdatatransferwith
justtwopins-SDA(dataline)andSCL(clockline).
171/12/2021 IoT Devices -Raspberry Pi

Serial / UART
181/12/2021 IoT Devices -Raspberry Pi

SPI
•InSPIConnection,thereisonemasterdeviceandone
ormoreperipheraldevices.
•TherearefivepinsonRaspberryPiforSPIinterface.
–MISO(MasterInSlaveOut)–MasterLineforSendingData
totheperipherals.
–MOSI(MasterOutSlaveIn)–SlaveLineforsendingdata
tothemaster.
–SCK(SerialClock)–ClockGeneratedbyMasterto
Synchronizedatatransmission.
–CE0(ChipEnable0)–ToEnableorDisabledevices.
–CE1(ChipEnable1)–ToEnableorDisabledevices.
191/12/2021 IoT Devices -Raspberry Pi

I2C
201/12/2021 IoT Devices -Raspberry Pi

211/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configurations
•ApowerfulfeatureoftheRaspberryPiisthe
rowofGPIO(general-purposeinput/output)
pinsalongthetopedgeoftheboard.
•A40-pinGPIOheaderisfoundonallcurrent
RaspberryPiboards(unpopulatedonPiZero
andPiZeroW).
•PriortothePi1ModelB+(2014),boards
comprisedashorter26-pinheader.
221/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configuration
231/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configuration
•AnyoftheGPIOpinscanbedesignated(in
software)asaninputoroutputpinandusedfora
widerangeofpurposes.
•Note:thenumberingoftheGPIOpinsisnotin
numericalorder;GPIOpins0and1arepresent
ontheboard(physicalpins27and28)butare
reserved for advanced use.
241/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configuration
•Voltages
–Two5Vpinsandtwo3V3pinsarepresentontheboard,aswellasa
numberofgroundpins(0V),whichareunconfigurable.
–Theremainingpinsareallgeneralpurpose3V3pins,meaningoutputs
aresetto3V3andinputsare3V3-tolerant.
•Outputs
–AGPIOpindesignatedasanoutputpincanbesettohigh(3V3)orlow
(0V).
•Inputs
–AGPIOpindesignatedasaninputpincanbereadashigh(3V3)orlow
(0V).
–Thisismadeeasierwiththeuseofinternalpull-uporpull-down
resistors.
–PinsGPIO2andGPIO3havefixedpull-upresistors,butforotherpins
thiscanbeconfiguredinsoftware.
251/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configuration
•Aswellassimpleinputandoutputdevices,theGPIOpinscanbeused
withavarietyofalternativefunctions,someareavailableonallpins,
othersonspecificpins.
•PWM(pulse-widthmodulation)
–SoftwarePWMavailableonallpins
–HardwarePWMavailableonGPIO12,GPIO13,GPIO18,GPIO19
•SPI
–SPI0:MOSI(GPIO10);MISO(GPIO9);SCLK(GPIO11);CE0(GPIO8),CE1(GPIO7)
–SPI1:MOSI(GPIO20);MISO(GPIO19);SCLK(GPIO21);CE0(GPIO18);CE1
(GPIO17);CE2(GPIO16)
•I2C
–Data:(GPIO2);Clock(GPIO3)
–EEPROMData:(GPIO0);EEPROMClock(GPIO1)
•Serial
–TX(GPIO14);RX(GPIO15)
261/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configuration
•GPIOpinout
–It'simportanttobeawareofwhichpiniswhich.
–Somepeopleusepinlabels(like
•theRasPiOPortsplusPCB,or
•theprintableRaspberryLeaf).
271/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Pin Configuration
•Ahandyreferencecanbeaccessedonthe
RaspberryPibyopeningaterminalwindow
andrunningthecommandpinout.
•ThistoolisprovidedbytheGPIOZeroPython
library,whichisinstalledbydefaultonthe
RaspberryPiOSdesktopimage,butnoton
RaspberryPiOSLite.
281/12/2021 IoT Devices -Raspberry Pi

291/12/2021 IoT Devices -Raspberry Pi

Python programming with Raspberry PI with focus of
-Interfacing external gadgets
-Controlling output
-Reading input from pins

Python Programming with Raspberry
Pi
•Python programming with Raspberry PI with focus of
–Interfacing external gadgets
–Controlling output
–Reading input from pins
•GPIO pins on Raspberry Pi that makes it useful device for IoT.
•We can interface a wide variety of sensors and actuators with Raspberry
Pi using the GPIO pins and SPI, I2C and Serial Interfaces.
•Input from the sensors connected to Raspberry Pi can be processed and
various actions can be taken, for
–Instance,
–Sending data to a server
–Sending an email
–Triggering a relay switch
311/12/2021 IoT Devices -Raspberry Pi

Controlling LED with Raspberry Pi
321/12/2021 IoT Devices -Raspberry Pi

Components Reuired
•You'll need the following components to
connect the circuit.
•1. Raspberry Pi
2. LED
3. Resistor -330 ohm
4. Breadboard
5. 2 Male-Female Jumper Wires
331/12/2021 IoT Devices -Raspberry Pi

341/12/2021 IoT Devices -Raspberry Pi

351/12/2021 IoT Devices -Raspberry Pi

Python Code
•import RPi.GPIOas GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21,GPIO.OUT)
print "LED on"
GPIO.output(21,GPIO.HIGH)
time.sleep(10)
print "LED off"
GPIO.output(21,GPIO.LOW)
361/12/2021 IoT Devices -Raspberry Pi

371/12/2021 IoT Devices -Raspberry Pi

Python programming with Raspberry PI with focus of
-Interfacing external gadgets
-Controlling output
-Reading input from pins

Controlling LED with Switch on
Raspberry Pi
391/12/2021 IoT Devices -Raspberry Pi

Components Reuired
•You'll need the following components to
connect the circuit.
•1. Raspberry Pi
2. LED
3. Resistor -330 ohm
4. Breadboard
5. Button / Switch
6. 2 Male-Female Jumper Wires
401/12/2021 IoT Devices -Raspberry Pi

Components
411/12/2021 IoT Devices -Raspberry Pi

Switch / Button
•Buttonsareacommoncomponentusedto
controlelectronicdevices.
•Theyareusuallyusedasswitchestoconnect
ordisconnectcircuits.
•Althoughbuttonscomeinavarietyofsizes
andshapes,theoneusedhereisa6mmmini-
buttonasshowninthefollowingpictures.
•Pinspointedoutbythearrowsofsamecolor
aremeanttobeconnected.
421/12/2021 IoT Devices -Raspberry Pi

Switch / Button
431/12/2021 IoT Devices -Raspberry Pi

Switch / Button
•Whenthebuttonispressed,thepinspointedbythe
bluearrowwillconnecttothepinspointedbythered
arrow(seetheabovefigure),thusclosingthecircuit,as
showninthefollowingdiagrams.
441/12/2021 IoT Devices -Raspberry Pi

Switch / Button
•Generally,thebuttoncanbeconnecteddirectlytotheLEDinacircuitto
turnonorofftheLED,whichiscomparativelysimple.
•However,sometimestheLEDwillbrightenautomaticallywithoutany
buttonpressed,whichiscausedbyvariouskindsofexternalinterference.
•Inordertoavoidthisinterference,apull-downresistorisused–usually
connecta1K–10KΩresistorbetweenthebuttonandGND.Itcanbe
connectedtoGNDtoconsumetheinterferencewhenthebuttonisoff.
•UseanormallyopenbuttonastheinputofRaspberryPi.
•Whenthebuttonispressed,theGPIOconnectedtothebuttonwillturn
intolowlevel(0V).
•WecandetectthestateoftheGPIOconnectedtothebuttonthrough
programming.Thatis,iftheGPIOturnsintolowlevel,itmeansthebutton
ispressed.Youcanrunthecorrespondingcodewhenthebuttonis
pressed,andthentheLEDwilllightup.
451/12/2021 IoT Devices -Raspberry Pi

CIRCUIT Diagram
461/12/2021 IoT Devices -Raspberry Pi

Experimental Procedures
•Step 1: Build the circuit
•Step 2:Create a Python / C code
•Step 3: Run
sudopython 02_btnAndLed.py
•Now,pressthebutton,andtheLEDwilllightup;
pressthebuttonagain,andtheLEDwillgoout.
Atthesametime,thestateoftheLEDwillbe
printedonthescreen.
471/12/2021 IoT Devices -Raspberry Pi

Python Code
•#!/usr/bin/envpython
•import RPi.GPIOas GPIO
•import time
•LedPin= 11 # pin11 ---led
•BtnPin= 12 # pin12 ---button
•Led_status= 1
•def setup():
–GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location
–GPIO.setup(LedPin, GPIO.OUT) # Set LedPin'smode is output
–GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set BtnPin'smode is input, and pull up to high
level(3.3V)
–GPIO.output(LedPin, GPIO.HIGH) # Set LedPinhigh(+3.3V) to off led
•def swLed(ev=None):
–global Led_status
–Led_status= not Led_status
–GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on)
–if Led_status== 1:
•print 'led off...'
–else:
•print '...led on'
481/12/2021 IoT Devices -Raspberry Pi

Python Code (Contd.,)
•def loop():
–GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed,
bouncetime=200) # wait for falling and set bouncetimeto prevent the callback
function from being called multiple times when the button is pressed
–while True:
•time.sleep(1) # Don't do anything
•def destroy():
–GPIO.output(LedPin, GPIO.HIGH) # led off
–GPIO.cleanup() # Release resource
•if __name__ == '__main__': # Program start from here
–setup()
–try:
•loop()
–except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program
destroy() will be executed.
•destroy()
491/12/2021 IoT Devices -Raspberry Pi

Interfacing
501/12/2021 IoT Devices -Raspberry Pi

Applications
•InterfacingaPushButtonwithRaspberryPi
mightnotseemasabigprojectbutit
definitelyhelpsusinunderstandingthe
conceptofreadingfromInputpins.
•Asimilarconceptcanbeappliedtoother
inputdeviceslikedifferenttypesofSensors
–PIRSensor,
–UltrasonicSensor,
–TouchSensor,andsoforth.
511/12/2021 IoT Devices -Raspberry Pi

Python programming with Raspberry PI with focus of
-Interfacing external gadgets
-Controlling output
-Reading input from pins

Interfacing a Light Sensor (LDR) with
Raspberry Pi
531/12/2021 IoT Devices -Raspberry Pi

Components Reuired
•You'll need the following components to
connect the circuit.
•1. Raspberry Pi
2. Light Sensor (LDR Sensor)
3. Capacitor -1µF
4. Breadboard
5. 2 Male-Female Jumper Wires
541/12/2021 IoT Devices -Raspberry Pi

Components
551/12/2021 IoT Devices -Raspberry Pi

LDR Sensor
•Thelight-dependentresistororalsoknownas
theLDRsensoristhemostimportantpieceof
equipmentinourcircuit.Withoutit,we
wouldn’tbeabletodetectwhetheritisdark
orlight.
•Inthelight,thissensorwillhavearesistance
ofonlyafewhundredohms.
•Inthedark,itcanhavearesistanceofseveral
megaohms.
561/12/2021 IoT Devices -Raspberry Pi

LDR Sensor
571/12/2021 IoT Devices -Raspberry Pi

LDR Sensor
•Aphotoresistor,orlight-dependentresistor(LDR),or
photocellisaresistorwhoseresistancewilldecrease
whenincidentlightintensityincrease;inotherwords,
itexhibitsphotoconductivity.
•Aphotoresistorismadeofahighresistance
semiconductor.
•Iflightfallingonthedeviceisofhighenough
frequency,photonsabsorbedbythesemiconductor
giveboundelectronsenoughenergytojumpintothe
conductionband.Theresultingfreeelectron(andits
holepartner)conductelectricity,therebylowering
resistance.
581/12/2021 IoT Devices -Raspberry Pi

CIRCUIT Diagram
591/12/2021 IoT Devices -Raspberry Pi

LDR Sensor
•InthisimplementationwelearnhowtoInterfacealightSensor(LDR)
withRaspberryPiandturninganLEDon/offbasedontheligh-level
sensed.
•Lookgivenimage,ConnectonesideofLDRto3.3Vandothersidetoa1μF
capacitorandalsotoaGPIOpin(pin18inthisexample).
•AnLEDisconnectedtopin18whichiscontrolledbasedonthelight-level
sensed.
•ThereadLDR()functionreturnsacountwhichisproportionaltothelight
level.
•InthisfunctiontheLDRpinissettooutputandlowandthentoinput.
•Atthispointthecapacitorstartschargingthroughtheresistor(anda
counterisstarted)untiltheinputpinreadshigh(thishappenswhen
capacitorvoltagebecomesgreaterthan1.4V).
•Thecounterisstoppedwhentheinputreadshigh.Thefinalcountis
proportionaltothelightlevelasgreatertheamountoflight,smalleristhe
LDRresistanceandgreateristhetimetakentochargethecapacitor.
601/12/2021 IoT Devices -Raspberry Pi

611/12/2021 IoT Devices -Raspberry Pi

Experimental Procedures
•Step 1: Build the circuit
•Step 2:Create a Python / C code
•Step 3: Run
sudopython 03_ldrAndLed.py
621/12/2021 IoT Devices -Raspberry Pi

Importing Packages
•Tobegin,weimporttheGPIOpackagethatwewill
needsothatwecancommunicatewiththeGPIOpins.
•Wealsoimportthetimepackage,sowe’reabletoput
thescripttosleepforwhenweneedto.
631/12/2021 IoT Devices -Raspberry Pi

Pin Assignment
•WethensettheGPIOmodetoGPIO.BCM,and
thismeansallthenumberingweuseinthisscript
willrefertothephysicalnumberingofthepins.
•Sinceweonlyhaveoneinput/outputpin,we
onlyneedtosetonevariable.Setthisvariableto
thenumberofthepinyouhaveactingasthe
input/outputpin.
GPIO.setmode(GPIO.BCM)
ldr_threshold= 1000
LDR_PIN = 18
LIGHT_PIN = 25
641/12/2021 IoT Devices -Raspberry Pi

Reading the Light Value
•Next,wehaveafunctioncalledreadLDR()thatrequiresoneparameter,whichis
thepinnumbertothecircuit.Inthisfunction,weinitializeavariable
calledreading,andwewillreturnthisvalueoncethepingoestohigh.
•Wethensetourpintoactasanoutputandthensetittolow.Next,wehavethe
scriptsleepfor10ms.
•Afterthis,wethensetthepintobecomeaninput,andthenweenterawhile
loop.Westayinthisloopuntilthepingoestohigh,thisiswhenthecapacitor
chargestoabout3/4.
•Oncethepingoeshigh,wereturnthecountvaluetothemainfunction.Youcan
usethisvaluetoturnonandoffanLED,activatesomethingelse,orlogthedata
andkeepstatisticsonanyvarianceinlight.
def readLDR(PIN):
reading = 0
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(PIN, false)
time.sleep(0.1)
GPIO.setup(PIN, GPIO.IN)
while (GPIO.input(PIN) ==Flase):
reading=reading+1
return reading
651/12/2021 IoT Devices -Raspberry Pi

Python Code
# Example code Interfacing a light Sensor (LDR) with Raspberry Pi
import RPi.GPIOas GPIO
import time
GPIO.setmode(GPIO.BCM)
ldr_threshold= 1000
LDR_PIN = 18
LIGHT_PIN = 25
def readLDR(PIN):
reading = 0
GPIO.setup(LIGHT_PIN, GPIO.OUT)
GPIO.output(PIN, false)
time.sleep(0.1)
GPIO.setup(PIN, GPIO.IN)
while (GPIO.input(PIN) ==Flase):
reading=reading+1
return reading
661/12/2021 IoT Devices -Raspberry Pi

Python Code to Toggle the LED
def switchOnLight(PIN):
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, True)
def switchOffLight(PIN):
GPIO.setup(PIN, GPIO.OUT)
GPIO.output(PIN, False)
while True:
ldr_reading= readLDR(LDR_PIN)
if ldr_reading< ldr_threshold:
switchOnLight(LIGHT_PIN)
else:
switchOffLight(LIGHT_PIN)
time.sleep(1)
671/12/2021 IoT Devices -Raspberry Pi

Interfacing
681/12/2021 IoT Devices -Raspberry Pi

Applications
•Therearecountlessusesforalightsensorinacircuit.Iwilljust
nameafewthatIthoughtofwhileIwaswritingupthisPPT.
•LightActivatedAlarm–Imentionedthisoneearlier,butyoucan
usetheLDRtodetectwhenitstartstogetlightsoyoucansoundan
alarmtowakeyouup.Iftheprogramandsensorareaccurate,then
youcanhavethealarmslowlygetlouderasitgetslighter.
•Gardenmonitor–Alightsensorcouldbeusedinagardentocheck
howmuchsunacertainareaofthegardenisgetting.Thiscouldbe
usefulinformationifyou’replantingsomethingthatneedslotsof
sunorviceversa.
•RoomMonitor–Wanttomakesurelightsarealwaysturnedoffin
acertainroom?Youcouldusethistoalertyouwheneversomelight
isdetectedwhereitshouldn’tbe.
691/12/2021 IoT Devices -Raspberry Pi

Problem In This Method
•Thebiggestproblemofthiscircuitisthefactthat
thePidoesn’thaveanyanaloguepins.They’re
alldigital,sowecan’taccuratelymeasurethe
varianceinresistanceonourinput.
•Thislackofanaloguepinswasn’taproblemin
themotionsensortutorialsincetheoutputfrom
itwaseitherhighorlow(Digital).
•Instead,wewillmeasurethetimeittakesforthe
capacitortochargeandsendthepinhigh.
•Thismethodisaneasybutinaccuratewayof
tellingwhetheritislightordark.
701/12/2021 IoT Devices -Raspberry Pi

Solution
•Ifyouwanttomakealightcontrolledswitch,asinglephotoresistor
mightbeuselesssinceyouwillneedthedigitalsignalaccordingtothe
brightness.Thismoduleisdesignedforthatpurpose.
–usingahighqualityphotoresistor
–workingvoltage:3.3~5V
–output:digitalswitching(LOWorHIGHvoltageonDpin)andanalogsignal
(voltageoutputonApin)
–usingawidevoltageLM393comparatorthathasgoodwaveform
–outputcurrent>=15mA,candirectlylightLED.
–withadjustablepotentiometertoadjustthesensitivity
–hastwoM2.5mountingholes
•Thismoduleisverysensitivetoambientlight,andisverysuitablefor
detectingbrightnessofambientlight.Theoutputsignalcantrigger
RaspberryPi,microcontrollerlikeArduino,orotherdigitalrelay
modules.
•Whentheambientlightintensityislowerthanthepredefined
threshold,theoutputsignalishigh.Whenthelightintensityreachesor
exceedsthethreshold,thesignaloutputislow.
711/12/2021 IoT Devices -Raspberry Pi

Python programming with Raspberry PI with focus of
-Interfacing external gadgets
-Controlling output
-Reading input from pins

Sending an E-Mail on Switch Press
731/12/2021 IoT Devices -Raspberry Pi

Components Reuired
•You'll need the following components to
connect the circuit.
•1. Raspberry Pi
2. LED
3. Resistor -330 ohm
4. Breadboard
5. Button / Switch
6. 2 Male-Female Jumper Wires
741/12/2021 IoT Devices -Raspberry Pi

Components
751/12/2021 IoT Devices -Raspberry Pi

Switch / Button
•Buttonsareacommoncomponentusedto
controlelectronicdevices.
•Theyareusuallyusedasswitchestoconnect
ordisconnectcircuits.
•Althoughbuttonscomeinavarietyofsizes
andshapes,theoneusedhereisa6mmmini-
buttonasshowninthefollowingpictures.
•Pinspointedoutbythearrowsofsamecolor
aremeanttobeconnected.
761/12/2021 IoT Devices -Raspberry Pi

Switch / Button
771/12/2021 IoT Devices -Raspberry Pi

CIRCUIT Diagram
781/12/2021 IoT Devices -Raspberry Pi

How It Is Works
•SendinganemailwiththePiusingPythonisn’tthatdifficult.
•Wearegoingtocreatetheemailcontentincodeandusean
externalemailprovidertoactasthemailserversendtheemail.
•Becauseweareusingcodetogeneratetheemail,wecan
dynamicallycreatethecontentwesendbasedonsensorreadings,
timeofday,orjustaboutanythingelseyoucanimagine!
•InthisexamplewearegoingtouseGoogle/Gmailtoprovideemail
services.
•WewillcreateaGmailaccountspecificallyforthisdeviceandgive
thePipermissiontosendwiththisaccount.
•Donotuseyournormalemailaddress–theemailaddressand
passwordarestoredinplaintextinyourcode!
791/12/2021 IoT Devices -Raspberry Pi

Set GMAIL Permissions
•ToaccessaGmailaccountusinganexternal
deviceliketheRaspberryPi,permissionfor“less
secureapps”willhavetobeenabled.
•Whenloggedinasyournewemailaccountyou
can jump over
tohttps://myaccount.google.com/lesssecureapps
andenablethissetting.
•SincemostpeoplehaveseveralGoogleaccounts,
justbesureyouareusingtherightaccountwhen
youenablethissetting!
801/12/2021 IoT Devices -Raspberry Pi

811/12/2021 IoT Devices -Raspberry Pi

SMTP Library
•Firstwearegoingtostartbyaddinginthe
smtplibraryreference.Thisgivesustheemail
toolswearegoingtoneed.
821/12/2021 IoT Devices -Raspberry Pi

E-Mail Variables
•Weneedtostoreabunchofinformationfor
sendingoutemailsaswell.
•TheSMTPServerandSMTPportarenotgoingto
change,butbesuretoupdatetheemailaddress
andpasswordinyourcodetomatchthe
credentialsfortheGmailaccountyoucreated
earlier.
831/12/2021 IoT Devices -Raspberry Pi

How to set up BOARD and GPIO
numbering schemes
•TherearetwokindsofInputandOutputpinnumberingfortheRaspberrypi.Oneisthe
BCMandtheotherisBOARD.Basicallythesepinnumberingsareusefulforwriting
pythonscriptfortheRaspberryPi.
•GPIO BOARD–This type of pin numbering refers to the number of the pin in the plug, i.e,
the numbers printed on the board, for example, P1. The advantage of this type of
numbering is, it will not change even though the version of board changes.
•GPIO BCM–The BCM option refers to the pin by “Broadcom SOC Channel. They signify
the Broadcom SOC channel designation. The BCM channel changes as the version number
changes.
•Note: It is very important to wire the GPIO pins with limited resistors to avoid serious
damage to the Raspberry Pi. LEDs must have resistors to limit the current passing through
them. The motors should not be connected to the GPIO pins directly.
•InRPi.GPIOyoucanuseeitherpinnumbers(BOARD)ortheBroadcomGPIOnumbers
(BCM),butyoucanonlyuseonesystemineachprogram.
•Bothhaveadvantagesanddisadvantages.
•Ifyouusepinnumbers,youdon’thavetobotheraboutrevisionchecking,asRPi.GPIO
takescareofthatforyou.Youstillneedtobeawareofwhichpinsyoucanandcan’tuse
though,sincesomearepowerandGND.
•IfyouuseGPIOnumbers,yourscriptswillmakebettersenseifyouuseaGertboard,
whichalsousesGPIOnumbering.IfyouwanttousetheP5headerforGPIO28-31,you
havetouseGPIOnumbering.IfyouwanttocontroltheLEDonaPicameraboard(GPIO5)
youalsohavetouseGPIOnumbering.
841/12/2021 IoT Devices -Raspberry Pi

Raspberry Pi Numbering Schemes
851/12/2021 IoT Devices -Raspberry Pi

How to set up a GPIO port as an input
•Usethefollowinglineofcode…
GPIO.setup(Port_or_pin,GPIO.IN)
•…changingPort_or_pintothenumberoftheGPIOportorpinyou
wanttouse.I’mgoingtousetheBCMGPIOnumberingandport
GPIO25,soitbecomes…
GPIO.setup(25,GPIO.IN)
861/12/2021 IoT Devices -Raspberry Pi

Reading inputs
•InputsareBooleanvalues:1or0,GPIO.HIGHorGPIO.LOW,
TrueorFalse(thiscorrespondstothevoltageontheport:
0V=0or3.3V=1).Youcanreadthevalueofaportwiththis
code…
GPIO.input(25)
871/12/2021 IoT Devices -Raspberry Pi

GPIO Pin Assignment
881/12/2021 IoT Devices -Raspberry Pi

E-Mail Sender
•Next,wearegoingtowritethechunkofcode
thatactuallysendstheemail.
•Thiscreatestheemail,formatsitcorrectly,
createstheconnectiontoGmail,logsin,and
sendstheemail.
•Itisquiteafewlinesofcodesowearegoing
toputitintoacustomClass–thatwaywecan
writethiscodeonce,butcallitanytimewe
wanttosendanemailinourprogram.
891/12/2021 IoT Devices -Raspberry Pi

Create Headers
901/12/2021 IoT Devices -Raspberry Pi

Connect To GAMIL Server
•ExtendedHELO(EHLO)isanExtendedSimpleMailTransferProtocol(ESMTP)commandsentbyanemailserverto
identifyitselfwhenconnectingtoanotheremailservertostarttheprocessofsendinganemail.
•Itisfollowedwiththesendingemailserver'sdomainname.TheEHLOcommandtellsthereceivingserveritsupports
extensionscompatiblewithESMTP.
•SSL, TLS, and STARTTLS refer to standard protocols used to secure email transmissions.
•SSL (Secure Sockets Layer) and its successor, Transport Layer Security (TLS),provide a way to encrypt a communication
channel between two computers over the Internet.In most cases, theterms SSL and TLS can beused interchangeably
unless you’re referring to a specific version of the protocol.
•BecauseTLS and SSLare application-layer protocols, senders and receivers need to know that they are beingused to
encrypt emails during transit. That’s where STARTTLS comes into play.
•STARTTLS is an email protocol command that tells an email server that an email client, including an email client running
in a web browser, wants to turn an existing insecure connection into a secure one. (By the way, the use of “TLS” in the
STARTTLS command name does not mean that it only works with the TLS security protocol. It works with SSL too.)
•StartTLShas become the most populare-mail encryption methodamong internet providers, as it facilitates the use of
many different domains and certificates on one server
911/12/2021 IoT Devices -Raspberry Pi

Login To Gmail
921/12/2021 IoT Devices -Raspberry Pi

Send Email & Exit
931/12/2021 IoT Devices -Raspberry Pi

941/12/2021 IoT Devices -Raspberry Pi

E-Mail Contents
•TheClasswewroteinthelaststepsendsouttheemail.
•Theclasstakesthreearguments(piecesofinformationwespecifywhen
weusethecodetosendanemail)andconstructstheemailbefore
sending.
•Thesethreeexternalcomponentsare
–therecipientoftheemail,
–asubjectlinefortheemail,and
–thetextyouwanttohaveinthebodyoftheemail.
•Thesethreepiecesofinformationarestoredinthreevariables(sendTo,
emailSubject,andemailContent).
•Thisway,ourcodeiscapableofsendingemailstodifferentpeople,with
differentsubjectlines,anddifferentemailcontentwithouthavingtowrite
adifferentsenderforeachnewcontact/emailmessage.
•Addthethreevariablesandbesuretosettherecipienttosomewhereyou
wanttoreceiveyourfirsttestemail
951/12/2021 IoT Devices -Raspberry Pi

E-Mail Contents
•Example
–emailContent= ‘Switch pressed on Raspberry Pi’
961/12/2021 IoT Devices -Raspberry Pi

Calling the E-Mail Class
•Nowthatwehaveeverythingsetup–sendinganemail
isassimpleascallingtheEmailerClasswiththethree
arguments(sendTo,emailSubject,andemailContent).
•Itwillthencreateandsendtheemailbasedonthose
parameters.
•Sendsanemailtothe"sendTo"addresswiththe
specified"emailSubject"asthesubjectand
"emailContent"astheemailcontent.
971/12/2021 IoT Devices -Raspberry Pi

Example PYTHON Code for Sending an
Email on Switch Press
•Hereisaquickexampleofthiscodebeing
usedtosendanemailanytimeabuttonis
pressed.
•Totryitout,connectamomentarybuttonto
GPIO17andGND.
•YouwillalsoneedtochangeyourGmail
SenderEmailandPassword,alongwiththe
recipientatthebottom.
981/12/2021 IoT Devices -Raspberry Pi

Python Code
import smtplib
import RPi.GPIOas GPIO
import time
#Email Variables
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
GMAIL_USERNAME = '[email protected]' #change this to match your gmailaccount
GMAIL_PASSWORD = 'yourPassword'#change this to match your gmailpassword
#Set GPIO pins to use BCM pin numbers
GPIO.setmode(GPIO.BCM)
#Set digital pin 17(BCM) to an input
GPIO.setup(17, GPIO.IN)
#Set digital pin 17(BCM) to an input and enable the pullup
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#Event to detect button press
GPIO.add_event_detect(17, GPIO.FALLING)
991/12/2021 IoT Devices -Raspberry Pi

Python Code (Contd.,)
class Emailer:
def sendmail(self, recipient, subject, content):
#Create Headers
headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
"MIME-Version: 1.0", "Content-Type: text/html"]
headers = "\r\n".join(headers)
#Connect to Gmail Server
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.ehlo()
session.starttls()
session.ehlo()
#Login to Gmail
session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
#Send Email & Exit
session.sendmail(GMAIL_USERNAME, recipient, headers + "\r\n\r\n" + content)
session.quit
sender = Emailer()
1001/12/2021 IoT Devices -Raspberry Pi

Python Code (Contd.,)
while True:
if GPIO.event_detected(17):
sendTo= '[email protected]'
emailSubject= "Button Press Detected!"
emailContent= "The button has been pressed at: " + time.ctime()
sender.sendmail(sendTo, emailSubject, emailContent)
print("Email Sent")
time.sleep(0.1)
•Oncetheemailandpasswordfieldsareupdated,runthiscodebyhitting“F5”onthe
keyboard.
•Whenthebuttonisdepressed,anemailshouldbereceivedatthereceivingaddressa
momentlaterwiththetimethebuttonwaspressed.
1011/12/2021 IoT Devices -Raspberry Pi

Interfacing
1021/12/2021 IoT Devices -Raspberry Pi

Demonstration Video
•Video Link
1031/12/2021 IoT Devices -Raspberry Pi

Thank You
1041/12/2021 IoT Devices -Raspberry Pi