Internet of Things With Raspberry Pi and Arduino
Internet of Things With Raspberry Pi and Arduino
Internet of Things With Raspberry Pi and Arduino
RASPBERRY PI AND
ARDUINO
Rajesh Singh, Anita Gehlot, Lovi Raj Gupta,
Bhupendra Singh, and Mahendra Swain
Internet of Things with
Raspberry Pi and Arduino
Internet of Things with
Raspberry Pi and Arduino
Rajesh Singh
Professor, School of Electronics & Electrical Engineering
Lovely Professional University, India
Anita Gehlot
Associate Professor, School of Electronics & Electrical Engineering
Lovely Professional University, India
Lovi Raj Gupta
Executive Dean
Lovely Professional University, India
Bhupendra Singh
Managing Director
Schematics Microelectronics, India
Mahendra Swain
Assistant Professor
MIET, Jammu, India
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
This book contains information obtained from authentic and highly regarded sources. Reasonable efforts
have been made to publish reliable data and information, but the author and publisher cannot assume
responsibility for the validity of all materials or the consequences of their use. The authors and publishers
have attempted to trace the copyright holders of all material reproduced in this publication and apologize
to copyright holders if permission to publish in this form has not been obtained. If any copyright material
has not been acknowledged please write and let us know so we may rectify in any future reprint.
Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted,
or utilized in any form by any electronic, mechanical, or other means, now known or hereafter invented,
including photocopying, microfilming, and recording, or in any information storage or retrieval system,
without written permission from the publishers.
For permission to photocopy or use material electronically from this work, please access www.copyright.
com (http://www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood
Drive, Danvers, MA 01923, 978-750-8400. CCC is a not-for-profit organization that provides licenses and
registration for a variety of users. For organizations that have been granted a photocopy license by the
CCC, a separate system of payment has been arranged.
Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are
used only for identification and explanation without intent to infringe.
Preface.......................................................................................................................xi
Acknowledgments............................................................................................... xiii
Authors....................................................................................................................xv
Section I Introduction
2. Sensors............................................................................................................. 13
2.1 Sensors Classification............................................................................ 13
2.2 Working Principle of Sensors............................................................... 15
2.3 Criteria to Choose a Sensor.................................................................. 17
2.4 Generation of Sensors........................................................................... 17
v
vi Contents
3.4.11 OpenRemote............................................................................. 23
3.4.12 Arrayent Connect TM.............................................................. 23
3.4.13 Arkessa...................................................................................... 24
3.4.14 Oracle IoT Cloud...................................................................... 24
3.4.15 ThingWorx................................................................................ 24
3.4.16 Nimbits...................................................................................... 24
3.4.17 InfoBright.................................................................................. 24
3.4.18 Jasper Control Center.............................................................. 24
3.4.19 AerCloud................................................................................... 24
3.4.20 Echelon...................................................................................... 25
3.4.21 ThingSpeak............................................................................... 25
3.4.22 Plotly.......................................................................................... 25
3.4.23 GroveStreams........................................................................... 25
3.4.24 IBM IoT...................................................................................... 25
3.4.25 Microsoft Research Lab of Things......................................... 25
3.4.26 Blynk.......................................................................................... 25
3.4.27 Cayenne APP............................................................................ 26
3.4.28 Virtuino APP............................................................................ 26
4. Basics of Arduino.......................................................................................... 29
4.1 Introduction to Arduino....................................................................... 29
4.1.1 Arduino Uno............................................................................. 29
4.1.2 Arduino Mega..........................................................................30
4.1.3 Arduino Nano.......................................................................... 31
4.2 Arduino IDE........................................................................................... 33
4.2.1 Steps to Install Arduino IDE.................................................. 33
4.3 Basic Commands for Arduino............................................................. 37
4.4 LCD Commands.................................................................................... 37
4.5 Serial Communication Commands..................................................... 38
4.6 Play with LED and Arduino................................................................ 38
4.6.1 Sketch......................................................................................... 40
4.7 Play with LCD with Arduino............................................................... 40
4.7.1 Sketch.........................................................................................43
Bibliography......................................................................................................... 187
Index...................................................................................................................... 189
Preface
xi
Acknowledgments
xiii
Authors
xv
xvi Authors
She has been awarded with the Certificate of Appreciation from the
University of Petroleum and Energy Studies for exemplary work. She has been
honored with the Certificate of Appreciation from Rashtryapati Bhawan for
a mentoring project through the Gandhian Young Technological Innovation
Award 2018. She has published 15 books in the areas of embedded systems and
Internet of Things with reputed publishers like CRC/Taylor & Francis Group,
Bentham Science, Narosa, GBS, IRP, NIPA, River Publisher, and RI Publications.
She is an editor to a special issue published by the AISC book series at Springer
with the title Intelligent Communication, Control and Devices, 2018.
Introduction
1
Introduction to Internet of Things
3
4 Internet of Things with Raspberry Pi and Arduino
Application
RES TAPI, JSON-IPSO objects, Binary objects
layer
Transport
layer CoAP, MQTT, XMPP, AMQP, LLAP, DDS, SOAP, UDP, TCP, DTLS
Physical
layer Devices, objects, things
FIGURE 1.1
OSI model for IoT protocols.
Introduction to Internet of Things 7
13
14 Internet of Things with Raspberry Pi and Arduino
1. Accuracy
2. Cost
3. Range of communication
4. Repeatability
5. Resolution
6. Environmental constraints
7. Data calibration
19
20 Internet of Things with Raspberry Pi and Arduino
3.4.1 KAA
KAA is an IoT middleware platform and open-source framework for build-
ing smart connections for end-to-end IoT solutions with Apache License 2.0.
It provides services for data analysis, visualization, and cloud service for IoT
systems (http://www.kaaproject.org/).
3.4.3 Temboo
Temboo is a cloud-based platform for application code generation. It involves
less wiring and coding of hardware and software. It has more than 90 inbuilt
libraries named “Choreos” for third-party services, including Yahoo weather,
Twilio telephony, eBay product shopping, Flickr photo management, Amazon
cloud, Twitter microblogging, Facebook Graph API, Google analytics, PayPal
payment, Uber vehicle confirmation, YouTube video streaming, and many
more (https://temboo.com).
3.4.4 SensorCloud
SensorCloud is an IoT cloud that provides the Platform as a Service (PasS) to
gather, visualize, monitor, and analyze the information coming into sensors
connected by wire or wirelessly. It allows the data to be analyzed with com-
plex mathematical algorithms (http://www.sensorcloud.com).
3.4.5 Carriots
Carriots is platform that helps anyone to build quick IoT applications. It saves
time, cost, and troubles. The PasS is designed to add features like remote
device management and control, rule-based listeners’ activity logging, trig-
gering custom alarms, and data export (https://carriots.com).
3.4.6 Xively
Xively is a gravity cloud technology-based IoT cloud service. It helps compa-
nies manage their products by addressing various features like scalability,
reliability, and secure. It is easy to integrate with devices but has minimum
notification services (https://xively.com).
IoT Design Methodology 23
3.4.7 Etherios
Etherios supports comprehensive products and services for connected enter-
prises. Its cloud is designed on the PaaS model to enable users for connecting
product and gain real-time visibility into their assets. It is a specialized cloud,
but developers are restricted with limited devices (http://www.etherios.com).
3.4.8 thethings.io
thethings.io is a platform that gives a complete solution for the back-end
developer with easy and flexible application program interfaces (APIs). thet-
hings.io is a hardware agnostic that allows the connection of any device that
is capable of using MQTT, CoAP protocols, HTTP, or WebSockets (https://
thethings.io).
3.4.10 Exosite
Exosite is modular, enterprise-grade IoT software platform that helps to
bring connected products to the market. It has a cloud platform based on IoT
Software as a Service (SaaS), which provides real-time data visualization and
analytics support to the users. The system development is easy with it, but it
lacks in big data provisions (https://exosite.com).
3.4.11 OpenRemote
OpenRemote is an open source the IoT middleware solution, which allows
users to integrate any device—protocol—design using available resources
like iOS, Android, or web browsers. It supports open cloud services but has
a high cost (http://www.openremote.com).
3.4.13 Arkessa
Arkessa provides services to companies to empower them with maximum
revenue and to enhance customer satisfaction. It helps companies to develop
IoT devices to enhance connectivity, monitoring, and controlling with enter-
prise. It has enterprise-enabled design facets, but its visualization apps are
not proper (http://www.arkessa.com).
3.4.15 ThingWorx
ThingWorx is a data-driven decision-making cloud. It provides M2M and
IoT services based on SQUEAL. Zero coding facility is available (https://
thingworx.com).
3.4.16 Nimbits
Nimbits is a cloud server that provides solutions to edge-computing IoT-
related services. It performs operations such as noise filtering and sends data
on the cloud. It is easy to adopt but lacking in the real-time processing of
query (http://www.nimbits.com).
3.4.17 InfoBright
InfoBright is an IoT-based analytical database platform that connects busi-
ness to store and acts on machine-generated data for a complete ecosystem
(https://www.infobright.com/index.php/internet-of-things).
3.4.19 AerCloud
AerCloud platform collects, manages, and analyzes sensory data for IoT and
M2M applications. It is scalable to M2M services but not suitable for develop-
ers (http://www.aeris.com).
IoT Design Methodology 25
3.4.20 Echelon
Echelon is an IoT-based platform for the cloud with resources like
microphones, hardware devices, and other applications. It is good for the
industrial prospective but lacks in basics for beginners (http://www.iiot.
echelon.com).
3.4.21 ThingSpeak
It is an open-source public cloud platform specially developed for IoT-based
applications. It has open API that receives real-time data. It has data storage,
monitoring, and visualization facilities (https://thingspeak.com).
3.4.22 Plotly
Plotly is a data visualization cloud service provider for the public. It provides
data storage, analysis, and visualization services. Python, R, MATLAB, and
Julia-based APIs are implemented in Plotly (https://plot.ly).
3.4.23 GroveStreams
GroveStreams is a public cloud for data visualization. It supports various
data types. It enables seamless monitoring but lacks in statistical services
(https://thingworx.com).
3.4.26 Blynk
It is an open-source platform with iOS and Android apps, which allows the
control of Raspberry Pi and Arduino over the internet. It supports a graphical
interface to build projects just by dragging the widgets. It supports many IoT
modules.
26 Internet of Things with Raspberry Pi and Arduino
Basics of Arduino
and Raspberry Pi
4
Basics of Arduino
Advantages of Arduino:
Cost: Arduino boards are less expensive compared to other micro-
controller boards.
Platform: The Arduino Software (IDE) is compatible with most of
the operating systems like Macintosh OSX, Windows, and Linux.
User friendly: The Arduino Software (IDE) is user-friendly, easy to
begin, and has flexibility for the skilled programmers.
Open source: The Arduino is an open-source software that can be
programmed with C, C++, or AVR-C languages. So a variety of
modules can be designed by users.
29
30 Internet of Things with Raspberry Pi and Arduino
FIGURE 4.1
Arduino Uno board.
TABLE 4.1
Pin Description of Arduino UNO
Pin Description
FIGURE 4.2
Arduino Mega board.
TABLE 4.2
Pin Description
Pin Description
FIGURE 4.3
Arduino Nano board.
TABLE 4.3
Pin Description of Arduino NANO
PIN Description
TABLE 4.4
Comparison Table for a Few Arduino Boards
Operating/
CPU Input Digital IO/ Analog Flash
Name Processor Speed Voltage PWM In/Out UART [kB]
FIGURE 4.4
Window Arduino IDE.
FIGURE 4.5
Selection of Arduino board.
in the Arduino IDE. To select the Arduino board, click on “Tool” and
then click on “board.” Figure 4.5 shows the selection of “Arduino
Uno.”
Step 3: Write and compile the program
Write the program in the Arduino IDE window. Then “RUN” the pro-
gram. Figure 4.6 shows the window to compile the program.
Basics of Arduino 35
FIGURE 4.6
Compile the program.
FIGURE 4.7
Window to check port of Arduino.
FIGURE 4.8
The serial port of the board.
Basics of Arduino 37
FIGURE 4.9
Window to upload the program.
FIGURE 4.10
Light-emitting diode.
Basics of Arduino 39
FIGURE 4.11
Circuit diagram to interface LED with Arduino.
40 Internet of Things with Raspberry Pi and Arduino
4.6.1 Sketch
int LED_CONTROL=4;
void setup()
{
pinMode(LED_CONTROL, OUTPUT); // initialize pin 4 as output pin
}
void loop()
{
digitalWrite(LED_CONTROL, HIGH); // Make pin 4 HIGH
delay(1000); // 1000 mS delay
digitalWrite(LED_CONTROL, LOW); // Make pin 4 HIGH
delay(1000); // 1000 mS delay
}
FIGURE 4.12
Liquid crystal display (16 × 2).
Basics of Arduino 41
FIGURE 4.13
Liquid crystal display (20 × 4).
TABLE 4.5
LCD Pin Description
Pin Description
LCD connection
Connect the components as follows:
• Arduino digital pin (13) to RS pin (4) of LCD.
• Arduino digital pin (GND) to RW pin (5) of LCD.
• Arduino digital pin (12) to E pin (6) of LCD.
42 Internet of Things with Raspberry Pi and Arduino
Figure 4.14 shows the circuit diagram of the Arduino interfacing with the
LCD.
FIGURE 4.14
Circuit diagram to read LCD.
Basics of Arduino 43
4.7.1 Sketch
#include <LiquidCrystal.h>
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
void setup()
{
lcd.begin(20, 4); // Initialize LCD
lcd.print("WELCOME"); // Print string on LCD
delay(2000); // Delay 2000mS
lcd.clear();
}
void loop()
{
lcd.setCursor(0, 1); // set cursor of LCD
lcd.print("ECE Department"); // Print string on LCD
delay(2000); // Delay 2000mS
lcd.setCursor(0, 2); // set cursor of LCD
lcd.print("Rajesh Singh"); // Print string on LCD
delay(2000); // Delay 2000mS
}
5
Basics of Raspberry Pi
45
46 Internet of Things with Raspberry Pi and Arduino
(a)
(b)
FIGURE 5.1
(a) Raspberry Pi. (b) Pin diagram of Raspberry Pi 3 B+ model.
Basics of Raspberry Pi 47
FIGURE 5.2
Micro-USB power supply.
FIGURE 5.3
SD card.
48 Internet of Things with Raspberry Pi and Arduino
FIGURE 5.4
NOOBS window.
Basics of Raspberry Pi 49
FIGURE 5.5
Raspberry Pi booting up.
FIGURE 5.6
Angry IP scanner.
FIGURE 5.7
SD formatter.
FIGURE 5.8
Win32 disk imager.
Basics of Raspberry Pi 51
FIGURE 5.9
Terminal window.
FIGURE 5.10
Command window for Raspberry Pi after command “ifconfig.”
Now remove “#” from each line of this paragraph and change the
last figures of the IP address from a range of 1 to 255 (Figure 5.14).
Once changes are made, exit the window by using Ctrl+x and
save the changes by click on “Yes” (Figure 5.15).
4. Reboot the Raspberry Pi by the command “reboot” (Figure 5.16).
5. Check the static IP address of Raspberry by the command “ifcon-
fig” (Figure 5.17).
54 Internet of Things with Raspberry Pi and Arduino
FIGURE 5.11
Nano editor for static IP address configuration.
FIGURE 5.12
Window to configure IP address.
Basics of Raspberry Pi 55
FIGURE 5.13
Static IP configuration.
FIGURE 5.14
Static IP address.
56 Internet of Things with Raspberry Pi and Arduino
FIGURE 5.15
“Yes” to changes.
FIGURE 5.16
Reboot the Raspberry Pi.
Basics of Raspberry Pi 57
FIGURE 5.17
Static IP address of Raspberry Pi.
• rc.local
• .bashrc
• init.d tab
• systemd
• crontab
The Pi runs this program at bootup before the start of other services.
The Pi will not complete its boot process if the ampersand is not included
and program runs continuously. The ampersand allows the command to run
in a separate process and continue booting with running the main process.
Now, reboot the Pi to test it: “sudo reboot.”
FIGURE 5.18
Remote desktop connection.
Basics of Raspberry Pi 59
5.9 Pi Camera
Pi camera is a module with a Python interface. Install Picamera by the com-
mand “sudo apt-get install python –picamera.”
FIGURE 5.19
Verify window.
60 Internet of Things with Raspberry Pi and Arduino
FIGURE 5.20
Window to enable I2C driver.
FIGURE 5.21
i2c-dev.
62 Internet of Things with Raspberry Pi and Arduino
NO T E : The installation can take a few minutes, depending on how busy the
server is.
FIGURE 5.22
Window after reboot test command.
Basics of Raspberry Pi 63
Commands:
importRPi.GPIO as X
# This is to access GPIO pins of Raspberry Pi as the name “X” indicated
in the command.
import time
# Imports the Time library so that we can pause the script later on.
X.setmode(X.BCM)
# Pins are referred as GPIO numbers, as BCM mode is selected.
X.setwarnings(False)
# This command is not to print GPIO warning messages on the screen.
64 Internet of Things with Raspberry Pi and Arduino
X.setup(21,X.OUT)
# This is to define GPIO 21 as output pin.
print(“Two LED ON”)
# This is to print the string on the terminal.
X.output(21, True) or X.output(21, HIGH)
# This is to turn the GPIO 21 pin “on.”
time.sleep(1)
# To pause the Python program for 1 s.
exceptKeyboardInterrupt:
# End program with keyboard.
GPIO.cleanup()
# Reset GPIO settings.
FIGURE 5.23
Circuit diagram of the Raspberry Pi interfacing with LED.
def loop():
while True:
print ("BOTH LED on") # print string on terminal
RAJ.output(ledPin1, RAJ.HIGH) # turn on LED1
RAJ.output(ledPin2, RAJ.HIGH) # turn on LED2
wait.sleep(1.0) # delay of 1 Sec
print("BOTH LED off") # print string on terminal
RAJ.output(ledPin1, RAJ.LOW) # turn off LED1
RAJ.output(ledPin2, RAJ.LOW) # turn off LED2
wait.sleep(1.0) # wait 1 sec
defendprogram():
RAJ.output(ledPin1, RAJ.LOW) # turn off LED1
RAJ.output(ledPin2, RAJ.LOW) #turn off LED2
RAJ.cleanup() # clean GPIOs
if __name__ == '__main__': # Main program to call functions
setup()
try:
loop()
exceptKeyboardInterrupt: # keyboard interrupt to stop program
endprogram()
importRPi.GPIO as RAJ
RAJ.setup(23, RAJ.IN, pull_up_down=RAJ.PUD_DOWN)
RAJ.setup(24, RAJ.IN, pull_up_down=RAJ.PUD_UP)
5.15.1 Recipe
importRPi.GPIO as RAJ
RAJ.setmode(GPIO.BCM) # use pi in BCM mode
RAJ.setup(23, RAJ.IN, pull_up_down = RAJ.PUD_DOWN) # set pin as
input
RAJ.setup(24, RAJ.IN, pull_up_down = RAJ.PUD_UP) # set pin as input
while True:
if(RAJ.input(23) ==1):
print("pressed button 1") # print string on terminal
if(RAJ.input(24) == 0):
print("pressed button2") # print string on terminal
RAJ.cleanup() # clean all GPIOs
Connections:
• Connect one terminal of the switch to ground and other terminal
to GPIO21 of Raspberry Pi.
• Connect one resistor of 10 K between +5 V and GPIO21 of
Raspberry Pi.
• Connect the anode of the LED to GPIO20 of Raspberry Pi through
a resistor and the cathode to ground.
Figure 5.24 shows the circuit diagram of the Raspberry Pi interfacing with
the switch.
68 Internet of Things with Raspberry Pi and Arduino
FIGURE 5.24
Circuit diagram of the Raspberry Pi interfacing with switch in “Pull-down” configuration.
Connections:
• Connect one terminal of the switch to +5 V and the other termi-
nal to GPIO21 of Raspberry Pi.
• Connect one resistor of 10 K between the ground and GPIO21 of
Raspberry Pi.
• Connect the anode of the LED to GPIO20 of Raspberry Pi through
a resistor and the cathode to ground.
Figure 5.25 shows the circuit diagram of the Raspberry Pi interfacing with
the switch.
FIGURE 5.25
Circuit diagram of the Raspberry Pi interfacing with switch in “Pull-up” configuration.
70 Internet of Things with Raspberry Pi and Arduino
Connections:
• Connect the “base” of transistor 2N222 to GPIO26 of Raspberry Pi.
• Connect “emitter” of transistor to the ground.
Basics of Raspberry Pi 71
FIGURE 5.26
Circuit diagram for interfacing of relay with Raspberry Pi.
5.17.1 Recipe
importRPi.GPIO as MAHE # import pi GPIOs lib
import time as wait # wait time lib
MAHE.setmode(MAHE.BCM) # use pi pins in BCM mode
MAHE.setup(26, MAHE.OUT) # set pin 26 to output pin
while (True):
GPIO.output(26, MAHE.HIGH) // make pin 26 pin to HIGH
print(' relay ON') # print string on terminal
wait.sleep(5) # delay of 5 Sec
GPIO.output(26, GPIO.LOW)
print('relay OFF') # print string on terminal
wait.sleep(5) # delay of 5 Sec
72 Internet of Things with Raspberry Pi and Arduino
Connections:
• Connect pin2 (IN1) of L293D to GPIO26 of Raspberry Pi.
• Connect pin7 (IN2) of L293D to GPIO19 of Raspberry Pi.
• Connect pin10 (IN3) of L293D to GPIO13 of Raspberry Pi.
• Connect pin15 (IN4) of L293D to GPIO6 of Raspberry Pi.
• Connect pin3 (OUT1) of L293D to one terminal of motor1.
• Connect pin6 (OUT2) of L293D to another terminal of motor1.
FIGURE 5.27
Circuit diagram for interfacing of DC motors with Raspberry Pi.
Basics of Raspberry Pi 73
5.18.1 Recipe
importRPi.GPIO as MAHI #import GPIO as MAHI
import time as wait #include time library
M1_PIN1=26 # assign variable to GPIO26
M1_PIN2=19 # assign variable to GPIO19
M2_PIN1=13 # assign variable to GPIO13
M2_PIN2=6 # assign variable to GPIO6
try:
while True:
MAHI.output(M1_PIN1, True) #make pin 26 to HIGH
MAHI.output(M1_PIN2, False) #make pin 19 to LOW
MAHI.output(M2_PIN1, True) #make pin 13 to HIGH
MAHI.output(M2_PIN2, False) #make pin 6 to LOW
print("Both Motor Forward") #print string on terminal
wait.sleep(10) # delay of 10 sec
MAHI.output(M1_PIN1, False) #make pin 26 to LOW
MAHI.output(M1_PIN2, True) #make pin 19 to HIGH
MAHI.output(M2_PIN1, False) #make pin 13 to LOW
MAHI.output(M2_PIN2, True) #make pin 6 to HIGH
print("Both Motor Reverse") #print string on terminal
wait.sleep(10) # delay of 10 sec
exceptkeyboardInterrupt:
MAHI.cleanup() # clean all GPIOs
74 Internet of Things with Raspberry Pi and Arduino
def loop():
# forward movement
MAHI.output(M11,MAHI.HIGH) # set M11 to HIGH
GPIO.output(M12,MAHI.LOW) # set M12 to LOW
GPIO.output(M1E,MAHI.HIGH) # set M1E to HIGH
wait.sleep(5) // delay of 5 Sec
# for reverse movement
MAHI.output(M11,MAHI.LOW) # set M11 to LOW
MAHI.output(M12,MAHI.HIGH) # set M12 to HIGH
MAHI.output(M1E,MAHI.HIGH) # set M1E to HIGH
wait.sleep(5) // delay of 5 Sec
# for stop movement
MAHI.output(M1E,MAHI.LOW) # set M1E to LOW
def destroy():
MAHI.cleanup() # clean GPIOs
if __name__ == '__main__': # Program start from here
setup()
try:
loop()
exceptKeyboardInterrupt:
destroy() # stop the execution
Basics of Raspberry Pi 75
Connections:
• Connect pin1 (Vss), pin5, (RW) and pin16 (LED-) of LCD to ground.
• Connect pin2 (Vcc) and pin15 (LED+) of LCD to +5 V DC.
• Connect pin3 (VEE) of LCD to output of 10 K potentiometer and
connect other two terminals of potentiometer to +5 V DC and
ground.
• Connect pin4 (RS) of LCD to GPIO26 of Raspberry Pi.
• Connect pin6 (E) of LCD to GPIO19 of Raspberry Pi.
• Connect pin11 (D4) of LCD to GPIO13 of Raspberry Pi.
• Connect pin12 (D5) of LCD to GPIO6 of Raspberry Pi.
• Connect Pin13 (D6) of LCD to GPIO5 of Raspberry Pi.
• Connect Pin14 (D7) of LCD to GPIO21 of Raspberry Pi.
FIGURE 5.28
Circuit diagram for interfacing of LCD with Raspberry Pi.
76 Internet of Things with Raspberry Pi and Arduino
def main():
RAJ.setwarnings(False) # remove the warnings
RAJ.setmode(RAJ.BCM) # Use BCM GPIO numbers
RAJ.setup(RAJ_LCD_E, RAJ.OUT) # setup enable pin as output
RAJ.setup(RAJ_LCD_RS, RAJ.OUT) # setup RS pin as output
RAJ.setup(RAJ_LCD_D4, RAJ.OUT) # setup D4 pin as output
RAJ.setup(RAJ_LCD_D5, RAJ.OUT) # setup D5 pin as output
RAJ.setup(RAJ_LCD_D6, RAJ.OUT) # setup D6 pin as output
RAJ.setup(RAJ_LCD_D7, RAJ.OUT) # setup D7 pin as output
RAJ_lcd_init() # initialise LCD
while True:
RAJ_lcd_string("R Singh ",LCD_LINE_1) # print some text to ROW 1
of LCD
RAJ_lcd_string(" Presents ",LCD_LINE_2) # print some text to ROW2
of LCD
wait.sleep(3) # delay of 3 Sec
RAJ_lcd_string("123456789012345",LCD_LINE_1)
RAJ_lcd_string("ABCDEFGHIJK",LCD_LINE_2)
wait.sleep(3)# delay of 3 Sec
78 Internet of Things with Raspberry Pi and Arduino
defRAJ_lcd_init():
RAJ_lcd_display(0x28,RAJ_LCD_CMD) # choose 4 bit mode and rows
RAJ_lcd_display(0x0C,RAJ_LCD_CMD) # To ON the display, no cursor
blink
RAJ_lcd_display(0x01,RAJ_LCD_CMD) # Clear the contents of LCD
Wait.sleep(RAJ_E_DELAY) # delay
defRAJ_lcd_display(bits, mode):
RAJ.output(RAJ_LCD_RS, mode) # set Mode
RAJ.output(RAJ_LCD_D4, False) # make D4 pin of LCD LOW
RAJ.output(RAJ_LCD_D5, False) # make D5 pin of LCD LOW
RAJ.output(RAJ_LCD_D6, False) # make D6 pin of LCD LOW
RAJ.output(RAJ_LCD_D7, False) # make D7 pin of LCD LOW
if bits&0x10==0x10:
RAJ.output(RAJ_LCD_D4, True) # make D4 pin of LCD HIGH
if bits&0x20==0x20:
RAJ.output(RAJ_LCD_D5, True) # make D5 pin of LCD HIGH
if bits&0x40==0x40:
RAJ.output(RAJ_LCD_D6, True) # make D6 pin of LCD HIGH
if bits&0x80==0x80:
RAJ.output(RAJ_LCD_D7, True) # make D7 pin of LCD HIGH
RAJ_lcd_toggle_enable()
defRAJ_lcd_toggle_enable():
wait.sleep(RAJ_E_DELAY) # delay
RAJ.output(RAJ_LCD_E, True) # make E pin to HIGH
wait.sleep(RAJ_E_PULSE) # delay
RAJ.output(RAJ_LCD_E, False) # make E pin to LOW
wait.sleep(RAJ_E_DELAY) # delay
defRAJ_lcd_string(message,line):
message = message.ljust(RAJ_LCD_WIDTH," ")
RAJ_lcd_display(line, RAJ_LCD_CMD)
for i in range(RAJ_LCD_WIDTH):
RAJ_lcd_display(ord(message[i]),RAJ_LCD_CHR)
if __name__ == '__main__':
try:
main()
Basics of Raspberry Pi 79
exceptKeyboardInterrupt:
pass
finally:
RAJ_lcd_display(0x01, RAJ_LCD_CMD)
RAJ.cleanup() # clean all GPIOs
Connections:
• Connect pin1 (Vss) and pin16 (LED-) of LCD and pin (GND) of the
I2C driver to ground.
• Connect pin2 (Vcc) and pin15 (LED+) of LCD and pin (Vcc) of the I2C
driver to +5 V DC.
FIGURE 5.29
Circuit diagram for LCD interfacing in I2C mode.
80 Internet of Things with Raspberry Pi and Arduino
FIGURE 5.30
Setting on terminal.
Basics of Raspberry Pi 81
FIGURE 5.31
Enable I2C.
FIGURE 5.32
Reboot.
RAJ_lcd_byte(ord(message[i]),RAJ_LCD_CHR)
def main():
RAJ_lcd_init()
while True:
RAJ_lcd_string("I2C LCD<",RAJ_LCD_LINE_1) # print string on line1
on LCD
RAJ_lcd_string("Connected<",RAJ_LCD_LINE_2) # print string on
line2 on LCD
wait.sleep(3) # delay of 3 Sec
RAJ_lcd_string(">RPiSpy", RAJ_LCD_LINE_1) # print string on line1
on LCD
RAJ_lcd_string("> I2C LCD", RAJ_LCD_LINE_2) # print string on
line2 on LCD
wait.sleep(3) # delay of 3 Sec
if __name__ == '__main__':
try:
main()
exceptKeyboardInterrupt:
pass
finally:
RAJ_lcd_byte(0x01, RAJ_LCD_CMD)
FIGURE 5.33
View of DHT11 sensor.
Connections:
• Connect pin1 (Vss), pin5 (RW) and pin16 (LED-) of LCD to ground.
• Connect pin2 (Vcc), and pin15 (LED+) of LCD to +5 V DC.
• Connect pin3 (V EE) of LCD to output of 10 K potentiometer
and connect other two terminals of potentiometer to +5 V DC
and ground.
• Connect pin4 (RS) of LCD to GPIO26 of Raspberry Pi.
• Connect pin6 (E) of LCD to GPIO19 of Raspberry Pi.
• Connect pin11 (D4) of LCD to GPIO13 of Raspberry Pi.
• Connect pin12 (D5) of LCD to GPIO6 of Raspberry Pi.
• Connect pin13 (D6) of LCD to GPIO5 of Raspberry Pi.
• Connect pin14 (D7) of LCD to GPIO21 of Raspberry Pi.
• Connect pin (Vcc) and pin (GND) of DHT11 to +5 V and ground,
respectively.
• Connect output pin of DHT11 to GPIO17 of Raspberry Pi.
Basics of Raspberry Pi 85
FIGURE 5.34
Circuit diagram for the interfacing of DHT11S.
Figure 5.34 shows the circuit diagram for the interfacing of LCD and
DHT11 with Raspberry Pi.
FIGURE 5.35
Ultrasonic sensor.
and GND. The ultrasonic transmitter in the sensor generates a 40 KHz ultra-
sound, which propagates in the air and reflects back if any obstacle occurs
in its path. The distance is calculated on the basis of a time interval between
the transmitted signal and receiving it back to echo the pin of the sensor. To
generate the ultrasonic signal trigger, the pin needs to hold “HIGH” for a
minimum duration of 10 µS. Figure 5.35 shows the ultrasonic sensor.
For example, if the time for which ECHO is HIGH is 588 µS, then the distance
can be calculated with the help of the speed of sound, which is equal to 340 m/s.
Connections:
• Connect pin1 (Vss), pin5 (RW), and pin16 (LED−) of LCD to
ground.
• Connect pin2 (Vcc) and pin15 (LED+) of LCD to +5 V DC.
• Connect pin3 (VEE) of LCD to output of 10 K potentiometer, and
connect the other two terminals of the potentiometer to +5 V DC
and ground.
• Connect pin4 (RS) of LCD to GPIO26 of Raspberry Pi.
• Connect pin6 (E) of LCD to GPIO19 of Raspberry Pi.
• Connect pin11 (D4) of LCD to GPIO13 of Raspberry Pi.
88 Internet of Things with Raspberry Pi and Arduino
Figure 5.36 shows the circuit diagram for the interfacing of the LCD and
ultrasonic sensor with Raspberry Pi.
FIGURE 5.36
Circuit diagram for interfacing of ultrasonic sensor with Raspberry Pi.
Basics of Raspberry Pi 89
while True:
RAJ_dist = distance()
print ("DISTANCE = %.1f cm" % RAJ_dist)
RAJ_lcd.clear() #clear the contents of LCD
RAJ_lcd.message ('DIST = %.1f cm' % RAJ_dist)
wait.sleep(1)
exceptKeyboardInterrupt:
print("stop measurement")
ANITA.cleanup()
FIGURE 5.37
Configuring the Raspberry Pi.
FIGURE 5.38
Enable camera.
92 Internet of Things with Raspberry Pi and Arduino
2. Save with ctrl+o then press “Enter” to execute with the command
sudo python image_RAJ.py. The camera preview is shown for 10 s, and
then closed. Move the camera around to preview.
3. If the preview is upside-down, rotate it by 90, 180, or 240 degrees
with the following commands:
RAJ_camera.rotation = 180
RAJ_camera.start_preview()
wait.sleep(10)
RAJ_camera.stop_preview()
4. Alter the transparency of the camera preview by setting an alpha
level (from values 0–255):
frompicamera import PiCamera
import time as wait
RAJ_camera = PiCamera()
RAJ_camera.start_preview(alpha=200)
sleep(10)
camera.stop_preview()
5. To take still pictures, amend the code to reduce the sleep at least for
2 s and add a camera.capture() line:
camera.start_preview()
sleep(5)
RAJ_camera.capture(‘/home/pi/Desktop/image.jpg’)
RAJ_camera.stop_preview()
6. Run the code and see the camera preview open for 5 s before captur-
ing a still picture.
7. The picture is on the desktop. Double-click the file icon to open it.
8. Now try adding a loop to take five pictures:
RAJ_camera.start_preview()
for i in range(5):
wait.sleep(5)
RAJ_camera.capture(‘/home/pi/Desktop/image%s.jpg’ % i)
RAJ_camera.stop_preview()
The variable “I” contains the current iteration number, from 0 to 4, so
the images will be saved as image0.jpg, image1.jpg, and so on.
9. Pictures can be resized by using libraries like PIL and OpenCV.
This can be done with the resize parameter of the capture()
methods:
import time as wait
Basics of Raspberry Pi 93
importpicamera
withpicamera. PiCamera() as RAJ_camera:
RAJ_camera.resolution = (1024, 468)
RAJ_camera.start_preview()
wait.sleep(2)
RAJ_camera.capture(‘image.jpg’, resize=(320, 240))
FIGURE 5.39
Taskbar.
94 Internet of Things with Raspberry Pi and Arduino
wait.sleep(5)
RAJ_camera.capture(‘/home/pi/Desktop/text.jpg’)
RAJ_camera.stop_preview()
6. The default brightness is “50”; it can be altered by the commands:
RAJ_camera.start_preview()
RAJ_camera.brightness = 40
wait.sleep(5)
RAJ_camera.capture(‘/home/pi/Desktop/bright.jpg’)
RAJ_camera.stop_preview()
7. The brightness can be altered by applying the loop:
RAJ_camera.start_preview()
for i in range(100):
RAJ_camera.annotate_text = “Brightness: %s” % i
RAJ_camera.brightness = i
wait.sleep(0.1)
RAJ_camera.stop_preview()
8. The contract can also be altered by using commands:
RAJ_camera.start_preview()
for i in range(100):
RAJ_camera.annotate_text = “Contrast: %s” % i
RAJ_camera.contrast = i
wait.sleep(0.1)
RAJ_camera.stop_preview()
9. The annotation text size (value from 6 to 160) with default value 32
can be added with the command:
RAJ_camera.annotate_text_size = 50
10. The annotation colors can be altered by using the commands:
frompicamera import PiCamera, Color
11. Then other colors can also be amended by using the commands:
RAJ_camera.start_preview()
RAJ_camera.annotate_background = Color(‘blue’)
RAJ_camera.annotate_foreground = Color(‘yellow’)
RAJ_camera.annotate_text = “Hello world “
wait.sleep(5)
RAJ_camera.stop_preview()
Basics of Raspberry Pi 95
Connections:
• Connect camera to Raspberry Pi as described in Section 5.23.
• Connect pin (Vcc) and pin (GND) of PIR sensor to +5 V and
ground, respectively.
• Connect pin (OUT) of PIR sensor to GPIO21 of Raspberry Pi.
• Connect anode of LED to GPIO3 of Raspberry Pi through a 10 K
resistor and cathode of LED to ground.
Figure 5.40 shows the circuit diagram for interfacing of the PIR sensor and
camera with Raspberry Pi.
FIGURE 5.40
Circuit diagram for interfacing of PIR sensor and camera with Raspberry Pi.
96 Internet of Things with Raspberry Pi and Arduino
99
100 Internet of Things with Raspberry Pi and Arduino
FIGURE 6.1
Blank window of Arduino IDE.
Liquid Crystal
Display
(LCD)
LED
Power 1
Supply ARDUINO
12V/1A UNO
LED
2
PIR
SENSOR
FIGURE 6.2
Block diagram for PIR interfacing with Arduino.
a PIR sensor, a liquid crystal display, and an LED. The system is designed
such that “RED LED” will be “ON” if motion is detected; otherwise, “BLUE
LED” will be “ON.”
FIGURE 6.3
Circuit diagram for PIR interfacing with Arduino.
6.2.3 Sketch
#include <LiquidCrystal.h> // include library of LCD
LiquidCrystallcd(13, 12, 11, 10,9, 8); // attach LCD pin RS,E,D4,D5,D6,D7
to the given pins
int PIR_SENSOR_LOW=5; // assign pin 5 as PIR_SENSOR_LOW
int RED_LED=7; // assign pin 7 as RED_LED
int BLUE_LED=6; // // assign pin 6 as BLUE_LED
void setup()
{
Raspberry Pi and Arduino 103
Liquid Crystal
Display
(LCD)
Power
ARDUINO
Supply
UNO
12V/1A
LED
LDR
ANALOG
OUT
FIGURE 6.4
Block diagram to interface LDR with Arduino.
Raspberry Pi and Arduino 105
FIGURE 6.5
Circuit diagram for LDR sensor interfacing with Arduino.
LCD connection
• Connect Arduino digital pin 13 to RS pin(4) of LCD.
• Connect Arduino digital pin GND to RW pin(5) of LCD.
• Connect Arduino digital pin 12 to E pin(6) of LCD.
• Connect Arduino digital pin 11 to D4 pin(11) of LCD.
• Connect Arduino digital pin 10 to D5 pin(12) of LCD.
• Connect Arduino digital pin 9 to D6 pin(13) of LCD.
• Connect Arduino digital pin 8 to D7 pin(14) of LCD.
6.3.2 Sketch
#include <LiquidCrystal.h> // include library of LCD
LiquidCrystallcd(13, 12, 11, 10, 9, 8); // attach LCD pin RS,E,D4,D5,D6,D7
to the given pins
intLDR_sensor_Pin = A0; // select the input pin for the potentiometer
intLDR_sensor_ADC_Value = 0; // variable to store the value coming
from the sensor
int RED_LED=7; // assign pin 7 to RED_LED
106 Internet of Things with Raspberry Pi and Arduino
void setup()
{
void loop()
{
LDR_sensor_ADC_Value = analogRead(LDR_sensor_Pin); // read the
value from the sensor
lcd.setCursor(0,2); // set cursor on LCD
lcd.print("ADC LEVEL+LDR:"); // print string on LCD
lcd.setCursor(17,2); // set cursor on LCD
lcd.print(LDR_sensor_ADC_Value); // // print value on LCD
if(LDR_sensor_ADC_Value>=100)
{
digitalWrite(RED_LED,HIGH); // make pin7 to HIGH
delay(20); // delay of 20 mS
}
else
{
digitalWrite(RED_LED,LOW); // make pin7 to HIGH
delay(20); // delay of 20 mS
}
}
Raspberry Pi and Arduino 107
6.4.1 DC Motor
The DC-geared motors with 100 rpm 12 V are generally used for robotics
applications. They are very easy to use. They have nuts and threads on the
shafts to easily connect and internally threaded shafts for easy connection
to the wheel. Figure 6.6 shows the block diagram to interface the DC motor
with Arduino. It is comprised of an Arduino Uno, a power supply, a liquid
crystal display, a motor driver (L293D), and two DC motors.
Power
Supply ARDUINO Motor
UNO DC MOTOR
12V/1A Driver (L293D)
LEDS
FIGURE 6.6
Block diagram of DC motor interfacing with Arduino.
108 Internet of Things with Raspberry Pi and Arduino
FIGURE 6.7
Circuit diagram of DC motor interfacing with Arduino.
6.4.1.2 Sketch
#include <LiquidCrystal.h> // include library of LCD
LiquidCrystallcd(13, 12, 11, 10,9, 8); // attach LCD pin RS, E, D4, D5, D6,
D7 to the given pins
int MPIN1= 7; // assign pin 7 as MPIN1
int MPIN2= 6; // assign pin 6 as MPIN2
int MPIN3= 5; // assign pin 5 as MPIN3
int MPIN4= 4; // assign pin 4 as MPIN4
void setup()
{
pinMode(MPIN1, OUTPUT); // make MPIN1 as an output
pinMode(MPIN2, OUTPUT); // make MPIN2 as an output
pinMode(MPIN3, OUTPUT); // make MPIN3 as an output
pinMode(MPIN4, OUTPUT); // make MPIN4 as an output
lcd.begin(20,4); // initialise LCD
lcd.setCursor(0, 0); // set cursor on LCD
lcd.print("DC Motor direction"); // print string on LCD
lcd.setCursor(0, 1); // set cursor on LCD
lcd.print("control system..."); // print string on LCD
delay(1000); // delay of 1000 mS
lcd.clear(); // clear the contents of LCD
}
void loop() // infinite loop
{
digitalWrite(MPIN1, HIGH); // make MPIN1 to HIGH
110 Internet of Things with Raspberry Pi and Arduino
Liquid Crystal
Display
(LCD)
Power
ARDUINO SERVO
Supply
UNO MOTOR
12V/1A
POT
ANALOG
OUT
FIGURE 6.8
Block diagram to interface servo motor with Arduino.
position feedback. It also requires a servo drive. The drive uses the feed-
back sensor to control the rotary position of the motor precisely. This is
called a closed-loop operation. The high torque standard servo motor with
metal gears and 360° rotation can provide 11 kg/cm at 4.8 V, 13.5 kg/cm at
6 V, and 16 kg/cm at 7.2 V. Figure 6.8 shows the block diagram to interface
the servo motor with Arduino. It is comprised of an Arduino Uno, a power
supply, a liquid crystal display, a potentiometer (POT), and a servo motor.
The system is designed to control the angle of the servo motor with the
potentiometer.
Servo connection
• Connect Arduino GND to GND pin of servo motor.
• Connect Arduino +5 V to “+” terminal of servo motor.
• Connect Arduino pin(3) to PWM pin of servo motor.
POT connection
• Connect Arduino GND to GND pin of POT.
• Connect Arduino +5 V to “+” terminal of POT.
• Connect Arduino A0 pin to data out pin of POT.
112 Internet of Things with Raspberry Pi and Arduino
FIGURE 6.9
Circuit diagram to interface servo motor with Arduino.
LCD connection
• Connect Arduino digital pin (13) to RS pin(4) of LCD.
• Connect Arduino digital pin (GND) to RW pin(5) of LCD.
• Connect Arduino digital pin (12) to E pin(6) of LCD.
• Connect Arduino digital pin (11) to D4 pin(11) of LCD.
• Connect Arduino digital pin (10) to D5 pin(12) of LCD.
• Connect Arduino digital pin (9) to D6 pin(13) of LCD.
• Connect Arduino digital pin (8) to D7 pin(14) of LCD.
6.4.2.2 Sketch
#include <LiquidCrystal.h> // include library of LCD
LiquidCrystallcd(13, 12, 11, 10, 9, 8); // attach LCD pin RS,E,D4,D5,D6,D7
to the given pins
Servo myservo; // create servo object to control a servo
int POT_PIN = A0; // analog pin used to connect the potentiometer
int POT_PIN_ADC_LEVEL; // variable to read the value from the
analog pin
Raspberry Pi and Arduino 113
void setup()
{
myservo.attach(3); // attaches the servo on pin 9 to the servo object
lcd.begin(20,4); // initialise LCD
lcd.setCursor(0, 0); // set cursor on LCD
lcd.print("Servo ANALOG write "); // print string on LCD
lcd.setCursor(0, 1);// set cursor on LCD
lcd.print("system at LPU....");// print string on LCD
}
void loop()
{
POT_PIN_ADC_LEVEL = analogRead(POT_PIN); // reads POT value
in the form of levels
POT_PIN_ADC_LEVEL = map(POT_PIN_ADC_LEVEL, 0, 1023, 0, 179);
// map the value //between 0 to 180 degree for servo
myservo.write(POT_PIN_ADC_LEVEL); // sets the servo position
according to the scaled value
lcd.setCursor(0, 2); // set cursor on LCD
lcd.print("ANGLE:"); // print string on LCD
lcd.print(POT_PIN_ADC_LEVEL); // print value on LCD
delay(15); // delay of 15 mSec
}
7
Python and Arduino with Pyfirmata
115
116 Internet of Things with Raspberry Pi and Arduino
FIGURE 7.1
Circuit diagram for the interfacing of LED.
Python and Arduino with Pyfirmata 117
7.3.1 Recipe
import pyfirmata # import lib of pyfirmata
import time as wait # import lib of pyfirmata
board = pyfirmata.Arduino('/dev/ttyUSB0')# define COM port of Arduino
red_pin = board.get_pin('d:7:o')# assign digital pin 7 as an output
green_pin = board.get_pin('d:6:o')# assign digital pin 6 as an output
it = pyfirmata.util. Iterator(board)
it.start()
118 Internet of Things with Raspberry Pi and Arduino
FIGURE 7.2
Pull-down arrangement for reading button.
FIGURE 7.3
Pull-up arrangement for reading button.
The iterator function can’t be stopped, so when Ctrl+Z is pressed to exit the
window, it will not exist.
Python and Arduino with Pyfirmata 119
FIGURE 7.4
Circuit diagram for flame sensor interfacing.
Python and Arduino with Pyfirmata 121
Once the reading operation is done, the pin is set to disable reporting:
board.analog[3].disable_reporting()
122 Internet of Things with Raspberry Pi and Arduino
FIGURE 7.5
Circuit diagram for potentiometer interfacing.
7.6.1 Recipe
import pyfirmata # import library of pyfirmata
import time as wait # import library of time
board = pyfirmata.Arduino('/dev/ttyUSB0') # define COM port of
Arduino
POT_pin = board.get_pin('a:0:i') # assign A0 pin as an input
it = pyfirmata.util.Iterator(board) # use iterator
it.start() # start iterator
POT_pin.enable_reporting() # enable pin
while True: # infinite loop
POT_reading = POT_pin.read() # read analog pin
Python and Arduino with Pyfirmata 123
FIGURE 7.6
Circuit diagram of LM35 interfacing.
124 Internet of Things with Raspberry Pi and Arduino
7.7.1 Recipe
IMPORT pyfirmata # import library of pyfirmata
import time as wait # import library of time
board = pyfirmata.Arduino('/dev/ttyUSB0') # define COM port of
Arduino
POT_pin = board.get_pin('a:0:i') # assign A0 pin as an input
it = pyfirmata.util.Iterator(board) # use iterator
it.start() # start iterator
POT_pin.enable_reporting() # enable pin
while True:
reading = switch_pin.read() # read analog input
if reading != None: # check condition
voltage = reading * 5.0 # convert level into voltage
temp = (voltage*1000)/10 # convert voltage into
temperature
print('Reading=%f\t Voltage=%f\tTemperature=%f'%
(reading,voltage,temp))
# print value on Pi Terminal
wait.sleep(1) # sleep for 1 Sec
else:
print("No reading Obtained") # print string on Pi Terminal
wait.sleep(1)# sleep for 1 Sec
Connections:
• Connect pins (IN1, IN2, IN3, IN4) of L293D to pins (5, 4, 3, 2) of
Arduino Uno, respectively.
• Connect a DC motor (M1) between pins (OUT1 and OUT2) of
L293D.
Python and Arduino with Pyfirmata 125
FIGURE 7.7
Circuit diagram for line-following robot.
7.8.1 Recipe
import pyfirmata
import time as wait
board = pyfirmata.Arduino('/dev/ttyUSB10')
ir1_pin = board.get_pin('d:7:i') # connect IR sensor1 to pin 7 and used
as input
ir2_pin = board.get_pin('d:6:i') # connect IR sensor2 to pin 6 and used
as input
126 Internet of Things with Raspberry Pi and Arduino
129
130 Internet of Things with Raspberry Pi and Arduino
FIGURE 8.1
Tk version.
TABLE 8.1
The Tkinter Widgets to Develop GUI
Widget Description
Tk() Root widget need in every program
Label() It shows an image or a text
Button() Execute actions
Entry() Text field to provide inputs
Scale() It provides a numeric value by dragging the
slider
Checkbox() It enables toggling between two values
FIGURE 8.2
Circuit diagram to interface LED.
Python GUI with Tkinter and Arduino 131
FIGURE 8.3
Tkinter GUI to control LED with fixed delay.
FIGURE 8.4
LED ON/OFF.
FIGURE 8.5
Tkinter GUI to control LED with variable delay.
FIGURE 8.6
Screenshot for LED ON/OFF with delay.
8.3.1 Recipe
import Tkinter # add Tkinter library
import pyfirmata # add pyfirmata library
import time as wait # add time library
board = pyfirmata.Arduino('/dev/ttyUSB0')
wait.sleep(5) # delay of 5 Sec
led_Pin = board.get_pin('d:7:o') # connect led to pin 7 and used as output
def call_led_blink_pwm():
time_Period = time_Period_Entry.get()
134 Internet of Things with Raspberry Pi and Arduino
time_Period = float(time_Period)
led_Brightness = brightness_Scale.get()
led_Brightness = float(led_Brightness)
button.config(state=Tkinter.DISABLED)
led_Pin.write(led_Brightness/100.0)
print 'LED brightness control' # print on terminal
wait.sleep(time_Period)
led_Pin.write(0) # make led_Pin to LOW
button.config(state=Tkinter.ACTIVE)
TOP = Tkinter.Tk()
time_Period_Entry = Tkinter.Entry(TOP, bd=7, width=30)
time_Period_Entry.pack()
time_Period_Entry.focus_set()
brightness_Scale = Tkinter.Scale(TOP, from_=0, to=100, orient=Tkinter.
VERTICAL)
brightness_Scale.pack()
button = Tkinter.Button(TOP, text="Start", command =
call_led_blink_pwm)
button.pack()
TOP.mainloop()
FIGURE 8.7
Tkinter GUI for LED brigtness control.
Python GUI with Tkinter and Arduino 135
FIGURE 8.8
Screenshot for LED brightness control.
FIGURE 8.9
Circuit diagram to interface multiple LEDs.
136 Internet of Things with Raspberry Pi and Arduino
8.4.1 Recipe
import Tkinter # add Tkinter library
import pyfirmata # add pyfirmata library
import time as wait # add time library
board = pyfirmata.Arduino('/dev/ttyUSB0')
wait.sleep(5) # delay of 5 Sec
red_led_pin = board.get_pin('d:7:o') # connect led to pin 7 and used as
output
green_led_pin = board.get_pin('d:6:o') # connect led to pin 6 and used
as output
def start_button_press():
red_led_pin.write(red_led_Var.get())
green_led_pin.write(green_led_Var.get())
print 'start...' # print on terminal
def stop_button_press():
red_led_pin.write(0) # make pin 7 to HIGH
green_led_pin.write(0) # make pin 6 to HIGH
print 'stop....' # print on terminal
TOP = Tkinter.Tk()
red_led_Var = Tkinter.IntVar()
red_CheckBox = Tkinter.Checkbutton(TOP, text="Red_LED_status",
variable=red_led_Var)
red_CheckBox.grid(column=1, row=1)
green_led_Var = Tkinter.IntVar()
green_CheckBox = Tkinter.Checkbutton(TOP, text="Green_LED_status",
variable=green_led_Var)
green_CheckBox.grid(column=2, row=1)
start_Button = Tkinter.Button(TOP, text="Start_button", command =
start_button_press)
start_Button.grid(column=1, row=2)
stop_Button = Tkinter.Button(TOP, text="Stop_button", command =
stop_button_press)
stop_Button.grid(column=2, row=2)
exit_Button = Tkinter.Button(TOP, text="Exit_button", command=TOP.
quit)
exit_Button.grid(column=3, row=2)
TOP.mainloop()
Python GUI with Tkinter and Arduino 137
FIGURE 8.10
Tkinter GUI for multiple LEDs.
FIGURE 8.11
Screenshot for status window.
FIGURE 8.12
Circuit diagram for PIR sensor interfacing.
Motion_Label.config(text=message)
Motion_Label.update_idletasks()
TOP.update()
pin.write(1) # make pin to HIGH
wait.sleep(1) # delay of 1 Sec
pin.write(0) # make pin to HIGH
wait.sleep(1) # delay of 1 Sec
# Define the action associated with Start button press
def press_start_button():
while True:
if FLAG.get():
if PIR_pin.read() is True:
blink_LED(red_led_pin, "motion_status:Y")
print ‘Motion detected’ # print on terminal
else:
blink_LED(green_led_pin, "motion_status:N")
print ‘No motion’ # print on terminal
Python GUI with Tkinter and Arduino 139
else:
break
board.exit()
TOP.destroy()
def press_exit_button():
FLAG.set(False)
import Tkinter # import Tkinter library
import pyfirmata # import pyfirmata library
import time as wait # import time library
board = pyfirmata.Arduino('/dev/ttyUSB0')
wait.sleep(5) # wait for 5Sec
PIR_pin = board.get_pin('d:8:i') # connect PIR sensor to pin8 and as
input
red_led_pin = board.get_pin('d:7:o') # connect red LED to pin7 and as
output
green_led_pin = board.get_pin('d:6:o') # connect Green led to pin6 and
as output
# Using iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start() # start iterator
PIR_pin.read() # read PIR sensor
# Initialize main windows with title and size
TOP = Tkinter.Tk()
TOP.title("PIR_sensor_for_motion")
# Create Label to for motion detection
Motion_Label = Tkinter.Label(TOP, text="Press Start..")
Motion_Label.grid(column=1, row=1)
# Create flag to work with indefinite while loop
FLAG = Tkinter.BooleanVar(TOP)
FLAG.set(True)
# Create Start button and associate it with onStartButtonPress method
Start_Button = Tkinter.Button(TOP , text="Start", command=press _start_
button)
Start_Button.grid(column=1, row=2)
# Create Stop button and associate it with onStopButtonPress method
140 Internet of Things with Raspberry Pi and Arduino
FIGURE 8.13
Tkinter GUI for motion detection.
FIGURE 8.14
Status window for motion sensor.
FIGURE 8.15
Circuit diagram for interfacing of POT.
8.6.1 Recipe
# Define the action associated with Start button press
def start_button_press():
while True:
if FLAG.get():
analog_Read_Label.config(text=str(a0.read()))
analog_Read_Label.update_idletasks()
TOP.update()
print 'analog values of pot'
else:
break
board.exit()
TOP.destroy()
FIGURE 8.16
Tkinter GUI for reading a POT.
FIGURE 8.17
Window showing analog values of POT.
9
Data Acquisition with Python and Tkinter
9.1 Basics
The open() method: This function is a most commonly used method
that is available in Python, and it is used to manipulate files.
To open a file command:
>>> f = open('test.txt', 'w')
This command creates a test.txt file in the same folder in which the
Python interpreter is saved or the location from where the code is
being executed.
The modes that can be used with the open() function are discussed in
Table 9.1.
The write() method: Once the file is open in the writing mode, the
write() method is used to start writing to the file object. The write()
method takes input argument only in the format of a string.
>>>F.write("Hello World!\n")
Here “Hello World” is a string, and \n means a new line character.
To write a sequence of strings, the writelines() method is used:
>>> sq = ["Python programming for Arduino\n", "Bye\n"]
>>>W.writelines(sq)
The close() method: The close() method is used to close the file, and
the file object can’t be used again. The command is:
>>>W.close()
The read() method: This read() method reads the data of a file. To use
this method, open the file with any of the reading compatible modes
like: w+, r, r+, or a+:
>>>D = open('test.txt', 'r')
>>> D.read()
145
146 Internet of Things with Raspberry Pi and Arduino
TABLE 9.1
Description of Modes
Mode Description
W This mode opens a file only to write. It overwrites an existing file.
w+ This mode opens a file to write and read both. It overwrites an existing file.
R This mode opens a file only to read.
r+ This mode opens a file to write and read both.
A This mode opens a file for appending, starting from end of the document.
a+ This mode opens a file for appending and reading, starting from end of the
document.
CSV writer
import csv
data = [[1, 2, 3], ['a', 'b', 'c'], ['Python', 'Arduino', 'Programming']]
with open('example.csv', 'w') as f:
w = csv.writer(f)
for row in data:
w.writerow(row)
Data Acquisition with Python and Tkinter 147
CSV reader
import csv
with open('example.csv', 'r') as file:
r = csv.reader(file)
for row in r:
print row
FIGURE 9.1
Circuit diagram to interface the PIR sensor and the POT with Arduino UNO and Pi.
148 Internet of Things with Raspberry Pi and Arduino
Connections:
• Connect one terminal of POT to +5 V, the other terminal to
ground, and wiper to pin (A0) of Arduino Uno.
• Connect pins (Vcc and ground) of the PIR sensor to +5 VDC and
ground, respectively.
• Connect pin (OUT) of the PIR sensor to pin(7) of Arduino Uno.
• Connect Arduino Uni to Raspberry Pi through a USB.
9.3.1 Recipe
import csv # import CSV library
import pyfirmata # import pyfirmata library
import time as wait # import time library
board = pyfirmata.Arduino('/dev/ttyUSB0')
it = pyfirmata.util.Iterator(board)
it.start() # start iterator
PIR_pin = board.get_pin('d:7:i') # connect PIR sensor to pin 7 as input
POT_pin = board.get_pin('a:0:i') # connect POT to pin 0 as input
with open('SensorDataStore.csv', 'w') as f:
w = csv.writer(f)
w. writerow(["Number", "Potentiometer", "Motion sensor"])
i=0
PIR_Data = PIR_pin.read() # read PIR sensor
POT_Data = POT_pin.read() # read POT
while i < 25:
sleep(1)
if PIR_Data is not None:
i += 1
row = [i, POT_Data, PIR_Data]
w. writerow(row)
print "process complete. CSV file is ready!"
board.exit()
Data Acquisition with Python and Tkinter 149
pyplot.plot(x, y)
To change the style of line and makers with different colors, the plot() method
can be used, e.g., for the solid line style command:
pyplot.plot(x, y, ‘-’)
FIGURE 9.2
Plotting the random number.
150 Internet of Things with Raspberry Pi and Arduino
9.4.1 Recipe
For generating and plotting random numbers:
import random
R = range(0,25)
S = [random.randint(0,100) for r in range(0,25)]
FIGURE1 = pyplot.figure()
pyplot.plot(R, S, '-')
pyplot.title('random integer plot....')
pyplot.xlabel('X Axis for R')
pyplot.ylabel('Y Axis for S')
pyplot.show()
pyplot.ion()
Once the interactive mode is set, the plot will be drawn by calling the draw()
method. Now, initialize the plot with a set of blank data, 0, in this case:
pData = [0] * 25
In this array for y values, pData, is used to append values from the sensor in
the while loop to keep appending the newest values to this data array and
redraws the plot with these updated arrays for the x and y values.
pData.append(float(a0.read()))
del pData[0]
Data Acquisition with Python and Tkinter 151
FIGURE 9.3
Circuit diagram for the interfacing of POT with Arduino.
The set_xdata() and set_ydata() methods are used to update the x and y axes
data.
9.5.1 Recipe
//from matplotlib import pyplot
import pyfirmata # import pyfirmata library
import time as wait
board = pyfirmata.Arduino('/dev/ttyUSB0')
wait.sleep(5) # wait for 5 Sec
it = pyfirmata.util.Iterator(board)
it.start() # start iterator
POT_pin = board.get_pin('a:0:i') # connect POT to A0 pin as input
152 Internet of Things with Raspberry Pi and Arduino
pyplot.ion()
pData = [0.0] * 25
fig = pyplot.figure()
pyplot.title('Real time data plot from POT')
ax1 = pyplot.axes()
l1, = pyplot.plot(pData)
pyplot.ylim([0, 1])
while True:
try:
wait.sleep(1)
pData.append(float(POT_pin.read()))
pyplot.ylim([0, 1])
del pData[0]
l1.set_xdata([i for i in xrange(25)])
l1.set_ydata(pData) # update the data
pyplot.draw() # update the plot
except KeyboardInterrupt:
board.exit()
break
9.6.1 Recipe
import sys # import sys library
from matplotlib import pyplot # import library
import pyfirmata # import library
import time as wait # import time library
import Tkinter # import library
Data Acquisition with Python and Tkinter 153
def start_button_press():
while True:
if FLAG.get():
wait.sleep(1) # wait for 1 Sec
pData.append(float(POT_pin.read()))
pyplot.ylim([0, 1])
del pData[0]
l1.set_xdata([i for i in xrange(25)])
l1.set_ydata(pData) # update the data
pyplot.draw() # update the plot
TOP.update()
else:
FLAG.set(True)
break
def pause_button_press():
FLAG.set(False)
def exit_button_press():
print "out from data recording...."
pause_button_press()
board.exit()
pyplot.close(fig)
TOP.quit()
TOP.destroy()
print "completed....."
sys.exit()
board = pyfirmata.Arduino('/dev/ttyUSB0')
# Using iterator thread to avoid buffer overflow
it = pyfirmata.util.Iterator(board)
it.start() # start iterator
# Assign a role and variable to analog pin 0
POT_pin = board.get_pin('a:0:i') # read POT
# Tkinter canvas
TOP = Tkinter.Tk()
TOP.title("Tkinter + matplotlib")
# Create flag to work with indefinite while loop
FLAG = Tkinter.BooleanVar(TOP)
154 Internet of Things with Raspberry Pi and Arduino
FLAG.set(True)
pyplot.ion()
pData = [0.0] * 25
figure = pyplot.figure()
pyplot.title('Potentiometer')
ax1 = pyplot.axes()
l1, = pyplot.plot(pData)
pyplot.ylim([0, 1])
# Create Start button and associate with start button press method
start_Button = Tkinter.Button(TOP, text="Start", command=start_
button_press)
start_Button.grid(column=1, row=2)
# Create Stop button and associate with pause button press method
pause_Button = Tkinter.Button(TOP, text="Pause", command=pause_
button_press)
# Create Exit button to exit from window
exit_Button=Tkinter.Button(TOP,text="Exit",command=exit_button_press)
exit_Button.grid(column=3, row=2)
TOP.mainloop()
Execute the program, and a window will appear on the screen (Figure 9.4).
The plot can be controlled by using “Start”, “Pause” and “Exit” buttons.
Click on start button and rotate the knob of POT and see the changes in plot.
The process can be paused or close the program with “Exit” button.
FIGURE 9.4
Plot for real-time data from Arduino.
Section IV
157
158 Internet of Things with Raspberry Pi and Arduino
FIGURE 10.1
Circuit diagram for interfacing of DHT11 with Raspberry Pi.
FIGURE 10.2
Window for ThingSpeak.
4. Enter the channel setting values and click on “Save Channel” at the
bottom of the settings.
5. Check API write key (this key needs to write in the program).
6. Write the program described in Section 10.1.3 and check the sensory
data on cloud server (Figures 10.4 and 10.5).
Smart IoT Systems 159
FIGURE 10.3
New channel in my channels.
FIGURE 10.4
Graph for temperature data.
FIGURE 10.5
Graph for humidity data.
160 Internet of Things with Raspberry Pi and Arduino
10.1.3 Recipe
import sys # import sys library
importRPi.GPIO as RAJ # import GPIO library
import time as wait # add time library
importAdafruit_DHT as RAJ_DHT
import urllib2 #import urllib library
my_API = 'F1MAEF943TLMVTC1'
defsensor_data():
HUM, TEMP= RAJ_DHT.read_retry(RAJ_DHT.DHT11, 21)
return (str(HUM), str(TEMP))
defmain_function():
base_URL = 'https://api.thingspeak.com/update?api_key=%s' % my_API
while True: # infinite loop
try:
HUM, TEMP = sensor_data() # read value of Temperature and Humidity
f = urllib2.urlopen(base_URL + '&field1=%s&field2=%s' % (HUM,
TEMP))
printf.read() # print function value
f.close() # close function
wait.sleep(15) # delay of 15 Sec
except:
print ‘exit from program’ # print string on terminal
break
FIGURE 10.6
Circuit diagram for interfacing of ultrasonic sensor with Raspberry Pi.
10.2.1 Recipe
import time as wait # add time library
importRPi.GPIO as ANITA # add pi GPIO library
import sys # add sys library
import urllib2 # add urllib
my_API = 'F1MAEF943TLMVTC1'
defget_sensor_data():
ANITA.setmode(ANITA.BOARD) # use pi in board mode
162 Internet of Things with Raspberry Pi and Arduino
TABLE 10.1
AQI Classification
AQI Range AQI Category
0–50 Excellent
51–100 Good
100–150 Lightly polluted
151–200 Moderately polluted
201–250 Heavily polluted
251–300 Severely polluted
FIGURE 10.7
Block diagram of the air quality monitoring system.
164 Internet of Things with Raspberry Pi and Arduino
FIGURE 10.8
Circuit diagram for air quality monitoring system.
FIGURE 10.9
Humidity data on ThingSpeak server.
Smart IoT Systems 165
FIGURE 10.10
Temperature data on ThingSpeak server.
FIGURE 10.11
CO level data on ThingSpeak server.
Connections
• Connect camera to the dedicated port at Raspberry Pi.
• Connect pins(Vcc and ground) of MQ2, MQ3, MQ7, GP2Y1030,
and DHT11 sensor to +5 VDC and ground, respectively.
• Connect pin(OUT) of DHT11 sensor to pin(2) of Arduino Uno.
• Connect Arduino Uni to Raspberry Pi through a USB.
166 Internet of Things with Raspberry Pi and Arduino
FIGURE 10.12
Air level data on ThingSpeak server.
10.3.1 Recipe
import sys # import sys library
import urllib2 # add url library
import pyfirmata # add pyfirmata library
importAdafruit_DHT as RAJ_DHT
import time as wait # import time library
importRPi.GPIO as RAJ # import ri GPIO library
frompicamera import PiCamera # import picamera library
board = pyfirmata.Arduino('/dev/ttyUSB0') # USB com number
led_Power = board.get_pin('d:12:o') # connect led_power pin to 12 pin
of Arduino as output
Smart IoT Systems 167
if (dust_Density< 0):
dust_Density = 0.00
FIGURE 10.13
Circuit diagram for landslide detection and disaster management system.
170 Internet of Things with Raspberry Pi and Arduino
FIGURE 10.14
(a) Humidity data. (b) Temperature data.
FIGURE 10.15
(a) Pressure data. (b) Altitude data.
FIGURE 10.16
PIR sensor data.
Smart IoT Systems 171
FIGURE 10.17
(a) Accelerometer x-axis data. (b) y-axis data. (c) z-axis data.
Connections
• Connect camera to the dedicated port at Raspberry Pi.
• Connect pins (Vcc and ground) of the PIR sensor, BMP180 sen-
sor, rain sesnor, accelerometer, buzzer, and DHT11 sensor to +5
VDC and ground, respectively.
• Connect pin(OUT) of DHT11 sensor to pin(4) of Arduino Uno.
• Connect Arduino Uni to Raspberry Pi through a USB.
• Connect pin(OUT) of the PIR sensor to pin(2) of Arduino Uno.
• Connect pin(OUT) of the rain sensor to pin(A0) of Arduino Uno.
• Connect pin(OUT) of the buzzer to pin(5) of Arduino Uno.
• Connect pin(SCL) of BMP180 to pin(A5) of Arduino Uno.
• Connect pin(SDA) of BMP180 to pin(A4) of Arduino Uno.
• Connect “x axis” of accelerometer to pin (A1) of Arduino Uno.
• Connect “y axis” of accelerometer to pin (A2) of Arduino Uno.
• Connect “z axis” of accelerometer to pin (A3) of Arduino Uno.
10.4.1 Recipe
import sys # import library
importRPi.GPIO as RAJ
import time as wait # import time library
importAdafruit_DHT as RAJ_DHT
172 Internet of Things with Raspberry Pi and Arduino
defget_sensor_data():
HUM, TEMP = RAJ_DHT.read_retry(RAJ_DHT.DHT11, 4)
pir_sensor=RAJ.input(16) # connect PIR sensor to GPIO 16 as input
bmp_sensor = BMP085(0x77)
pressure1= bmp.readPressure() # read pressure
pressure_data=pressure1/100 # scale pressure value
altitude_data = bmp.readAltitude() # read altitude
axes = adxl345.getAxes(True)
x1_data= axes['x']
y1_data=axes['y']
z1_data=axes['z']
return (str(HUM), str(TEMP), str(pir_sensor), str(pressure_data),
str(altitude_data), str(x1_data), str(y1_data), str(z1_data))
defmain_program():
count=0 # initialise count
pir1_data=GPIO.input(16) # connect PIR sensor to GPIO16 as input
iflen(sys.argv) < 2:
print(‘print data’) # print string on terminal
exit(0)
print 'process start...' # print string on terminal
base_URL = 'https://api.thingspeak.com/update?api_key=%s' % sys.
argv[1]
while True:
try:
HUM, TEMP, pir_sensor, pressure_data, altitude_data, x1_data, y1_
data, z1_data =
get_sensor_data()
Smart IoT Systems 173
f = urllib2.urlopen(base_URL +"&field1=%s&field2=%s&field3=%
s&field4=%s&field5=%s&field6=%s&field7=%s&field8=%s"
% (HUM, TEMP, pir_sensor, pressure_data, altitude_data,
x1_data, y1_data, z1_data))
printf.read() # read function
if (pir1_data==1):
print "hello" # print string on terminal
RAJ_camera = PiCamera()
RAJ_camera.start_preview()
wait.sleep(5) # delay of 5 sec
count =count+ 1
RAJ_camera.capture('img/image%s.jpg' % count) # capture image
RAJ_camera.stop_preview() # stop preview
RAJ_camera.close() # close camera
f.close() # close function
wait.sleep(15) # dely 15 sec
except:
print 'exit from main program' # print string on terminal
break
if __name__ == '__main_program__':
main_program()
Connections:
• Connect the camera to the dedicated port at Raspberry Pi.
• Connect pins(Vcc and ground) of the PIR sensor to +5 VDC and
ground, respectively.
• Connect pin(OUT) of the PIR sensor to GPIO21 of Raspberry Pi.
• Connect the cathode terminal of the LED to the ground, and the
anode terminal to GPIO13 of Raspberry Pi through a resistor.
174 Internet of Things with Raspberry Pi and Arduino
FIGURE 10.18
Circuit diagram for smart motion detector.
10.5.2 Recipe
importRPi.GPIO as ANITA # import pi GPIO
importpicamera as RAJ_camera # import camera library
import time as wait # import time library
importsmtplib # import smtp library
fromemail.mime.multipart import MIMEMultipart # add library
fromemail.mime.text import MIMEText # add library
fromemail.mime.base import MIMEBase # add library
from email import encoders # add library
fromemail.mime.image import MIMEImage # add library
from_addr = "sssss@gmail.com" # change the email address accordingly
to_addr = "rrrrrr@gmail.com"
mail_RAJ = MIMEMultipart()
mail_RAJ['From'] = from_addr
mail_RAJ['To'] = to_addr
mail_RAJ['Subject'] = "Attachment"
body = "Please find the attachment"
led_pin=3 # connect led to pin 3 of raspberry pi GPIO
pir_pin=21 # connect PIR sensor to pin 21 of raspberry pi GPIO
defsend_Mail(data):
mail_RAJ.attach(MIMEText(body, 'plain'))
print data # print data on terminal
dat='%s.jpg'%data
print (data) # print data on terminal
attachment_RAJ = open(dat, 'rb')
image_RAJ=MIMEImage(attachment_RAJ.read())
attachment_RAJ.close()
176 Internet of Things with Raspberry Pi and Arduino
defRAJ_capture_image():
data= wait.strftime("%d_%b_%Y|%H:%M:%S")
RAJ_camera.start_preview() # start preview
wait.sleep(5) # wait for 5 Sec
print data # print on terminal
RAJ_camera.capture('%s.jpg'%data)
RAJ_camera.stop_preview()
wait.sleep(1) # wait for 1 Sec
send_Mail(data) # send mail
Figure 11.1 shows the window after the execution of the commands.
177
178 Internet of Things with Raspberry Pi and Arduino
FIGURE 11.1
Raspberry Pi window.
FIGURE 11.2
Creating a new account.
FIGURE 11.3
Create a new project.
FIGURE 11.4
Widget box.
180 Internet of Things with Raspberry Pi and Arduino
FIGURE 11.5
Button for LED.
FIGURE 11.6
Project to control two LEDs.
FIGURE 11.7
Circuit diagram for home appliance control.
Connections:
• Connect the base of the first transistor 2N2222 to GPIO21 through
a resistor and emitter to the ground.
• Connect the base of the second transistor 2N2222 to GPIO20
through a resistor and emitter to the ground.
• Connect the collector of transistor to “L2” of relay.
• Connect the positive terminal of +12V battery to “L1” of relay.
• Connect a diode 1N4007 across “L1” and “L2.”
• Connect one terminal of AC to “common” of the relay and the
other to one of the terminal of AC to the load (bulb).
• Connect the other terminal of the AC load to the “NO” terminal
of the relay.
12
Cayenne Application with Raspberry Pi
183
184 Internet of Things with Raspberry Pi and Arduino
FIGURE 12.1
Create an account.
FIGURE 12.2
Choose the device.
FIGURE 12.3
Installing Raspberry Pi.
Cayenne Application with Raspberry Pi 185
FIGURE 12.4
GPIO of Raspberry pi.
FIGURE 12.5
Circuit diagram for interfacing LED with Raspberry Pi.
Bibliography
Anita Gehlot, Rajesh Singh, Mamta Mittal, Bhupendra Singh, Ravindra Sharma, Vikas
Garg, Hands on Approach on Applications of Internet of Things in Various Domain of
Engineering. New Delhi, India: International Research Publication House, 2018.
Anita Gehlot, Rajesh Singh, Rohit Samkaria, Sushabhan Choudhury, Aisik De,
Kamlesh, Air quality and water quality monitoring using XBee and internet of
things, International Journal of Engineering and Technology (UAE), 7.2 (2018).
Jan I. Freijer and Henk J.Th. Bloemen, Modeling relationships between indoor
and outdoor air quality, Taylor & Francis Group. Journal of the Air & Waste
Management Association, 50(2), 292–300 (2011).
Neeraj Kumar Singh, Amardeep Singh, Rajesh Singh, Anita Gehlot, Design and
development of air quality management devices with sensors and web of
things, International Journal of Engineering and Technology (UAE), 7.2 (2018).
doi:10.14419/ijet.v7i2.6.10077.
Rajesh Singh, Anita Gehlot, Bhupendra Singh, Sushabhan Choudhury, Arduino-
Based Embedded Systems: Interfacing, Simulation, and LabVIEW GUI. Boca Raton,
FL: CRC Press/Taylor & Francis Group, 2017.
Rajesh Singh, Anita Gehlot, Bhupendra Singh, Sushabhan Choudhury, Arduino meets
MATLAB…. Interfacing, Programs and Simulink. Sharjah: Bentham Science, 2018.
Rajesh Singh, Anita Gehlot, Lovi Raj Gupta, Bhunpendra Singh, and Priyanka Tyagi,
Getting Started for Internet of Things with Launch Pad and ESP8266. India: River
Publishers, 2019.
Rajesh Singh, Anita Gehlot, Raghuveer Chimata, Bhupendra Singh, P.S. Ranjith, Internet
of Things in Automotive Industries and Road Safety. India: River Publishers, 2018.
Rajesh Singh, Rohit Samkaria, Anita Gehlot, Neeraj Kumar, Kausal Rawat, Aisik
De, Adil Rehman, Algorithm to read various sensors to detect the hazard-
ous parameters in industry, International Journal of Engineering and Technology
(UAE), 7.2 (2018). doi:10.14419/ijet.v7i2.6.10060.
187
Index
Note: Page numbers in italic and bold refer to figures and tables, respectively.
A G
Adafruit, 76 gateway, 5
analog sensor, 104–106 generation, sensors, 17
architecture, 5
Arduino, 29–43
Arduino IDE, 33–37 H
Arduino Mega, 30, 31, 31 heterogeneity, 4
Arduino Nano, 31, 32, 32, 33 home appliance control, 180–181, 181
Arduino Uno, 29, 30, 30
B I
D M
data acquisition, 145–154 machine learning, 6
DC motor, 72, 72–74 Matplotlib, 149–150
design methodology, 19 M2M, 11
design principles, 4
DHT11, 83–86, 84
digital input, 66–67 N
digital sensor, 100–103
disaster management system, 169–173 NOOBS, 48, 48, 49
dynamic nature, 3
O
F
OSI (Open Systems Interconnection)
face recognition, 60 model, 6, 6
189
190 Index
S U
security, 4 ultrasonic sensor, 16
sensors, 13–17 UV sensor, 16