You are on page 1of 110

1

INDUSTRIAL TRAINING REPORT

Raspberry Pi & IOT

SUBMITTED TO: SUBMITTED BY:


ER. ROHIT KHOSLA GARIMA PRASHAR
(DIRECTOR)

2
INDUSTRIAL TRAINING REPORT

Raspberry Pi & IOT

SUBMITTED TO: SUBMITTED BY:


ER. ROHIT KHOSLA RAVI RAMAN
(DIRECTOR)

INDEX

CHAPTER TITLE PAGE NO.


1 IOT 3

3
2 Linux & types 4-7
3 VmWare 8-14
4 Ubuntu commands 15-16
5 Desktop environments & managers 17
6 Raspberry pi 18-21
7 Installation of Operating system in pi 22-27
8 WinSCP 28-29
9 Remote Desktop (Putty) 30-33
10 Python 34
11 GPIO library 35
12 Sublime 36-38
13 Programming with python 39
14 Programs
14.1 Simple I/O with RPi 40
14.2 Simple I/O with delay 41
14.3 Simple I/O with loop 41
14.4 Input switch 42
14.5 PWM 43-47
14.6 ASCII art 48
14.7 Increment the value 49
14.8 Pull Up down 49
15 GPIO pins of Raspberry pi 50-51
16 Projects
16.1 Wireless Hotspot 52-57
16.2 Webcam using motion 58-61
16.3 Sensors 62-65
16.4 Twitter 66-73
16.5 MyDevices 74-77
16.6 Google 78-85
16.7 Particle.io 86-90
16.8 IFTTT 91-95
16.9 NodeMCU 96-103
17 References 104

CHAPTER-1

IOT (INTERNET OF THINGS)

4
1.1 Introduction to IOT

Fig. 1.1 IOT


The Internet of things (IOT) is the network of physical devices, vehicles, home appliances and
other items embedded with electronics, software, sensors, actuators, and connectivity which
enables these objects to connect and exchange data. The IOT allows objects to be sensed or
controlled remotely across existing network infrastructure, creating opportunities for more direct
integration of the physical world into computer-based systems, and resulting in improved
efficiency, accuracy and economic benefit in addition to reduced human intervention.

When IOT is augmented with sensors and actuators, the technology becomes an instance of the
more general class of cyber-physical systems, which also encompasses technologies such as
smart grids, virtual power plants, smart homes, intelligent transportation and smart cities.

“Things”, in the IOT sense, can refer to a wide variety of devices such as heart monitoring
implants, biochip transponders on farm animals, cameras streaming live feeds of wild animals in
coastal waters, automobiles with built-in sensors, DNA analysis devices for
environmental/food/pathogen monitoring, or field operation devices that assist firefighters in
search and rescue operations.”Things” as an “inextricable mixture of hardware, software, data
and service.

CHAPTER-2

LINUX

5
2.1 Introduction to Linux : Linux is a family of free and open-source software operating
systems built around the Linux kernel. Typically, Linux is packaged in a form known as a Linux
distribution for both desktop and server use. The defining component of a Linux distribution is
the Linux kernel,an operating system kernel first released on September 17, 1991, by Linus
Torvalds.Many Linux distributions use the word “Linux” in their name. The Free Software
Foundation uses the name GNU/Linux to refer to the operating system family, as well as specific
distributions, to emphasize that most Linux distributions are not just the Linux kernel, and that
they have in common not only the kernel, but also numerous utilities and libraries, a large
proportion of which are from the GNU project.

Fig. 2.1 Linux Logo

2.2 The most popular Linux distributions are:

1. Ubuntu Linux :

Fig.2.2 ubuntu linux

2. Linux Mint.

6
Fig. 2.3 Linux mint
3. Arch Linux.

Fig. 2.4 arch linux

4. Deepin.

Fig. 2.5 deepin

5. Fedora.

7
Fig 2.6 Fedora

6. Debian.

Fig. 2.7 Debian

2.3 UBUNTU LINUX :


Ubuntu is an open source operating system for computers. It is a Linux distribution based on the
Debian architecture. Ubuntu is the most popular operating system running in hosted
environments, so-called “clouds” as it is the most popular server Linux distribution.
Development of Ubuntu is led by UK-based Canonical Ltd., a company founded by South
African entrepreneur Mark Shuttleworth.

CHAPTER-3

8
VMWARE (VIRTUALISATION)
3.1 Introduction to VMware : VMware Workstation is a hosted hypervisor that runs on x64
versions of Windows and Linux operating systems(an x86 version of earlier releases was
available);it enables users to set up virtual machines (VMs) on a single physical machine, and
use them simultaneously along with the actual machine. Each virtual machine can execute its
own operating system, including versions of Microsoft Windows, Linux, BSD, and MS-DOS.

3.2 Installing Ubuntu in a VMware on Windows

1. Download the Ubuntu (desktop not server) and the free VMware Software.
2. Install VMware and run it, you’ll see something like this:

Fig. 3.1 welcome to vmware


3. Select “Create a New Virtual Machine”

9
4. Select “Installer disc image file” and browse to the Ubuntu iso you downloaded.

fig. 3.2 how to install

VMware Player Virtual Machine WizardYou should see that it will use Easy Install – this takes
care of most of the hard work for you. Click next

5. Enter your full name, username and password and hit next

10
Fig. 3.3 personalize linux

6. Select the maximum disk size and type. Unless you’re planning on some really CPU intensive
work inside the VM, select the “Split virtual disk into multiple files” option. Hit next.

Fig. 3.4 specifying disk


11
7. This brings you to the confirmation page. Click “Customize Hardware”

Fig 3.5 Create virtual machine


8. In the hardware options section select the amount of memory you want the VM to use. In this
instance I’ve gone for 1.5GB out of the 8GB installed in my laptop. Leave everything else as it is
and click Close.

12
Fig. 3.6 hardware specification
9. This brings you back to the confirmation page. Click Finish this time

Fig.3.7 finish

13
10. You will probably be prompted to download VMware Tools for Linux. Click “Download
and Install” to continue.

11. Wait for it to install

12. Ubuntu will then start to install, so keep waiting

14
13. When all is done you’ll be presented with the Ubuntu login screen. So enter your password
and you’re on your way.

Fig. 3.8 Ubuntu Login screen

15
CHAPTER-4

UBUNTU COMMANDS:

4.1 COMMANDS ARE:

1. sudo : This SuperUserDo is the most important command Linux newbies will use. Every

single command that needs permission, need this sudo command. You can use sudo before each

command that requires root permissions -

2. ls (list) : Just like the other, you often want to see anything in your directory. With list

command, the terminal will show you all the files and folders of the directory that you're

working in.

3. cd: Changing directory (cd) is the main command that always be in use in terminal. It's one of

the most Linux basic commands. Using this is easy. Just type the name of the folder you want to

go in from your current directory.

4. mkdir : Just changing directory is still incomplete. Sometimes you want to create a new folder

or subfolder. You can use mkdir command to do that. Just give your folder name

after mkdir command in your terminal.

5. cp : copy-and-paste is the important task we need to do to organize our files. Using cp will

help you to copy-and-paste the file from terminal. First, you determine the file you want to copy

and type the destination location to paste the file.

16
6. rm :rm is a command to remove your file or even your directory. You can use -f if the

file need root permission to be removed. And also you can use -r to do recursive removal to

remove your folder.

7. apt-get : In Debian based Linux distributions, to install, remove and upgrade any package

we've Advanced Packaging Tool (APT) package manager. The apt-get command will help you

installing the software you need to run in your Linux. It is a powerful command-line tool which

can perform installation, upgrade, and even removing your software.

8. Grep :You need to find a file but you don't remember its exact location or the path. grep will

help you to solve this problem. You can use the grep command to help finding the file based on

given keywords.

9. chmod: This command is used to change permissions on a file. 

10. pwd: print working directory, this command can be used to display the directory in which
you are currently working. 

11. ifconfig :ifconfig in short “interface configuration” utility for system/network administration
in Unix/Linux operating systems to configure, manage and query network interface parameters
via command line.

12. apt-get update: updates the list of available packages and their versions, but it does
not install or upgrade any packages. 

13. apt-get upgrade: actually installs newer versions of the packages. 

14. dpkg: is a package manager for Debian-based systems. It can install, remove, and build
packages, but unlike other package management systems, it cannot automatically download and
install packages or their dependencies. 

17
CHAPTER-5

5.1 DIFFERENT DESKTOP ENVIRONMENTS :


 GNOME 3 Desktop.
 KDE Plasma 5.
 Cinnamon Desktop.
 MATE Desktop.
 Unity Desktop.
 Xfce4 Desktop.
 LXDE Desktop

Fig. 5.1 Cinnamon Desktop Environment

5.2 DIFFERENT DESKTOP MANAGERS:


 Ubuntu's Unity desktop with Dash open.
 The GNOME desktop in Fedora Workstation.
 KDE in Kubuntu.
 Linux Mint with the Cinnamon desktop.
 Linux Mint with the MATE desktop.
 Lubuntu with the LXDE desktop.
 Xubuntu with the XFCE desktop.

18
CHAPTER-6

RASPBERRY PI

6.1 Introduction to Raspberry pi: The Raspberry Pi is a series of small single-board ultimate
and affordable computers. It is an ultra-low-cost ($20-$35) credit-card sized Linux computer. It
may be operated with any generic USB computer keyboard and mouse. It may also be used with
USB storage, USB to MIDI converters, and virtually any other device/component with USB
capabilities. Other peripherals can be attached through the various pins and connectors on the
surface of the Raspberry Pi.

Fig. 6.1 Raspberry pi

19
6.2 Generations of Raspberry Pi’s. The different versions and their respective features are as
follows:

1. Raspberry Pi 1 Model B: This first generation was released in February 2012.


➢ The CPU is an older ARMv6 architecture, which includes a 700 MHzARM1176JZF-S
processor.
➢ 32 bit CPU
➢ 512 MB of RAM
➢ 2 USB ports
➢ 10/100 wired Ethernet RJ45
➢ 26 GPIO pins

Fig. 6.2 RPi Model B

2. Raspberry Pi Model A:This model was released in Feb 2013. It is simpler and
inexpensive model than the above.
 No Ethernet port
 1 USB port
 Composite video, Composite RCA, HDMI (not at the same time)
 32 bit, 700MHz ARM11 processor core.
 256 MB of RAM

Fig. 6.3 Rpi model A

20
3. Raspberry Pi Model A+: This model is square in shape
 256 MB of RAM
 32 bit, 700MHz ARM11 processor core
 1 USB port
 No Ethernet port
 SD card
 40 GPIO pins.

Fig. 6.4 Rpi Model A+

4. Raspberry Pi Zero: This smaller size Pi was released in November 2015 for US$5.
➢ 1 GHz Low Power ARM1176JZ-F processor
➢ 512 MB of RAM
➢ No Ethernet port
➢ 1 Micro USB OTG
➢ Mini HDMI port
➢ It is equipped with 2.4 GHz WiFi802.11n (150 Mbit/s) and Bluetooth 4.1 (24 Mbit/s)
➢ 40 General Purpose Input/Output (GPIO) pins

Fig 6.5 Rpi model zero

21
5. Raspberry Pi 2 Model B: It was released in February 2015.
➢ 32-bit 900 MHz quad-core ARM Cortex-A7 processor.
➢ 1 GB RAM.
➢ 4 USB ports
➢ 1 Ethernet port
➢ Combined 3.5mm audio jack and composite video
➢ Full HDMI port
➢ Camera interface (CSI) and Display interface (DSI)
➢ Micro SD card slot.
➢ 40 GPIO pins

Fig. 6.6 Rpi model B


6. Raspberry Pi 3 Model B: It was released in February 2016. As of January 2017, it
is the newest mainline Raspberry Pi.
➢ 1.2GHz 64-bit quad-core ARMv8 Cortex-A53 processor
➢ 1GB SDRAM
➢ 4 USB ports
➢ 10/100Mbps Ethernet
➢ HDMI port and composite video via 3.5 mm jack
➢ On board 802.11n Wireless LAN and 4.1 Bluetooth
➢ 40 GPIO pins

Fig. 6.7 Rpi model B3

22
CHAPTER-7

INSTALLATION OF OPERATING SYSTEM IN RASPBERRY PI

7.1 Introduction : If you order a Raspberry Pi without an SD card preloaded with New Out Of
Box Software (NOOBS), you will need to provide your own SD card and manually install an
operating system. There are two ways to install Raspberry Pi:
● Noobs
● Raspbian
Raspbian is the foundation’s official supported Operating System based on Debian. You can
install it with NOOBS that is an easy installer for Raspbian or can download it from the image by
following the installation guide.

Fig. 7.1 OS of RPI

7.2 INSTALLING OPERATING SYSTEM WITH NOOBS:


New Out Of Box Software(NOOBS) is an easy operating system installation manager for
Raspberry Pi.

HOW TO GET NOOBS:

➢ Buy a pre installed SD card-


SD cards with NOOBS preinstalled are available from many of our distributors and
independent retailers, including Pimoroni, Adafruit, and Pi Hut.
➢ Download-
Alternatively, NOOBS is available for download on the Raspberry Pi
website:raspberrypi.org/downloads
● NOOBSis an easy operating system installer which contains Raspbian. It also provides
a selection of alternative operating systems which are then downloaded from the
internet and installed.
● NOOBS Lite contains the same operating system installer without Raspbian pre-
loaded. It provides the same operating system selection menu allowing Raspbian and
other images to be downloaded and installed.

23
LATEST NOOBS RELEASE:
The latest NOOBS release is v2.4.0, released on 10th April 2017.

7.3 HOW TO FORMAT AN SD CARD:

For Windows users, it is recommended to format the SD card using the SD Formatter Tool.
You will need to set "FORMAT SIZE ADJUSTMENT" option to "ON" in the "Options" menu
to ensure that the entire SD card volume is formatted, and not just a single partition. The updated
size will be shown after the format is complete.

FIG. 7.2 SD formatter

WRITING NOOBS TO AN SD CARD:

Once you've downloaded the NOOBS zip file, you'll need to copy the contents to a formatted SD
card on your computer. To set up a blank SD card with NOOBS:
1. Format an SD card.
2. Download and extract the files from the NOOBS zip file.

24
3. Copy the extracted files onto the SD card that you just formatted, so that this file is at the
root directory of the SD card. Please note that in some cases it may extract the files into a
folder; if this is the case, then please copy across the files from inside the
folder rather than the folder itself.
4. On first boot, the "RECOVERY" FAT partition will be automatically resized to a
minimum, and a list of OSes that are available to install will be displayed.

WHAT’S INCLUDED IN NOOBS:

The following operating systems are currently included in NOOBS:


➢ Raspbian
➢ Pidora
➢ LibreELEC
➢ OSMC
➢ RISC OS
➢ Arch Linux
As of NOOBS v1.3.10 (September 2014), only Raspbian is installed by default in NOOBS. The
others can be installed with a network connection.

7.4 BOOTING FROM NOOBS AND INSTALLING RASPBIAN: Once the files have been
copied over, insert the microSD card into your Raspberry Pi and then plug it into a power source.
Connect the converter(HDMI to VJ ) to it. A keyboard and mouse will be required to install an
OS with NOOBS, as will a HDMI display. Raspberry Pi is connected to the Internet via Ethernet.
You will be provided with a single option, once the installer has loaded. Now Reboot the
raspberry pi and a Window appears as follows-

Fig. 7.3 Booting from Noobs


You should check the box for Raspbian, and then click Install.
25
7.5 INSTALLING OPERATING SYSTEM USING IMAGE FILE
HOW TO GET RASPBIAN:
You can find the Raspbian downloads here. You can choose between Raspbian Jessie with or
without PIXEL, the lightweight desktop.

INSTALLATION:

Win32 Disk Imager is the program designed to write a raw disk image to a removable device or
backup a removable device to a raw image file. It can be used to write images to SD cards as
follows-

1. Insert the SD card into your SD card reader. You can use the SD card slot if you have
one, or an SD adapter in a USB port. Note the drive letter assigned to the SD card. You
can easily see the drive letter (for example G:) in the left hand column of Windows
Explorer.
2. Download the Win32DiskImager utility from theSourceforge Project page(it is a zip file)
as an installer file, and run it to install the software.
3. Extract the executable from the Jessie image you downloaded. and run the
Win32DiskImager utility; you may need to run the utility as administrator. Right-click on
the file, and select Run as administrator.
4. Select the image file you extracted above.
5. Select the drive letter of the SD card in the device box. Be careful to select the correct
drive; if you get the wrong one you can destroy your data on the computer's hard disk! If
you are using an SD card slot in your computer and can't see the drive in the
Win32DiskImager window, try using an external SD adaptor in a USB port.
6. Click ‘Write’ and wait for the write to complete.
7. Once the image is finished writing to the the SD card, exit the imager.
Now, you can eject the SD card, insert it into the Raspberry Pi and power it on.

26
7.6 CONFIGURATION OF RASPBERRY PI :

● COMMAND LINE METHOD: raspi-config is the Raspberry Pi configuration tool that


targets Raspbian. It aims to provide the functionality to make the most common
configuration changes. This may result in automated edits to /boot/config.txt and various
standard Linux configuration files. Some options require a reboot to take effect. If you
changed any of those, raspi-config will ask if you wish to reboot now when you select the
<Finish> button.

Fig. 7.4 configuration of pi

27
 GRAPHICAL METHOD:
Alternatively, Pi can be configured directly by selecting Raspberry Pi Configuration in
Preferences in the menu as follows-

Fig. 7.5 Graphical configuration

28
CHAPTER-8

WINSCP
8.1 Introduction to WinSCP : WinSCP (Windows Secure Copy) is a free and open-source
SFTP, FTP, WebDAV and SCP client for Microsoft Windows. Its main function is secure file
transfer between a local and a remote computer. Beyond this, WinSCP offers basic file manager
and file synchronization functionality. For secure transfers, it uses Secure Shell (SSH) and
supports the SCP protocol in addition to SFTP.
My version:2013-02-09-wheezy-raspbian

Download WinSCP here:http://winscp.net/eng/download.php

8.2 INSTALLATION:
1. Open the installation program by double clicking on its icon.
2. If your Windows language is not supported by the installer, select an alternative
language you want to use (both for installation and later when using WinSCP).
3. On the License Agreementscreen click Accept after reviewing the license.
4. You will be prompted to select a setup type. For a basic setup, choose Typical
installation.
5. Then you will be prompted for Initial User Settings. This allows you to select user
interface style. If you have used (and enjoyed) file managers like Total Commander,
Altap Salamander or Norton Commander After you select the interface, theReady to
Install screen opens. On this screen, you can review the installation options you’ve
selected. Click Install to start the installation.
6. After you select the interface, theReady to Install screen opens. On this screen, you can
review the installation options you’ve selected. Click Install to start the installation.
7. A brief installation process will take place. You may have to restart Windows Explorer
or your computer. If you choose not to restart, some WinSCP functions may not be
available until you do so.

8.3 CONNECTING:
Start WinSCP. Login Dialog will appear. On the dialog:
● Select your File protocol. When you are about to use FTPS protocol, select FTP and
then choose one of the FTPS invocation methods.
● Enter your host name to Host name field, username to User name and password to
Password
● You may want to save your session details to a site so you do not need to type them in
every time you want to connect. Press Save button and type site name.

29
● Press Login to connect.

Once you are logged in, you’ll be presented with a dual-pane session window.The left side of
the screen is your local computer and the right side is your Raspberry pi.
You may copy files between the two systems by simply dragging and dropping them between
the panes ie you’re now able to visually manage your remote filesystem using WinSCP.

Fig. 8.1 WinSCP screen

30
CHAPTER-9

REMOTE ACCESS TO RASPBERRY PI


9.1 Introduction to Putty: Sometimes you need to access a Raspberry Pi without connecting it
to a monitor. Perhaps the Pi is embedded in something like a robot, or you may want to view
some information from it from elsewhere.
Any device connected to a Local Area Network is assigned an IP address. In order to connect to
your Raspberry Pi from another machine, you need to know the Pi's IP address. There are two
methods of remotely accessing a pi. They are-
○ Via SSH - Command line mode
○ Via RDP - GUI mode
SSH enables access of the Raspberry Pi command line. However, if you want to boot to the GUI
(startx) you will need a different program that is RD Connection Manager - a remote desktop
manager.

9.2 Secure Shell (SSH)


SSH is a secure network protocol for data communication. Via SSH, you can access the
command line of a Raspberry Pi remotely from another computer or device on the same network.
Also, you can quickly copy text or files across to your Pi's command line instead of typing it all
out. You need two computers - a server (your desktop) and a client (the Raspberry Pi).
The steps to logging into your Raspberry Pi's console from another PC or laptop are -

1. Give your Raspberry Pi a Static IP:


To log in to your Raspberry Pi remotely, you'll need the IP of the Raspberry Pi – this tells the
host computer where to look for it on the network. By default, the Raspberry Pi will be given an
IP automatically by the router (called Dynamic IP) when you connect to a network. However,
this can change whenever you remove the Pi from the network e.g. turn it off. It's therefore very
useful is the IP never changes, hence a 'static' IP. Use the following command to grab your Pi's
current IP.
> Ifconfig

31
2. Enable SSH:
Raspbian has the SSH server disabled by default. It can be enabled manually from the desktop:
➢ Launch Raspberry Pi Configuration from the Preferences menu
➢ Navigate to the Interfaces tab
➢ Select Enabled next to SSH
➢ Click OK

Alternatively, raspi-config can be used:


➢ Enter sudoraspi-config in a terminal window
➢ Select Interfacing Options
➢ Navigate to and select SSH
➢ Choose Yes
➢ Select Ok
➢ Choose Finish

sshpi@192.168.2.# :
➢ Open the Terminal window and on the command line, type the above command.
➢ Once the local IP address of the RPi has been found, the above command can be used to
establish an SSH connection using the default username/password combination of "pi"
and "raspberry".

3. Install the SSH client on your computer: Download an SSH client to your computer.
We are going to use Putty, which is an SSH and telnet client, developed originally by
Simon Tatham for the Windows platform. It is open source software that is available with
source code and is developed and supported by a group of volunteers. Putty is great for
generally browsing around your Pi's folders and copying files to or from a Windows PC.
Download from : www.putty.org

32
Fig. 9.1 Putty Configuration Screen
Simply hit yes and continue - you should be relatively sure that you're accessing the
correct device.

Fig. 9.2 Putty Security Alert

33
Login using Username :pi

Password : Power

Fig. 9.3 Putty Login Screen

This will appear on the computer desktop & you can access the remote desktop environment now.

CHAPTER-10

34
PYTHON
10.1 Introduction to Python : Python is a widely used high-level programming language for
general-purpose programming. It is a wonderful and powerful programming language that's easy
to use (easy to read and write) and with Raspberry Pi lets you connect your project to the real
world.
An interpreted language, Python has a design philosophy which emphasizes code readability and
a syntax which allows programmers to express concepts in fewer lines of code than might be
used in languages such as C++ or Java. The language provides constructs intended to enable
writing clear programs on both a small and large scale.
Python also has a large collection of libraries, which speeds up the development process. There
are libraries for everything you can think of – game programming, rendering graphics, GUI
interfaces, web frameworks, and scientific computing.

10.2 PIP:
PIP is a recursive acronym that can stand for either "Pip Installs Packages" or "Pip Installs
Python". It is a package management system used to install and manage software packages
written in Python. Many packages can be found in the Python Package Index (PyPI).
Most distributions of Python come with pip preinstalled. Like, Python 2.7.9 and later (on the
python2 series), and Python 3.4 and later include pip (pip3 for Python 3) by default. If pip is
missing, it can be installed through the system package manager.
One major advantage of pip is the ease of its command-line interface, which makes installing
Python software packages as easy as issuing one command-
> pip install some-package-name
Users can also easily remove the package-
> pip uninstall some-package-name

10.3 INSTALL PYTHON DEVELOPMENT TOOLS:


To program the GPIO pins on Raspberry Pi with Python, there is a Raspberry Pi GPIO Python
library that is made available. For this, open a terminal on the Raspberry Pi either via the desktop
or by using SSH. (default credentials are pi/raspberry). Run the following commands to install
some basic Python development tools:
> sudo apt-get update
> apt-get install python-dev python-pip
> pip install python

35
CHAPTER-11

INSTALL GPIO LIBRARY

11.1 Introduction : The RPi.GPIO Python library allows you to easily configure and read-write
the input/output pins on the Pi’s GPIO header within a Python script. Thankfully this library is
now including in the standard Raspbian image. If it is required to install the RPi GPIO library,
there are two methods to install it-

11.2 Manual Installation :


The package is available from https://pypi.python.org/pypi/RPi.GPIO . There will be a
download button on the page as shown

Right click on this and copy the link address.


Further, in the terminal on the Raspberry Pi, paste the link address in the following command
to download the library-
> wget link address
This downloads the RPi.GPIO-0.6.3.tar.gz file. Extract the tar file to a new folder-
> tar -zxvf RPi.GPIO-0.6.3.tar.gz

Browse to the new directory i.e. into the above folder by-
> cd RPi.GPIO-0.6.3

and install the setup file-


> sudo python setup.py install

11.3 Install from Repository :


> sudo apt-get update

Then attempt to install the RPi.GPIOpackage :


> apt-get install python-rpi.gpio

If it isn’t already installed it will be installed. If it is already installed it will be upgraded if a


newer version is available.

Usually now, the default Raspbian image include the RPi.GPIO library but we would like to
install a newer version to get access to newer API for callbacks. This can be done by using-
> sudo pip install --upgrade RPi.GPIO

36
CHAPTER-12
SUBLIME TEXT

12.1 Introduction to Sublime Text: It is a proprietary cross-platform source code editor with a
Python application programming interface (API). It natively supports many programming
languages and markup languages, and functions can be added by users with plugins, typically
community-built and maintained under free-software licenses.

Fig. 12.1 Sublime


Sublime Text 3 (ST3) is lightweight, cross-platform code editor known for its speed, ease of use,
and strong community support. It’s an incredible editor right out of the box, but the real power
comes from the ability to enhance its functionality using Package Control and creating custom
settings.
We’ll look at how to setup Sublime Text for full stack Python development (from the front to
back), enhance the basic functionality with custom themes and packages, and use many of the
commands, features, and keyword shortcuts that make ST3 so powerful.
12.2 INSTALLATION:
1. Download the installer from https://www.sublimetext.com/3.
2. Install the software.

3. Then, paste the following crack in the Help menu → Enter License.
—– BEGIN LICENSE —–
Michael Barnes
Single User License

37
EA7E-821385
8A353C41 872A0D5C DF9B2950 AFF6F667
C458EA6D 8EA3C286 98D1D650 131A97AB
AA919AEC EF20E143 B361B1E7 4C8B7F04
B085E65E 2F5F5360 8489D422 FB8FC1AA
93F6323C FD7F7544 3F39C318 D95E6480
FCCC7561 8A4A1741 68FA4223 ADCEDE07
200C25BE DBBC4855 C4CFB774 C5EC138C
0FEC1CEF D9DCECEC D3A5DAD1 01316C36
—— END LICENSE ——

12.3 CONFIGURATION:

Open winscp and connect to Pi via IP address and username and password. Then go to tools
(shown in left of winscp) --> Preferences --> editors. When we go to editors there are two
options to select, one is Notepad and other is Internal Memory. Choose either of one option.

Fig. 12.2 Configuration of Sublime

38
Then select edit option and go to external editor.Finally, browse the path in which your sublime
text 3 is placed in your PC.

Fig.12.3 Add editor

After this WinSCP opens. Go to raspberry pi folder and you want to name your folder in your pi.
Then you right click in pi folder and go to new and then directory. Name your folder name and
select permissions and according to your permissions octal code has been sent. In these
permissions, R-Read W-Write X-Executable

39
Fig 12.4 Permissions

CHAPTER-13

PROGRAMMING WITH PYTHON ON RASPBERRY PI

14.1 Introduction :You can write a Python file in a standard editor like Sublime or Nano, and
run it as a Python script from the command line.
pi@raspberrypi ~ $
This (above) is the command prompt. A CLI or command line interface is actually a very quick
and efficient way to use a computer.
To start, just navigate to the directory where the file is saved (use cd and ls for guidance).
TIP: You can use the TAB key for autocomplete as you enter commands.
Then, run the program (e.g. hello) with python using the command
> python hello.py

14.2 Few commands which we are going to use in PYTHON program:

○ import RPi.GPIO as GPIO


We are going to import GPIO file from library, above function enables us to program GPIO
pins of PI. We are also renaming “Rpi.GPIO” to “GPIO”, so in the program whenever we want
to refer to GPIO pins we will use the word ‘GPIO’.

○ GPIO.setwarnings(False)
Sometimes, when the GPIO pins, which we are trying to use, might be doing some other
functions. In that case, we will receive warnings while executing the program. Below command
tells the PI to ignore the warnings and proceed with the program.

○ GPIO.setmode (GPIO.BCM)
We can refer the GPIO pins of PI, either by pin number on board or by their function number.
In pin diagram, you can see ‘PIN 35’ on the board is ‘GPIO 19’. So we tell here either we are
going to represent the pin here by ‘35’ or ‘19’.

40
○ GPIO.setup(19,GPIO.IN)
We can set the GPIO pins as input or output pins using setup command. As shown below we are
setting GPIO 19 (or PIN 35) as output pin. We will get PWM output from this pin.

○ While 1
It is used for infinity loop. With this command the statements inside this loop will be executed
continuously.

CHAPTER-14
PROGRAMS

14.1 SIMPLE INPUT/OUTPUT WITH RPI AND PYTHON :

FIG. 14.1 simple i/o with python

After the above program is executed from nano file, pin 17 goes low i.e. LED connected to pin
17 becomes OFF while those connected to pins 27 and 22 are switched ON.

41
14.2 SIMPLE INPUT/OUTPUT WITH DELAY:

FIG. 14.2 simple i/o with delay

14.3 SIMPLE INPUT/OUTPUT WITH LOOP :

42
Fig. 14.3 simple i/o with looP
14.4 INPUT SWITCH:

The quintessential LED blinking program is as shown below. The circuit for the switch
connected to the GPIO pin can be of the following two ways. The output on LED will be
according to the circuit used.

Fig. 14.4 Input switch

We have assumed that you have connected a breadboard, LED, resistor to the Raspberry Pi
GPIO and below is the simple program in which the switch - switches the LED on when the
button is pressed and switches it off again when the button is released.

43
Every 0.1s, this program checks the switch status -
● if not pressed (input port 25 == 1), button status is displayed and the LED is switched off
(output port 24 is set to 0)
● Otherwise,if pressed (input port 25 == 1), button status is displayed and the LED is
switched on (output port 24 is set to 1)
It keeps going until CTRL+C is pressed.

In the above program, if the delay is not provided you will probably notice that it printed many
times for just a single press. This may sometimes be what you want if you’re monitoring
something which changes state continuously, but for a button we’re probably only interested in
seeing each press as one event.

14.5 PULSE WIDTH MODULATION


PWM stands for ‘Pulse Width Modulation’.Pulse Width Modulation (or PWM) is a technique for
controlling power and is used for used for getting variable voltage out of constant power supply.
We will generate PWM signal from Raspberry Pi and demonstrate the PWM by varying the
brightness of a LED, connected to Pi.There are two important parameters that determine PWM-
1. Frequency
2. Duty cycle

Frequency:
Frequency, in Hertz (Hz) is the number of times per second that a pulse is generated. This counts
from the start of one pulse to the start of the next. i.e. from when the pulse starts to rise, to the
next time it starts to rise. So it includes all the “on” time and “off” time and “in between” time
for one complete wave cycle.

44
Duty Cycle:
The amount of time the PWM pin is high within each cycle is called the duty cycle. Also, it is the
proportion for which the LED is ON over the total time and can be calculated as follows:
Duty Cycle =Turn ON time/ (Turn ON time + Turn OFF time)

Fig. 14.5 Switch


In above figure, if the switch is closed continuously over a period of time, the LED will be
‘ON’ during this time continuously. If the switch is closed for half second and opened for next
half second, then LED will be ON only in the first half second.
Duty Cycle = (0.5/ (0.5+0.5)) = 50%
So the average output voltage will be 50% of the battery voltage. This is the case for one
second and we can see the LED being OFF for half second and LED being ON the other half
second. If Frequency of ON and OFF times increased from ‘1 per second’ to ’50 per second’.

45
Fig. 14.6 Waveforms of PWM

We will program the Pi for getting a PWM and connect a LED to show its working.

To create a PWM instance:


○ p= GPIO.PWM(channel,frequency)
The above command is for setting up the channel and also for setting up the frequency of the
PWM signal. ‘P’ here is a variable it can be anything.

To start PWM signal generation:


○ p.start(dc) # where dc is the duty cycle (0.0 <= dc <= 100.0)

To change the frequency:


○ p.ChangeFrequency(freq) # where freq is the new frequency in Hz

To change the duty cycle:


○ p.ChangeDutyCycle(dc) # where 0.0 <= dc <= 100.0

To stop PWM:

46
○ p.stop()
Note that PWM will also stop if the instance variable 'p' goes out of scope.
When you’re done, don’t forget to cleanup with GPIO.cleanup(), then hit CTRL+Z to exit the
Python live environment.
With the program below being executed, the duty cycle of PWM signal increases. With an LED
attached to this PIN, brightness of LED increases.

47
The above program can be modified by using a switch. Below is the simple program in
which the switch controls the brightness of the LED.

48
49
Fig. 14.7 PWM

14.6 PROGRAM TO PRINT ASCII ART

Fig. 14.8 ASCII art

50
14.7 PROGRAM TO INCREMENT THE VALUE

Fig. 14.9 Increment value

51
14.8 PROGRAM TO PULL_UP_DOWN REGISTERS USING SWITCH

Fig. 14.20 Pull Up Down

CHAPTER-15

INTRODUCTION TO GPIO AND PHYSICAL COMPUTING ON THE


RASPBERRY PI

15.1 Introduction: One powerful feature of the Raspberry Pi is the row of 40 GPIO (general
purpose input/output) pins along the top edge of the board in the models A+,B+, raspberry Pi 2B
and 3B

52
Fig. 15.1 GPIO pins

15.2 GPIO:

General purpose input/output; in this specific case the pins on the Raspberry Pi and what you can
do with them. So called because you can use them for all sorts of purposes; most can be used as
either inputs or outputs, depending on your program.

GPIO PINOUT:
This GPIO Pinout is designed to be both a quick, interactive reference to the Raspberry Pi GPIO
pins, plus a comprehensive guide to your Raspberry Pi's GPIO interfaces. It also includes dozens
of pinouts for Raspberry Pi add-on boards, HATs and pHATs.

The Raspberry Pi GPIO pinout can be found on www.pinout.xyz. The pinout for the models
consisting of 40 pins is as shown below -

53
Fig. 15.2 GPIO pin layout

The GPIO pins allow the Raspberry Pi to control and monitor the outside world by being
connected to electronic circuits. The Pi is able to control LEDs, turning them on or off, run
motors, and many other things. It's also able to detect whether a switch has been pressed, the
temperature, and light. We refer to this as physical computing.Inputs don't have to come from a
physical switch; it could be input from a sensor or a signal from another computer or device, for
example. The output can also do anything, from turning on an LED to sending a signal or data to
another device. If the Raspberry Pi is on a network, you can control devices that are attached to it
from anywhere and those devices can send data back. Connectivity and control of physical
devices over the internet is a powerful and exciting thing, and the Raspberry Pi is ideal for this.

54
CHAPTER-16
PROJECTS

16.1 PROJECT-1: WIRELESS HOTSPOT PRACTICAL

Webmin is a web-based interface for system administration for Unix. Using any modern web browser,
you can setup user accounts, Apache, DNS, file sharing and much more. Webmin removes the need to
manually edit Unix configuration files like /etc/passwd, and lets you manage a system from the console or
remotely. With it, it is possible to configure operating system internals, such as users, disk quotas,
services or configuration files, as well as modify and control open source apps, such as the Apache HTTP
Server, PHP or MySQL. Webmin consists of many CGC programs & web server that are written in Perl
version 5 Language.

Download Webmin from:


● downloads page or
● Run the command-
wgethttp://prdownloads.sourceforge.net/webadmin/webmin_1.840_all.deb

16.1.1 HOTSPOT
The Raspberry Pi can connect to a Wi-Fi network using a USB dongle but using that same
dongle you can also turn your Raspberry Pi into a wireless access point. Once set up correctly,
this will allow other wireless devices to connect to your Pi and optionally you can route any
traffic out through the Ethernet port and on to the internet (via the router from your ISP).

WHAT DO YOU NEED:


● Any Raspberry Pi, model B with power supply
● A boot SD card for the Raspberry Pi.
● A USB WiFi device that supports "Access Point" mode; the Raspberry Pi 3 has a built-in
AP Wi-Fi module.
● An Ethernet cable to connect to the local network.

HOW DOES IT WORK:


The Raspberry Pi is configured as a WiFi Hotspot, just like you would see in an internet cafe. It
allows you to connect to the internet over WiFi using the Raspberry Pi as the bridge to the
internet. The basic steps are-
● Enable a WiFi Access Point and broadcast on the channel of your choice
● Assign dynamic IP addresses to any device that connects to WiFi network
● Join the WiFi and Ethernet networks together by using Network Address Translation

55
INSTRUCTIONS:
To configure a hotspot requires several steps:
1. Configure the wireless adapter with a static IP address
2. Install and configure a DHCP server
3. Install and configure the access point daemon
4. Configure IP routing between the wireless and Ethernet
In this example, the wireless network will use the address range 10.x.x.x and the wired Ethernet
will use the address range 172.168.1.x.

1. Configure the wireless adapter with a static IP address:


Edit “/etc/network/interfaces” and add the static IP address information for wlan0.
> sudonano /etc/network/interfaces

Place a “#” sign in front of all the lines which mention wlan0 and wpa, except for “allow
hotplug wlan0“. Then add the following lines to the file:
○ iface wlan0 inet static
○ address 10.0.0.1
○ netmask 255.0 .0.0

Fig. 16.1.1 Configuration

Press ctrl + x to exit. Type y to save and enter to confirm. Now, reboot-
> init 6

2. Install and configure a DHCP server:

To install the DHCP server, run either of the two commands given below-
> sudo apt-get install isc-dhcp-server
> sudo apt-get install udhcpd

56
You can safely ignore any errors about not being able to start the DHCP server at this point.
Now edit its configuration file:
> sudonano /etc/udhcpd.conf
Edit the file /etc/udhcpd.conf and configure it like this:
○ start 10.0.0.4 #This is the range of IPs that the hotspot will give to client devices.
○ end 10.0.0.204
○ interface wlan0 #The device UDHCP listens on.

Fig. 16.1.2 Configuration of udhcpd file

Add a “#” character in front of the “option domain-name” lines like this:
#option domain-name "example.org";
#option domain-name-servers ns1.example.org, ns2.example.org;

Remove the “#” sign in front of the “authoritative;” statement like this:
# If this DHCP server is the official DHCP server for the local
# network, the authoritative directive should be uncommented.
Authoritative;

At the bottom of the file add the following lines:


○ opt dns 10.0.0.1 172.16.20.20 #The DNS servers client devices will use.
○ opt subnet 255.0.0.0
○ opt router 10.0.0.1 #The Pi's IP address on wlan0 which we will set up shortly.
○ opt lease 864000 #10 day DHCP lease time in seconds

57
Exit from nano with Ctrl + X.

Make thewireless adapter the default for the DHCP request by-
> sudonano /etc/default/udhcpd
To enable the DHCP change: DHCPD_ENABLED="no"
to
#DHCPD_ENABLED="no"
Exit from nano with “Ctrl + X”.
Restart the DHCP server-
> sudo service udhcpd restart

3. Install and configure the access point daemon:

Install hostapd by running the command-


> sudo apt-get install hostapd

Edit the hostapd configuration file and create a wireless network:


> sudonano /etc/hostapd/hostapd.conf
Add the following lines:
○ interface=wlan0
○ driver=nl80211 #driver=rtl871xdrv
○ ssid=MyPi
○ hw_mode=g
○ channel=6
○ macaddr_acl=0
○ auth_algs=1
○ ignore_broadcast_ssid=0
○ wpa=2
○ wpa_passphrase=raspberry
○ wpa_key_mgmt=WPA-PSK
○ #wpa_pairwise=TKIP #Do not use this weak encryption (only used by old client
devices)
○ rsn_pairwise=CCMP
This will create a password protected network called ‘MyPi’ on channel 6 with the
password ‘raspberry’.

If you would like to create an open network, put the following text instead of the above one-
○ interface=wlan0
○ ssid=My_AP
○ hw_mode=g

58
○ channel=6
○ auth_algs=1
○ wmm_enabled=0

In addition the built-in Raspberry Pi 3 Wi-Fi module seems to require the following additional
parameters-
○ ieee80211n=1 # 802.11n support
○ wmm_enabled=1 # QoS support
○ ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]

Tell hostapd where to find its configuration file by setting the default location-
> sudonano /etc/default/hostapd
Remove the “#” in front of “DAEMON_CONF” and alter the line to read:
DAEMON_CONF="/etc/hostapd/hostapd.conf”

4 Configure IP routing between the wireless and Ethernet:

Configure NAT (Network Address Translation). NAT is a technique that allows several
devices to use a single connection to the internet. Linux supports NAT using Netfilter (also
known as iptables) and is fairly easy to set up.

First, enable IP forwarding in the kernel-


> sudosh -c "echo 1 > /proc/sys/net/ipv4/ip_forward"
To set this up automatically on boot, edit “/etc/sysctl.conf”by-
> sudonano /etc/sysctl.conf
Find the line which reads “Uncomment the next line to enable packet forwarding for IPv4”
and uncomment the next line like this:

Second, enable NAT in the kernel or to turn the Pi into a router run the following commands
one by one:
> sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
> sudo iptables -A FORWARD -i eth0 -o wlan0 -m state
--stateRELATED,ESTABLISHED -j ACCEPT
> sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT

These instructions don't give a good solution for rerouting https and for URLs referring to a
page inside a domain, like www.nu.nl/38274.htm. The user will see a 404 error. Your Pi is

59
now NAT-ing. To make this permanent so you don't have to run the commands after each
reboot, save the routing tables into the file “/etc/iptables.ipv4.nat” by-
> sudosh -c "iptables-save > /etc/iptables.ipv4.nat"

Now, edit “/etc/network/interfaces“ using the command-


> sudonano /etc/network/interfaces
And add the following line to the end of the file. This line will restore the routing table
whenever the Pi is booted:
● pre-up iptables-restore < /etc/iptables.ipv4.nat
Your Pi should now be hosting a wireless hotspot. To get the hotspot to start on boot, run
these additional commands:
> sudo update-rc.dhostapd enable

> sudo update-rc.dudhcpd enable


You should now reboot your Pi and test the wireless access using a laptop, smartphone, tablet
or other Wi-Fi enabled device.

Fig. 16.1.3 Hotspot is available

60
16.2 PROJECT-2 : RASPBERRY PI WEBCAM SERVER USING MOTION

The Raspberry Pi is perfectly equipped to turn your USB based web cam into a fully functional
IP webcam. This will allow you to create a webcam for your Raspberry Pi so that you can view it
from any computer on the local network. Motion is a software that runs the camera on raspberry
pi.

Fig. 16.2.1 Webcam

COMPONENTS REQUIRED:
➢ Raspberry Pi with Raspbian installed and internet connection established.
➢ Webcam-
● PS3 Eye Camera
● Microsoft HD
➢ USB Powered Hub –We need a hub because the camera’s draw more power than the
Raspberry Pi can actually provide.

HOW TO SETUP A RASPBERRY PI WEBCAM SERVER:


1. Connect the USB camera to any one of the four available USB port.
2. Connect the ethernet cable i.e. LAN cable to your Pi and connect the other end to your
router. Then Power Up the Raspberry Pi.
3. To know ip address of your pi :
Use ifconfig command. eth0 is used for the attached ethernet cable.
>ifconfig eth0.

61
4. connect your pi with Putty by adding the right IP address in the host name.
5. now run the commands :
> sudo apt-get update
> sudo apt-get upgrade
6. Now, we need to install the software, we are using a great little application called Motion, this
will do a few things including accessing the USB cam, getting the images, and streaming them
via a built in web server. Motion also tracks & detects the motion in the video captured.
To install the motion software run the following command:
>sudo apt-get install motion

Fig. 16.2.2 Motion Installation

7.Type cd /dev to change the directory into dev folder.

8.Type ‘ls’ to check that the camera is connected & is correctly detecting the motion. The
video0 folder will be created i.e. camera is connected.

9.Type dev/video0

10. Next we need to edit some of the configuration files so that the motion service will start on
run up and be available on local network. First we will edit motion.conf file by-
>nano /etc/motion/motion.conf

62
Fig. 16.2.3 Editing Motion.conf file

Then you have to change some settings in the .conf file. It might be difficult sometimes to
find the settings but use 'ctrl + w' (Search) to find it. So follow the steps:

○ Make sure 'daemon' is ON.


○ Setup_mode OFF.
○ Set 'width' & 'height' to 640 & 480.
○ Set 'framerate' anywhere in between 15 to 30.
○ Auto_brightness ON.
○ Keep 'Stream_port' to 6666.
○ 'Stream_quality' should be 70.
○ 'Stream_localhost' to OFF.
○ 'Webcontrol_localhost' to OFF.
○ Webcontrol_port 4444
○ Set 'quality' to 80.
○ Set 'post_capture' to 5.
○ Press ctrl + x to exit. Type y to save and enter to confirm.
To ensure that the motion service will actually start as a daemon we need to change
another configuration setting, so enter the following:
Type motion & enter.

63
11. open a firefox webpage on your normal computer and type >
about:config > New > string > Name : network.security.port.banned.override > enter the port
number given above in motion.config

12. open the browser and type the IP address of raspberry pi with port number.
Eg. 172.16.33.224:6666
( Where 6666 is the port number.)

Fig. 16.2.4 Video will appear

13. video will appear as shown in the fig.16.2.4

64
16.3 SENSORS

A sensor is a device that measures a physical quantity and converts it into a 'signal' which can be
read by an observer or by an instrument. One of the many advantages of the Raspberry Pi is that
it is possible to connect almost all standard Arduino and Raspberry Pi sensors and components to
the various GPIOs. Moreover you can evaluate and / or process the values with programs and
other software. This accessory can be used in projects such as Smart Home (home automation),
robot kits or weather stations, etc.

The Raspberry pi provides 40 GPIO pins which provides digital interface with the motors,
sensors and monitoring the digital sensors but the GPIO pins do not interface with the analog
inputs.

Analog sensors for monitoring such data as temperature, humidity, light, and even wind speed
are readily available. With the single IC chip we can interface any type of analog sensor with the
raspberry pi.
These are the humidity and temperature sensors available from Adafruit.
1. DHT11
2. DHT22

16.3.1 DHT 11
DESCRIPTION:
The DHT11 is a basic, ultra low-cost digital temperature and humidity sensor. It uses a
capacitive humidity sensor and a thermistor to measure the surrounding air, and spits out a digital
signal on the data pin (no analog input pins needed). There are two variants of the DHT11 you’re
likely to come across. One is a three pin PCB mounted module and the other is a four pin stand-
alone module. The pinout is different for each one.

65
Fig. 16.3.1 DHT11

It is fairly easy to connect up to the DHT sensors. They have four pins VCC (3 to 5V power),
Data out, Not connected and Ground. Simply ignore pin 3, it’s not used. You will want to place a
10K resistor between VCC and the data pin, to act as a medium-strength pull up on the data line.
For DHT11 and DHT22 sensors, don't forget to connect a 4.7K - 10K resistor from the data pin
to VCC.

Fig. 16.3.2 Connecting DHT11 with Rpi

66
16.3.2 DHT22
DESCRIPTION: Compared to the DHT11, this sensor is more precise, more accurate and works
in a bigger range of temperature/humidity, but its larger and more expensive. It comes with a
4.7K - 10K resistor, which you will want to use as a pullup from the data pin to VCC.
DHT22 output calibrated digital signal. It utilizes exclusive digital-signal-collecting-technique
and humidity sensing technology, assuring its reliability and stability. Its sensing elements is
connected with 8-bit single-chip computer. Every sensor of this model is temperature
compensated and calibrated in accurate calibration chamber and the calibration-coefficient is
saved in type of programme in OTP memory, when the sensor is detecting, it will cite coefficient
from memory.
Small size & low consumption & long transmission distance(20m) enable DHT22 to be suited in
all kinds of harsh application occasions. Single-row packaged with four pins, making the
connection very convenient.

Fig. 16.3.3 DHT22

67
Connecting DHT22 to raspberry pi:

DHT22 requires Pin 1 to be connected to a 3.3V source, Pin 2 to the desired General-purpose
input/output (GPIO) pin on the RPi, and Pin 4 to ground (GND). A 10kΩ resistor is placed
between Pin 1 and Pin 2. Pin 3 in not used.

Fig. 16.3.4 Connecting DHT22 with Rpi

68
16.4 PROJECT 3: HOW TO UPLOAD THE DATA ON TWITTER

TWITTER
Twitter is an online news and social networking service where users post and interact with
messages, "tweets", restricted to 140 characters. Registered users can post tweets, but those who
are unregistered can only read them. Users access Twitter through its website interface, SMS or a
mobile device app. Raspberry Pi also offer you an alternative for this. You will need to have a
Raspberry Pi running Linux of some sort. We recommend the latest version of Raspbian, as it
comes pre-loaded with Python and GPIO libraries. Additionally, the Pi will need to be connected
to the Internet so that you can monitor the Twitter stream. This can be accomplished using an
Ethernet cable or a USB Wifi dongle. Sending a tweet using Pi is a very simple and
straightforward process.

1. Create a twitter account:

If you don't already have a Twitter account, you'll need to create one at twitter.com. Login to
Twitter and make a Twitterbot handle. You'll have to go through their steps of following several
people or organizations and verification via email.

Fig. 16.4.1 Signup in Twitter


In order to make the Twitter App available to you we have to add our mobile number for
verification purpose.

69
2. Create a Twitter application:

➢ Go to apps.twitter.comand click the Create New App button.

Next step is that we have to complete our following details.

Fig. 16.4.2 Create an Application in Twitter

70
○ Name: You can use any string for this fields, as long it doesn’t conflict with any other
app name on twitter. This field has a 32 character max limit.
○ Description: Provide some details for your app. App description must have at least 10
characters and may go up to 200 characters.
○ Website: If you have a website you can type its URL in this field. Don’t worry if you
don’t have a website, access to this URL will not be tested by twitter; so you can use any
dummy URL. Make sure the URL has correct format for ex: “https://www.iotbytes.com“.
○ Callback URL: Here we aren’t going to use call back feature so you can leave this field
blank.
○ Developer Agreement: Accept the Developer Agreement by clicking on the check box.
Read the terms of agreement and agree to them and then OK the dialog

After filling all these fields, click on “Create your Twitter application” button to complete the
process.

3. Modifying Permissions for Read/Write: You will be redirected to your newly


created app’s settings page. On this page, first modify your app permissions from Read
only to Read and write.

Fig. 16.4.3 Application Permissions

4. How to get API keys & Tokens: Click the 'Keys and Access Tokens' tab and
create an access token. Once you've clicked the Create an Access Token button, refresh
the page and you'll see a new section beneath the Application Settings with your access
token details.
You should now be able to see your Consumer key, Consumer secret, Access token, and
Access token secret. You'll need these four keys to connect to your Twitter account from
your Python code.

71
Fig. 16.4.5 Access Tokens

We do not have to share our these keys with anyone. In case we share these keys we have to
regenerate our keys by again logging into apps.twitter.com

5. Installing the library:


Before moving on to the Python Script, you need to install python library for twitter. SSH
into your Raspberry Pi, or else use the monitor. Run the latest package updates and
upgrades, just to make sure everything is current - you will have to have wifi access for
this step. Type in the commands -

72
> apt-get update
> apt-get upgrade

Now, uninstall the twitter -


> pip uninstall twitter
Then, use following command to install combined twitter-python package which will let
you use Twitter from Python-
> pip install python-twitter

6. Send a tweet from Python:


Now you have your API keys, and if your date/time is set correctly, you're ready to send a
tweet from Python.
Make a connection with the Twitter API using this set of keys. Create a new file and
paste your API keys from apps.twitter.com into variables.

73
74
Fig. 16.4.6 Twitter Program

Save this program and run.

Go to your Twitter profile in a web browser to verify it was sent! This will be at
twitter.com/username, where username is your Twitter account's username. Check Out the
Tweet.

Output of twitter program :

Fig. 16.4.7 Output

75
And on twitter account, tweet will be display as such :

Fig.16.4.8 Tweets on Twitter

Sending multiple tweets with the exact same text are classed as duplicates and rejected by
Twitter.
If you want to test it again, try tweeting a different message.
If you see an error, your API keys may be incorrect. Be sure to copy them exactly and check the
spelling of the variables. You should also check that your Pi is connected to the internet.

76
16.5 PROJECT 4: HOW TO LINK A DEVICE WITH APP

MY DEVICES
MY DEVICES is a Internet of Things solutions company. It accelerates IoT development and
empower enterprises to quickly design, prototype, and commercialize IoT solutions. To
accomplish the mission to simplify the connected world, it created Cayenne – the world’s first
drag-and drop IoT project builder that empowers developers to quickly create and host their
connected device projects. Cayenne was designed for the Internet of Things. It can control
hardware remotely, it can display sensor data, it can store data, analyze and do many other cool
things.

Cayenne App – setup and control your IoT projects with drag and drop widgets from an app.

Cayenne Online Dashboard – Use a browser to setup and control your IoT projects.

Cayenne Cloud – responsible for processing and storage of device, user and sensor data for
commands, actions, triggers and alerts.

Cayenne Agent – enables communication with the server, agent and hardware for implementing
incoming and outgoing commands, actions, triggers and alerts.

Every time you press a button from the Cayenne app or online dashboard, it travels to the
Cayenne Cloud where it’s processed and finds its way to your hardware. It works the same in the
opposite direction. You can use the Cayenne mobile app or online dashboard, it’s up to you. Any
changes you make to hardware from the mobile app are reflected when viewing the online
dashboard and vice versa.

GETTING STARTED:

1. Raspbian should be installed on pi.

2. Open mydevices.com and click on get started.

3. sign up to create a new account.

4.select raspberry pi & next.

5.Power on your raspberry pi & connect it to the internet.

6. Connect the Pi up to the account you just created. To do this simply copy the 2 command lines
shown after you sign up. Enter these into the terminal for your Pi.

77
Fig. 16.5.1 Installation of Cayenne app

7.It will take a few minutes to install onto your Pi depending on how fast your internet
connection is. The device will reboot and the web browser or app should automatically update
with information on the installation process.

8. Once installed it will look like this.

Fig. 16.5.2 MyDevices

9. configuration of the device like the device name and device icon etc can be done.

10. now, set up your sensor. The sensor that is used here is called DS18B20.

78
16.5.1 DS18B20

This sealed digital temperature probe lets you precisely measure temperatures in wet
environments with a simple 1-Wire interface. The DS18B20 provides 9 to 12-bit (configurable)
temperature readings over a 1-Wire interface, so that only one wire (and ground) needs to be
connected from a central microprocessor. The sensor is good up to 125°C the cable is jacketed in
PVC so we suggest keeping it under 100°C. Because they are digital, you don't get any signal
degradation even over long distances. These 1-wire digital temperature sensors are fairly precise
(±0.5°C over much of the range) and can give up to 12 bits of precision from the onboard digital-
to-analog converter. They work great with any microcontroller using a single digital pin, and you
can even connect multiple ones to the same pin, each one has a unique 64-bit ID burned in at the
factory to differentiate them.

Fig.16.5.3 DS18B20 Sensor

>Stainless steel tube 6mm diameter by 30mm long.

>Cable is 36" long / 91cm, 4mm diameter

> Usable temperature range: -55 to 125°C (-67°F to +257°F)

79
>Multiple sensors can share one pin

>±0.5°C Accuracy from -10°C to +85°C

> Usable with 3.3V power supply and 5V power supply.

Connecting DHT22 to Raspberry pi: If your sensor has four wires - Red connects to 3-5V, Black
connects to ground and White is data. The copper wire is soldered to the wire shielding or if your
sensor has three wires - Red connects to 3-5V, Blue/Black connects to ground and Yellow/White is
data.

Setting up the sensor:

1. Go to add new in the upper left corner of the dashboard.


2. Select device from the dropdown box.
3. Find the device, in this case it is a DS18B20 temperature sensor.
4. Add all the details for the device.
5. Once entered select add sensor.
6. The sensor should now be displayed on the dashboard.
7. If you need to customise your sensor press the cog and it will come up with some options.
8. You can also see stats/graphs. For example, the temperature sensor can plot data in real
time and will keep historical data too.

Fig.16.5.4 Selecting required Sensor

80
16.6 PROJECT 5: HOW TO UPLOAD DATA ON GOOGLE

GOOGLE
Adafruit have provided some software to interface with the sensor, which is available on
githubhttps://github.com/adafruit/Adafruit_Python_DHT.
16.6.1 Process:
1. DOWNLOADING THE CODE FROM GITHUB:
The easiest way to get the code onto your Pi or Beaglebone Black is to hook up an Ethernet
cable, and clone it directly using 'git', which is installed by default on most distros (or can be
done by using command apt-get install git). Simply run the following commands from an
appropriate location (ex. "/home/pi") -
> git clone https://github.com/adafruit/Adafruit_Python_DHT.git
> cd Adafruit_Python_DHT

2. INSTALLING THE ADAFRUIT PYTHON DHT SENSOR LIBRARY:


With the wiring is complete, download the Adafruit’s DHT library to the RPi, which is required
to read the temperature and humidity values from the sensor. To install the Python library on
either the Raspberry Pi or Beaglebone Black you will first need a few dependencies. Execute the
following command to install these dependencies (assuming you're using Raspbian on the Pi and
Debian on the Beaglebone Black):
> sudo apt-get update
> sudo apt-get install build-essential python-dev python-openssl

If you see an error that a package is already installed or at the latest version, don't worry you can
ignore it and move on.Next, to install the library execute & run the following steps step by step :
> sudo python setup.py install
> connecting to google
> apt-get install python-pip
> apt-get install gspread ouath2client
> apt-get purge python pyasn1
> pip install pyasn1
> ls
> cd examples
> cp *.* /home/pi
> cd /home/pi
> ls

81
3. TESTING THE LIBRARY:
To test the Python library, you can run some of the example programs in the examples
folder present in Adafruit_Python_DHT.
First navigate to the examples folder by executing:
> cd examples
> ls
Now, examine the source codes of the programs (like ‘simpletest’ and ‘google spreadsheet’) in
Nano editor to see simple examples of reading the DHT sensors from Python code.
SIMPLE TEST:
Edit the program in Nano as shown below. Use while loop for it to run continuously.
> nano simpletest.py

Fig.16.6.1 Editing Simpletest file

>ctrl+x
> yes
>execute the program with command: python simpletest.py
> reading will be displayed

82
Fig.16.6.2 Output of Simpletest program

16.6.2 GOOGLE SPREADSHEET :


Google spreadsheet program, readings from the sensors can be recorded online in a Google
spreadsheet. For this, you need your ‘json file name’ and the ‘google spreadsheet name.

How to create a JSON file :

JSON stands for JavaScript Object Notation. JSON is a lightweight data-interchange format. It is
a minimal, readable format for structuring data and is used primarily to transmit data between a
server and web application.

1. Open Google Developers Console and create a new project.


2. From at the top left corner, go to the Dashboard in the API Manager. Click on ‘Enable
API’.
3. Select Drive API & enable it.
4. Move forward to “Credentials” and create Creadentials > service account key.
5.

Fig.16.6.3 Creating Credentials

83
6. Create New Service Account. Select the role ‘Owner’ and the ‘JSON’ key type.

Fig.16.6.4 Create Service Account Key

8. Click on Create and you will automatically download a JSON file.


9. JSON file will look like.

Fig 16.6.5 JSON file

10. Copy the client email from this JSON file.

84
16.6.3 CREATE AND PREPARE SPREADSHEET:

1. Sign up for Google Docs & create a spreadsheet.

Fig.16.6.7 Google Spreadheet

2.Rename your spreadsheet.


3. Once you have created your spreadsheet delete all the rows instead of one row.

85
Fig.16.6.8 Renaming the google spreadsheet file

4. edit google_spreadsheet.py and adjust the configuration values towards the top of the file.
>nano google_spreadsheet.py
Set GDOCS_SPREADSHEET_NAME to the name of your spreadsheet and the
GDOCS_OAUTH_JSON to the name of the .json file. Make sure DHT_TYPE is set to the type
of sensor you are using (either Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or
Adafruit_DHT.AM2302), and DHT_PIN is set to the GPIO pin number which is connected to
your DHT sensor.

86
Fig.16.6.9 Google Spreadsheet Program

Save the file. Now, place the created .json file in the same directory as the
google_spreadsheet.py example. If you don't place this file in the same directory then
authentication will fail and you will not be able to update your spreadsheet.

5. last step that must be completed is to share your Google spreadsheet to the email address
associated with the OAuth2 credentials. Open the .json file and search for the "client_email".

87
6. Note that email address value and go to your Google spreadsheet in a web browser. Using the
File -> Share... menu item share the spreadsheet with read and write access to the email address
found below.

6.Execute the program :


> python google_spreadsheet.py

Fig.16.6.10 Output of Google Spreadsheet Program

Fig.16.6.11 Data is saved in Google Spreadsheet

You should see the program run and after about 5 seconds a humidity and temperature
measurement is displayed and written to the spreadsheet. The program will continue to run and
log a measurement until you force it to quit by pressing Ctrl+C.

88
16.7 PROJECT 6: PARTICLE.IO

Paricle.io is an open source hardware/software platform for the Internet of Things. It is the
fastest and easiest way to get your Internet of Things product up and running. It is an internet of
things (IoT) startup, providing a platform for individuals and small businesses to create their own
IoT devices. The company offers a range of hardware tools and cloud-based software, helping
companies to link their connected devices to the web and collect data on product usage to
improve functionality.

Fig.16.7.1 Particle.io cloud

PARTICLE POWERS THE INTERNET OF THINGS:

IoT is hard. Particle makes it easy.Particle’s full-stack of Internet of Things(IoT) device


platform gives you everything you need to securely and reliably connect your IoT devices to the
web.Particle includes everything you need to deploy an IoT product: a device cloud platform,
connectivity hardware, and even SIMs for cellular products.

➢ For using particle.io with the raspberry pi, first make an account in particle.io from
build.particle.io .

89
➢ Now go to docs.particle.io you will see the following options -
● Photon
● Electron
● Core
● Raspberry pi

Fig.16.7.2 Devices on Particle.io

We have to select the raspberry pi.

16.7.1 RASPBERRY PI:

90
The Raspberry Pi is an amazing credit-card sized computer with immense possibilities. It is a
low-cost single-board Linux computer designed and produced by the Raspberry Pi Foundation.
The Particle firmware is being developed on the Raspberry Pi 3.

Raspberry Pi is already the world’s most popular low-cost computer, and a powerful
development tool for building connected projects. Connecting your Pi to the Particle Cloud gives
it a few more key features that will make building IoT projects with your Pi easier than ever.

Quick Install:
Copy the following command shown on the docs.particle.io page -
> bash <( curl -sL https://particle.io/install-pi )

What You'll Need:


In order to connect your Raspberry Pi to the Particle Cloud you'll need the following things. Note
that these are all included in the Particle Pi Starter Kit with Raspberry Pi v3

>raspberry pi v3
>power supply
>micro SD card
>Ethernet cable

Fig.16.7.3 Raspberry pi
Install the Particle Agent:
connect your Raspberry pi to the Particle Cloud, you need to install the Particle Agent. The
Particle Agent is a software service that runs in the background on the Raspberry Pi and allows
you to write and run firmware.

91
Install by running the command:
>bash <( curl -sL https://particle.io/install-pi )

installation is over, the Particle Agent setup will ask you to sign in to your Particle account.

Control an LED With Particle App:


Now install the application particle.io in your mobile phone using playstore.
1. Open Dash-Board and then Open Your "Raspberry Pi" on Device List.
2. Here, we are using D7 pin on Particle app that belongs to Pi 35 pin or GPIO19 so connect
an LED to Pi pin 13 or GPIO19.
3. Set pins in Particle App. Click on D7 and Select pinMode. Here, we have digitalWrite.
4. Now Click on D7 button.
5. Done.

92
93
Fig.16.7.4 Controlling the device using Particle App

We can turn on and off the LED using the app.

16.8 PROJECT 7: IFTTT

IFTTT

IFTTT is a free web-based service that people use to create chains of simple conditional
statements, called applets. An applet is triggered by changes that occur within other web services
such as Gmail, Facebook, Instagram, or Pinterest.[4] An applet may send an e-mail message if the
user tweets using a hashtag or copy a photo on Facebook to a user's archive if someone tags a
user in a photo. IFTTT is an initialism for If This Then That.

In addition to the Web-based application, IFTTT runs on iOS and Android.

IFTTT is an automation that will enable you to connect 2 services so that, when something
happens with one service, a trigger goes off and an action takes place automatically on the other.

1. Open website ifttt.com

94
Fig.16.8.1 IFTTT website

2. Login into your account .

Fig.16.8.2 Login screen

4. Go to my Applet and create a new Applet.


5. Click on Get started and new applet.

95
6. At the top click on ‘Search’ and find ‘particle’, and then click the ‘Connect’
button to create a particle channel. Click on the gears icon (Settings) on the top-
right of the particle to view your key. Copy this key to Open Sprinklers IFTTT key
setting.

Fig.16.8.3 Create a New Applet

7. Idea of IFTTT is that you can connect a trigger (this) with an action (that).For
example, if the particle receives a message from Open Sprinkler, then send a text
message to my phone. These are formally called recipes, and are now called Applets.
8. IFTTT did not allow creating applets using the web interface, and instead required
using the mobile app. Since then they have allowed using the web interface to create
applets.
9. For trigger service (this), search and select ‘facebook’. Set sprinkler as the ‘Event
Name’ of the web request.
10. For action (that), search and select a desired notification method, such as ‘SMS’,
or ‘email’.

96
Fig.16.8.4 Triggering

11. Monitor your device started with your device name(online).

Fig.16.8.5 Choose a Trigger

12. Click on create Trigger.

97
Fig.16.8.6 Create Trigger

13. Login into your facebook account.

Fig.16.8.7 Login into Facebook account

14. Create link post on facebook.

98
Fig.16.8.8 Link post with facebook

15. Open Putty and restart your pi.

16. Login into your facebook account to view your post.

Fig.16.8.9 Login into facebook

99
16.9 Project 8: How to link NODEMCU with Adafruit

Fig. 16.9.1 NodeMCU

1. Firstly we have to install the drivers of Node MCU i.e. they are CH340 in the laptop.
2. Install the Arduino IDE of version 1.6.8.
3. Install the ESP8266 Board Package and enter.
http://arduino.esp8266.com/stable/package_esp8266com_index.json in the additional board
Managers.

Fig.16.9.2 Additional Board Manager

100
4. Use the Board manager to install the ESP8266 package.

Fig.16.9.3 Installing ESP8266 package

5. Choose the board as Node MCU 1.0(ESP12-E) and 80MHZ CPU frequency.

Fig.16.9.4 selecting the board ESP12-E

101
6. Set the port by choosing the right com port.

Fig.16.9.5 Selecting the right port

6. Now we have to install the certain libraries.

Fig.16.9.6 Manage Libraries

102
8. Enter Adafruit IO Arduino into the search box, and click Install on the Adafruit IO
Arduino library option to install version 2.1.1 or higher.

Fig.16.9.7 Installing Adafruit IO Arduino library

9. Enter Adafruit MQTT into the search box, and click Install on the Adafruit MQTT library


option to install version 0.16.1 or higher.

Fig.16.9.8 Installing Adafruit MQTT library

103
10. Enter ArduinoHttpClient into the search box, and click Install on
the ArduinoHttpClient library option to install version 0.2.0 or higher.

Fig.16.9.10 Installing Arduino HTTP Client library

11. Now after installation of certain libraries now we can run any one example.

Fig.16.9.11 Run any Example

104
12. Click on config.h and edit the certain credentials.

105
Fig.16.9.12 Editing wifi credentials

13. Click on upload and compile the code and check the output in the Serial Monitor.

106
Fig.16.9.13 Output in Serial Monitor

14. Now we can upload the data on Adafruit cloud i.e. ADAFRUIT.IO

15. Make a account on the Adafruit.io and then click on > Action > Create a new Dashboard >
Name____ > OK.

16. Click on created dashboard and click on the key to retrieve your key.

Fig.16.9.14 Add Block


17. Click on ‘+’ to create a block.

107
18.Add a new stream block.

Fig.16.9.15 Add a Stream Block

19. give any name as ‘counter’ which should be same as that given in the program and click on
‘counter’ and next step.

108
Fig.16.9.16 Create a New Block

20. Modify stream block options and create the block.

Fig.16.9.17 Create Block

21. Output will be displayed with varying values.

109
CHAPTER-17

REFERENCES

1. GOOGLE.COM
2. WIKIPEDIA
3. RASPBERRY PI.COM
4. PINOUT.XYZ

110

You might also like