Sie sind auf Seite 1von 88

List of Tables

Table 1 Comparison of different Communication technology ............................................... 9


Table 2 Specification of R-Pi................................................................................................ 20
Table 3 P1 Header ................................................................................................................. 22

List of Figures
Figure 1 BBC Research ........................................................................................................ 11
Figure 2 Wireless Color Video Door Monitor with Intercom System ................................. 12
Figure 3 Crestron Green Light Power Pack .......................................................................... 14
Figure 4 ML-600 ................................................................................................................... 16
Figure 5 Block Diagram of Home Automation System ...................................................... 17
Figure 6 Structural Block Diagram ....................................................................................... 18
Figure 7 Components of Raspberry Pi .................................................................................. 21
Figure 8 P5 Header ............................................................................................................... 22
Figure 9 IP Address in Command window ........................................................................... 27
Figure 10 LX Terminal Of Raspberry pi .............................................................................. 28
Figure 11 Installing Packages ............................................................................................... 31
Figure 12 Choose Packages .................................................................................................. 32
Figure 13 Eclipse Window ................................................................................................... 33
Figure 14 Install ADT ........................................................................................................... 34
Figure 15 Architecture of Android ....................................................................................... 35
Figure 16 New Android Wizard ........................................................................................... 41
Figure 17 Anatomy of Android Application ......................................................................... 42
Figure 18 Package Explorer .................................................................................................. 43
Figure 19 Hello World Application ...................................................................................... 48
Figure 20 Activity Flowchart ................................................................................................ 49
Figure 21 Communication link ............................................................................................. 58
Figure 22 IP Address Format ................................................................................................ 59
Figure 23 Flow chart of TCP ................................................................................................ 61
1

Figure 24 Pin diagram of GPIO ............................................................................................ 64


Figure 25 Run Python File .................................................................................................... 65
Figure 26 Schematic Interfacing LED .................................................................................. 65
Figure 27 Interfacing LED on Bread Board ......................................................................... 65
Figure 28 Output snap of Blinking LEDs ............................................................................. 67
Figure 29 Interfacing of LEDs and Switch ........................................................................... 67
Figure 30 Output of LEDs with Switch ................................................................................ 68
Figure 31 Android Application ............................................................................................. 69
Figure 32 Client and Server Java Application ...................................................................... 70
Figure 33 Output on raspberry Pi ......................................................................................... 71
Figure 34 PC to Android Phone communication .................................................................. 71
Figure 35 Schematic of interfacing LEDs ............................................................................ 72
Figure 36 Output of Raspberry pi from Android Application .............................................. 75
Figure 37 Output of Raspberry pi GPIO from Android Application .................................... 75

INDEX
1. INTRODUCTION .................................................................................................................. 5
1.1 Problem Statement ............................................................................................................. 5
1.2 Introduction to topic ........................................................................................................... 5
1.3 Source of Inspiration .......................................................................................................... 6
2. LITERATURE SURVEY ...................................................................................................... 7
2.1 Communication protocol .................................................................................................... 7
2.2 Market Survey .................................................................................................................. 11
3. HOME AUTOMATION SYSTEM ..................................................................................... 17
3.1

Block Diagram ............................................................................................................ 17

4. RASPBERRY PI ................................................................................................................... 19
4.1 Specification of Raspberry pi ........................................................................................... 20
4.2 GPIO................................................................................................................................. 21
4.3 Basic Requirement of raspberry pi ................................................................................... 23
4.4 LINUX OSs for Raspberry Pi .......................................................................................... 23
4.5 Introducing Raspbian ....................................................................................................... 24
4.6 Flashing OS in the SD Card ............................................................................................. 24
4.7 Setting Up Raspberry Pi ................................................................................................... 25
4.8 Plugging in your Raspberry Pi ......................................................................................... 25
4.9 Logging into your Raspberry Pi ....................................................................................... 26
4.10 Update the System Software .......................................................................................... 26
4.11 Configure the Network ................................................................................................... 26
5. ANDROID ............................................................................................................................. 29
3

5.1 Introduction to Android .................................................................................................... 29


5.2 Features of Android .......................................................................................................... 29
5.3 Environment Setup ........................................................................................................... 30
5.4 Architecture ...................................................................................................................... 35
5.5 Hello World Example ....................................................................................................... 40
5.6 Android Layout Types...................................................................................................... 51
6. TCP/IP ................................................................................................................................... 58
6.1 Introduction ...................................................................................................................... 58
6.2 Networks .......................................................................................................................... 58
6.3 IPv4 Internet Protocol ...................................................................................................... 59
6.4 Socket Programming For TCP Server & Client ............................................................... 59
6.4.1 Steps involved in TCP connection ................................................................................ 59
6.5 Socket Programming For TCP Server & Client ............................................................... 60
7.0 WORK DONE .................................................................................................................... 62
7.1 Raspberry pi GPIO ........................................................................................................... 63
7.2 Android Application ......................................................................................................... 69
7.3 PC to PC communication using TCP ............................................................................... 70
7.4 PC to Raspberry Pi communication using TCP ............................................................... 71
7.5 PC to Android Phone communication using TCP ............................................................ 71
7.6 Raspberry pi GPIO from Android Application Using TCP ............................................. 72
CONCLUSION ......................................................................................................................... 76
APPENDIX ............................................................................................................................... 78

1. INTRODUCTION
1.1 Problem Statement
To Control and Monitor various appliances in Home through Raspberry Pi board and other
peripheral Modules.
OBJECTIVE:
Part A:

To control various appliances from android based tablet/mobile.

Video door phone in which we can see person want to enter in to home standing at the
main door, also one can open from android application.

Water level control system which control water pump based on water sensor input.

Part B (Optional as if time permits):

Develop Web Server for control and monitoring of Home Appliance from remote
location(outside the Home)

Analog control offering to appliances like fan and light as achieve speed control and
dimming respected.

1.2 Introduction to topic


Old age persons faces problem of turning ON or OFF various appliances in home.
This will also help and make life easy for any ordinary person if there is automation in
home appliances. So we are proposing system based on raspberry pi and android
application on tablet or phone home automation system for this problem. The block
diagram of the system is shown in below.
It is proposed to control various home appliances like Tube light, Bulb and Fan
using android application in tablet or any other android platform based handheld device.
This whole system will be controlled by Raspberry pi. For wireless connection it is
5

proposed to use USB WiFi Adapter which is connected with raspberry pi and Tablet with
WiFi(IEEE 802.11 protocol) connection. One will able to select appliances from the
application, as command will be given to the raspberry pi. According to that command
Raspberry pi will give signal to relay switching circuit to turn ON/OFF particular Electrical
appliance. There are also water control system in which it can measure the water level of
the water tank and display on Android application. The level control can be perform by
ON/OFF the water pumps motor connected at raspberry pi.
In monitoring system, there is one camera outside the main door which can be
accessed from the tablet, using android application. It is proposed to control to open the
door; also Raspberry pi is having a socket through which one can connect camera.
It is thought of adding facility analog controls offering to appliances like fan or
light as achieve speed control or dimming respect using thyristor module by interfacing
with raspberry pi.
1.3 Source of Inspiration
The motivation is to facilitate the old age people to turn ON or OFF various appliances
easily. This will also help and make life easy for any ordinary person if there is automation
in home appliances. The system provides availability due to development of a low cost
system. The home appliances control system with an affordable cost was thought to be built
that should be android based tablet providing remote access to the appliances. The system
also provides monitoring system with the help of camera which is located at the outside of
the main door.

2. LITERATURE SURVEY

2.1 Communication protocol


The home automation refers to domestic environment that improves the quality of the
residents life by facilitating a flexible, comfortable, healthy, and safe environment.
Internet based home automation systems become the most popular home automation
system in international markets. The remote controlling and monitoring of a house using
internet requires computer, which is large in size and heavy to carry around. The most
available home automation systems use different wireless communication standard to
exchange data and signaling between their components, like IR,RF,Bluetooth, Zigbee, WiFi, and finally the Global System for Mobile Communication (GSM) . Wireless based
home automation systems decrease installation cost and effort, and enhance system
flexibility and scalability.

In Home automation systems there are collections of interconnected devices for


controlling various functions within a house. Mobile devices are ideal in providing a user
interface in a home automation system, due to their portability and their wide range of
capabilities. . Within the house, the user might not want to go to a central control panel,
or not even to the laptop, but use the phone that is usually placed in closer proximity to
the user. When far from the house, the user might want to check its current status or even
schedule actions for his return.

In concept of android based home automation system we can provide end users with
simple secure and easily configurable home automation system .Also the concept can
overcome the barriers facing home automation systems and will enable a home
technology ecosystem that allows people to easily adopt the subset of home automation
technology that appeals to their household. Home Automation is becoming an inevitable
thing in our fast developing environment and current life style. New trends in lifestyle
have enhanced the installation of automated home appliances in many places. Home
automation not only refers to the automation of appliances in a house but also the
7

automation of things that we use in our daily life such as cars, telephones etc.
Automation of appliances was firstly introduced in offices for ease of use and also for
reduction in time and cost consumption. Nowadays, home automation systems are
available in a number of varieties. A few have been discussed here.

IR Remote based Home Automation System.

RF Remote based Home Automation System.

Zigbee based Home Automation System.

Bluetooth Based Home Automation System.

Wi-Fi based Home Automation System.

Java-(Web) Based Home Automation System.

GSM based Home Automation using SMS.

Even if many varieties of home automation systems are available, current system has got a
number of limitations. Currently home automation systems are implemented with a large
amount of hardware. The installation and maintenance of the current system is a difficult
task. It also imposes a huge installation cost on the user or consumer. Current home
automation systems are inefficient in security. In IR (Infrared) remote based Home
automation required line of sight communication. RF (Radio Frequency) based home
automation required high power consumption. They are also very poor in bandwidth
utilization. They may either leave a large amount of bandwidth or it will be very less. In
case of Zigbee the bandwidth is too low and in case of GSM it is too high. The java web
based home automation is very poor in security as the uses web pages to access and control
the appliances. Bluetooth have limited communication range. MS based and GSM based
home automation is costly for the consumer as it becomes expensive to communicate via
SMS. The varieties of home automation system improves the quality of the residents life
by facilitating a flexible, comfortable, healthy
safe environment.

Table 1 Comparison of different Communication technology


General
Purpose

Bl
ue
Wi to
-Fi ot
h

Telecommunication
devices
(routers)
High-definition
multimedia solutions
Remote control for
home automation

Low-Power

ZZig W
Be US AN W
av
e B T
e

Lo
wP
AN
DA
SH
7

Closeprox.

Entertainment

Tr
an
sfe
rJe
t

6
NF
C

W
HD
I

Wi
HD

Wi
Gi
g

Home
Automation

eHealth

Lo
n
W
or
ks

Ru
Be X1
e
0

En
Oc
KN ea
n
X

Se
nsi
u
m

Za
rli
nk

Scenarios
Connectivity of
medical devices
Wireless Sensor
Networks (WSN)
Embedded systems
Smart-energy based
systems
IP-connectivity

supported solutions
Point-to-Point (P2P)
Topology

Mesh
Star (master-slave)

Several meters

Several centimeters
Cover
range

Up to 100m

More than 100m

Several b/s

Several kb/s

Up to 250kb/s
Maximum
data rate

Several Mb/s

Power

More than 1Gb/s

Up to 450Mb/s

Ultra-low-power
consumption
Low-power
consumption
Standard power
consumption
120130kHz

13.56MHz

433MHz

RF band

868915MHz
2.4GHz

More than 2.4GHz


Alliance, Special
Interest Group (SIG)
Entities,
bodies

Standard (IEEE, ISO,


IETF)
Proprietary

10

2.2 Market Survey

The U.S. Market for Home Automation and Security Technologies

REPORT HIGHLIGHTS

The U.S. market for home automation systems and devices was worth
approximately $3.2 billion in 2010. It is expected to grow to almost $3.4 billion in
2011. In the longer term (i.e., 2011 to 2016), the forecast is for strong renewed
growth in the home automation market, which is expected to exceed $5.5 billion in
2016, a CAGR of 10.5% between 2011 and 2016.

Lighting, home entertainment, and security systems accounted for nearly 58% of
the U.S. home automation market in 2010. It is estimated to be around $2.1 billion
in the year and further to reach $3.8 billion by 2016 at a CAGR of 12.2 %.

Heating, ventilation, and air conditioning (HVAC) and energy management made
up for the remaining 42% of the U.S. market. It is expected to reach $1.7 billion by
2016 at a CAGR of 7.4% between 2011 and 2016.

Figure 1 BBC Research

11

Product name: Wireless Color Video Door Monitor with Intercom System
Price: $199.95/ each

Figure 2 Wireless Color Video Door Monitor with Intercom System

PRODUCT OVERVIEW

Model # VD-8810
Internet # 202278744

The IQ America Wireless Color Video Door Monitor with Intercom System puts effortless
audio/video monitoring of your home or business entry at your fingertips. Wireless
installation means it can be installed in less than 30 minutes. Kit includes a wireless
12

doorbell/camera with a satin nickel finish that mounts near the front door and a portable
color LCD receiver unit with charging cradle. When a visitor signals their arrival by
pressing the remote station's doorbell push button, a color video appears on the master
station interior LCD monitor along with a doorbell ring. A two-way conversation can be
initiated by the internal LCD monitor if desired. The LCD monitors stores images of
visitors so you'll know who visited even when you are away. The doorbell camera unit can
be used without batteries by connecting it directly to an existing 16Volt wired doorbell
supply or 16-Volt external power pack (not supplied). The Live Browsing function allows
you to monitor the view from the doorbell camera on the LCD display at any time when the
doorbell camera unit is powered by a 16-Volt wired doorbell supply or 16Volt external
power pack.

Wireless range of up to 328 ft.

1 master station and 1 remote station work together on 1 channel

Stores color images of visitors so you will know who visited while you're away

Remote station doorbell function

2.4 MHz frequency for enhanced privacy

Uses 6 AA alkaline batteries (included)

The Live Browsing feature is disabled when the doorbell camera unit is powered by
batteries

2-Year warranty

13

Crestron Green Light Power Pack

Figure 3 Crestron Green Light Power Pack

Description:

The Crestron Green Light


Power Pack (GLPP) family delivers affordable room lighting control with the essential
features for reducing energy usage. Available with up to three channels of switching or 010V dimming, each GLPP model includes inputs for a photo sensor and occupancy sensor
to control lighting levels automatically based on the amount of natural light and the
presence of people in a space, offering a cost-effective and powerful lighting-control
solution for classrooms, small offices, and open-plan offices.
Ideal for new construction as well as retrofitting existing buildings, GLPPs are designed to
install and commission quickly and without hassle. Additionally, the GLPP can be
connected to a central control system, enabling it to become an integral part of the building
energy management system. The dimming models also include built-in power monitoring
to track energy usage in real time, providing accurate metrics to assess real power savings.
When installed as a standalone lighting system, the GLPP can be easily commissioned via
14

an optional, wireless IR remote (the GLPPA-REMOTE-PROG).


Works in 120-277VAC systems
Ideal for new construction or retrofits
Quick and easy commissioning via optional handheld remote (GLPPA-REMOTEPROG)
Wired or wireless link to central Crestron system
1, 2, and 3-channel models available
Switched and 0-10V dimming models available
Integrates with occupancy sensor and photo sensor
Supports up to three remote keypads
Easy keypad wiring using existing switch-loop wiring
Optional handheld remote for daily use (GLPPA-REMOTE-USER)
Real-time energy monitoring on select models
Adaptive zero-cross switching for extended life
Seamless integration with Crestron AV systems
CEC Title 24 2013 Compliant

15

ML-600 MiniLCD is a handheld wireless

Figure 4 ML-600

The ML-600 MiniLCD is a handheld wireless remote that features a customizable LCD
display, a 5-way thumb pad controller, and an intuitive array of pushbuttons designated for
a variety of common AV functions. But, Crestron designed the ML-600 to go beyond
conventional home theater and AV system control, extending domain over lighting, climate,
security, and more as part of a complete Crestron system. Its compact size and ergonomic
design offer easy one-handed operation

Ergonomic handheld design

Large programmable LCD screen flanked by 10 menu buttons

3 LCD menu navigation buttons

27 programmable function buttons

2 programmable power buttons

5-way thumb pad for OSM navigation

EL backlighting of LCD screen and buttons

1-way RF(433MHz) or IR wireless communication[1]

Operates on 4 AAA alkaline batteries

16

3. HOME AUTOMATION SYSTEM

In this chapter, we are going to explain detailed block diagram with entire process and
signal.
3.1

Block Diagram

Figure 5 Block Diagram of Home Automation System

17

Figure 6 Structural Block Diagram


It is proposed to control various home appliances like Tube light, Fan, Bulb using
android application in tablet or any other android platform based handheld device. This
whole system will be controlled by Raspberry pi. For wireless connection It is proposed to
use USB WiFi Adapter which is connected with raspberry pi and Tablet with WiFi(IEEE
802.11 protocol) connection.
One will able to select appliances from the application, as command will be given
to the raspberry pi. According to that command Raspberry pi will give signal to relay
switching circuit to turn on/off particular Electrical appliance. In monitoring system, there
is one camera out side the main door which can be accessed from the tablet, using android
application. It is proposed to control to open the door; also Raspberry pi is having a socket
through which one can connect camera.
It is thought of adding facility to turn ON or OFF water pump from remote location with
the help of GSM modem, interfacing with raspberry pi. Analog controls offering to
appliances like fan, as achieve speed control.

18

4. RASPBERRY PI
The Raspberry Pi is a credit card-sized single-board computer developed in
the UK by the Raspberry Pi Foundation with the intention of promoting the teaching of
basic computer science in schools.
The Raspberry Pi is manufactured in three board configurations through
licensed manufacturing agreements with Newark element14 (Premier Farnell), RS
Components and Egoman. These companies sell the Raspberry Pi online. Egoman produces
a version for distribution solely in China and Taiwan, which can be distinguished from
other Pis by their red coloring and lack of FCC/CE marks. The hardware is the same across
all manufacturers.
In 2014, the Raspberry Pi Foundation launched the Compute Module, which
packages a Raspberry Pi Model B into module for use as a part of embedded systems, to
encourage their use.
The Raspberry Pi is based on the Broadcom BCM2835 system on a chip
(SoC), which includes an ARM1176JZF-S 700 MHz processor, VideoCore IV GPU, and
was originally shipped with 256 megabytes of RAM, later upgraded (Model B & Model
B+) to 512 MB. The system has Secure Digital (SD) or MicroSD (Model B+) sockets for
boot media and persistent storage.
The Foundation provides Debian and Arch Linux ARM distributions for
download. Tools are available for Python as the main programming language, with support
for BBC BASIC (via the RISC OS image or the Brandy Basic clone for Linux), C, C++,
Java, Perl and Ruby.

19

4.1 Specification of Raspberry pi


Table 2 Specification of R-Pi
Broadcom BCM2835 CPU,GPU,DSP,SDRAM and
System On Chip (SOC)

single USB port)

CPU

700 MHz ARM1176JZF-S core (ARM11 Family)

GPU

Broadcom Videocore IV @250 MHz

Memory

512 MB

USB port

2, 2.0 Version

Cost

$35

Video input

A CSI input connector allows for the connectin of a


RPF designed camera module.

Video Output

PAL, NTSC, HDMI

Audio Output

Black 3.5 mm Jack

Card support

SD, MMC, SDIO (3.3V power only)

Onboard network

10/100 Ethernet(8P8C) USB adapter on the third port


of the USB hub

Power Ratings

300 mA(1.5 W)

Size

85.60 mm X 53.98 cm

Weight

45 gm

20

Figure 7 Components of Raspberry Pi


4.2 GPIO
One of the most exciting features of the Raspberry Pi is the presence of the GPIO
pins, which makes it possible to connect the Pi to some custom hardware which could
otherwise not be able to communicate with it on standard ports. They are basically some
general purpose pins, which one can control from software arbitrarily. They can be used as
input, to read information from other devices, such as sensors or they can be used as output
to send signals to external hardware, such as LEDs, motors, speakers, etc. Some of the
GPIO pins also have dedicated functions, allowing the Raspberry Pi to communicate with
other hardware through some standard protocols.
In order to be able to connect to the GPIO pins of the Raspberry Pi, one must need
to clarify where those pins are exactly. One will also have to find a way to unambiguously
identify the pins, so assign numbers to them and refer to them using these numbers. Both
(A and B) original models have a total of 26 GPIO pins, organized into one pin header,
named the P1 header. The newer Raspberry Pi (model B) adds 8 more GPIO pins in a new
pin header called P5, but they are not the same male pins sticking out of the board that we
can find on the P1 header, instead they are some little rings to which one can solder wires,
so they target more advanced users, with more serious hardware and soldering skills.

21

Figure 8 P5 Header

Table 3 P1 Header
3.3 V

5V

12 CO SDA

DNC

12 CO SCL

GROUND

GPIO4

UART TXD

DNC

10

UART RXD

GPIO 17

11

12

GPIO 18

GPIO 21

13

14

DNC

GPIO 22

15

16

GPIO 23

DNC

17

18

GPIO 24

SP10 MOSI

19

20

DNC

SP10 MISO

21

22

GPIO 25

SP10 SCLK

23

24

SP10 CEO N

DNC

25

26

SP10 CE1 N
22

4.3 Basic Requirement of raspberry pi

SD Card
o

We recommend an 8GB class 4 SD card ideally preinstalled with NOOBS.


You can buy a card with NOOBS pre-installed, or you can download it for
free from our downloads page.

Display and connectivity cables


o

Any HDMI/DVI monitor or TV should work as a display for the Pi . For


best results, use one with HDMI input, but other connections are available
for older devices. Use a standard Ethernet cable for internet access.

Keyboard and mouse


o

Any standard USB keyboard and mouse will work with your Raspberry Pi.

Power supply
o

Use a 5V micro USB power supply to power your Raspberry Pi. Be careful
that whatever power supply you use outputs at least 5V; insufficient power
will cause your Pi to behave in strange ways.

Not essential but helpful to have

Internet connection
o

To update or download software, we recommend that you connect your


Raspberry Pi to the internet either via and ethernet cable or a wifi adapter.

Headphones
o

Headphones or earphones with a 3.5mm jack will work with your Raspberry
Pi.

4.4 LINUX OSs for Raspberry Pi


There are several OS available to install on Raspberry Pi. Some are given as follow:
1.

Raspbian.

2.

OpenELEC.

3.

RISC OS.
23

4.

RaspBMC.

5.

Arch.

4.5 Introducing Raspbian


Raspbian is a free OS based on Debian optimized for the Raspberry Pi hardware. An os
is the best of basic programs and utilities that make your raspberry pi run. However
raspbian provides more than a pure os: it comes with over 35000 packages, precompiled software bundled in a nice format for easy installation on your raspberry pi.
The initial build of over 35000 raspbian packages, optimized for best performance on
the Raspberry Pi was completed in june of 2012. However, raspbian still under active
development with an emphasis on improving the stability and performance of as many
debian packages as possible.
4.6 Flashing OS in the SD Card

Raspbian is available for free from the Raspberry Pi website. Under the header
Raspbian wheezy, download either the torrent or direct download. The torrent
has the potential to be faster, but some firewalls may block the required ports and
you may have to use the direct download instead.

Once you have the ZIP file downloaded to your computer, unarchive it. There will
be a single .img file inside. This is the disk image you will flash to the Raspberry
Pis SD card. To install Raspbian, you will need an SD card that has 2 GB of space
or more this cheap 16 GB Class 10 SD card works great on the Raspberry Pi, and
gives you plenty of room to add media and other programs once Raspbian is
installed.

The recommended method for flashing an SD for use in a Raspberry Pi is a program


called Win32DiskImager. The latest version can be found on the official website.
Personally I recommend version 0.5, since the latest version (0.6) has a bug that
may cause your entire hard drive to be flashed instead of the SD card.

Once youve downloaded the Win32DiskImager application and extracted the ZIP
file, download the Raspbian distribution. This can be found on the Raspberry Pi
website under the heading Raspbian wheezy. Once the ZIP file downloads,
extract the .img from the .zip.
24

In Win32DiskImager, ensure you select the correct drive letter for your SD card. In
my case, the SD card was drive F:/. Yours may be different, so check in Windows
Explorer to make sure you have the correct letter. Do not choose C:\, since that is
your main hard drive.

Also, select the .img file you extracted from the Raspbian distribution above using
the file picker. Once you have made sure you have the correct .img file and drive
letter for your SD card, click Write (not read) to flash the SD card. This will take
less than five minutes on average and you can see the current progress in the
Win32DiskImager window. Once the flash completes, you can exit the program.

4.7 Setting Up Raspberry Pi


Once youve flashed the disk image using the methods above, place the SD card into your
Raspberry Pi, plug in the HDMI monitor, any keyboards and mice, and then the power
cable. Your Raspberry Pi should begin to boot and you should be able to see Raspbian on
your screen.
Complete the Raspbian setup, and your Raspberry Pi is now ready to be used!

4.8 Plugging in your Raspberry Pi


Before you plug anything into your Raspberry Pi, make sure that you have all the
equipment listed above to hand. Then follow these instructions:
1. Begin by slotting your SD card into the SD card slot on the Raspberry Pi, which
will only fit one way.
2. Next, plug in your USB keyboard and Mouse into the USB slots on the Raspberry
Pi.
3. Make sure that your monitor or TV is turned on, and that you have selected the right
input (e.g. HDMI 1, DVI, etc)
4. Then connect your HDMI cable from your Raspberry Pi to your monitor or TV.
25

5. If you intend to connect your Raspberry Pi to the internet, plug in an ethernet cable
into the ethernet port next to the USB ports, otherwise skip this step.
6. When you are happy that you have plugged in all the cables and SD card required,
finally plug in the micro usb power supply. This action will turn on and boot your
Raspberry Pi.
4.9 Logging into your Raspberry Pi
1. Once your Raspberry Pi has completed the boot process, a login prompt will
appear. The

default

login

for

Raspbian

is

username pi with

the

password raspberry. Note you will not see any writing appear when you type the
password. This is a security feature in Linux.
2. After you have successfully logged in, you will see the command line prompt
pi@raspberrypi~$
3. To load the graphical user interface, type startx and press Enter on your keyboard.
4.10 Update the System Software
To update the system software, first connect the Raspberry PI to the Internet through an
Ethernet cable. At the command prompt enter the following:
sudo apt-get update
Now enter:
sudo apt-get upgrade
You can enter this command from the main command prompt after logging in or from a
terminal window when running the graphical desktop (LXTerminal icon on the desktop).
between the Pi and a switch. One can connect either router or hub.

4.11 Configure the Network


However the Raspberry Pi is cleverer than that. The RJ45 port on the side of the Pi includes
a feature known as auto-MDI, which allows it to reconfigure itself automatically. As a
26

result, one can use any RJ45 cable to connect the R-Pi to the network, and it will adjust its
configuration accordingly. If one do connect the R-Pi directly to a PC or laptop, one wont
be able to connect out onto the Internet by default. To do so, one need to configure PC to
bridge the wired Ethernet port and another (typically wireless) connection. One will
completely unable to connect the R-Pi to the Internet in any other way; one can try
searching operating systems help file for bridge network to find more guidance. With a
cable connected, the R-Pi will automatically receive the details it needs to access the
Internet when it loads its operating system through the Dynamic Host Configuration
Protocol (DHCP). This assigns the R-Pi an Internet Protocol (IP) address on network, and
tells it the gateway it needs to use to access the Internet (typically the IP address of router
or modem).
Steps: (Setting the static IP address on Raspberry PI)
1. Open command window in windows.

Figure 9 IP Address in Command window

27

Write IP address, Subnet Mask and Default.


Now install Raspberry pi OS in SD card and run it on Raspberry Pi. Connect RJ45

Ethernet Cable.

Figure 10 LX Terminal Of Raspberry pi

Open LX terminal in Raspberry OS. Write command as follow:

1) ifconfig
2) cat /etc/network/interfaces
3) ssdo cp /etc/network/interfaces /etc/network/interfaces.backup
4) sudo nano /etc/network/interfaces now, new window will open. write static in place of
dhcp in second line. set you address, netmask and default gateway on
hat.OpenMidori (internet browser).
5) Raspberry Pi is ready to use internet connection.

28

5. ANDROID
5.1 Introduction to Android
Overview
Android is an open source and Linux-based Operating System for mobile devices such as
smartphones and tablet computers. Android was developed by the Open Handset Alliance,
led by Google, and other companies. Android offers a unified approach to application
development for mobile devices which means developers need only develop for Android,
and their applications should be able to run on different devices powered by android.

5.2 Features of Android


Android is a powerful operating system competing with Apple 4GS and supports great
features. Few of them are listed below:
Feature

Description

Beautiful UI

Android OS basic screen provides a beautiful and intuitive user interface.

Connectivity

GSM/EDGE, IDEN, CDMA, EV-DO, UMTS, Bluetooth, Wi-Fi, LTE,


NFC and WiMAX.

Storage
Media support

SQLite, a lightweight relational database, is used for data storage


purposes.
H.263, H.264, MPEG-4 SP, AMR, AMR-WB, AAC, HE-AAC, AAC 5.1,
MP3, MIDI, Ogg Vorbis, WAV, JPEG, PNG, GIF, and BMP

Messaging

SMS and MMS

Web browser

Based on the open-source WebKit layout engine, coupled with Chrome's


V8 JavaScript engine supporting HTML5 and CSS3.

29

Multi-touch

Android has native support for multi-touch which was initially made
available in handsets such as the HTC Hero.

Multi-tasking

User can jump from one task to another and same time various application
can run simultaneously.

Resizable
widgets

Widgets are resizable, so users can expand them to show more content or
shrink them to save space

MultiLanguage

Supports single direction and bi-directional text.

GCM

Wi-Fi Direct

Android Beam

Google Cloud Messaging (GCM) is a service that lets developers send


short message data to their users on Android devices, without needing a
proprietary sync solution.
A technology that lets apps discover and pair directly, over a highbandwidth peer-to-peer connection.

A popular NFC-based technology that lets users instantly share, just by


touching two NFCenabled phones together.

5.3 Environment Setup


Step 1 - Setup Java Development it (JDK)
For Windows, installed the JDK in C:\jdk1.6.0_15, you would have to put the following
line in your C:\autoexec.bat file.
set
PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15
Alternatively, you could also rightclick on My Computer, select
30

Properties, then Advanced,


thenEnvironment Variables. Then,
you would update the PATH value
and press the OK button.
Step 2 - Setup Android SDK
launch Android SDK Tool Setup wizard to guide you throughout of the installation, so just
follow the nstructions carefully.
So let's launch Android SDK Manager using the option All Programs > Android SDK
Tools > SDK Manager, this will give you following window:

Figure 11 Installing Packages

31

Once you launched SDK manager, its time to install other required packages. By default
it will list down total 7 packages to be installed, but I will suggest to de-select
Documentation for Android SDK andSamples for SDK packages to reduce installation
time. Next click Install 7 Packages button to proceed, which will display following
dialogue box:

Figure 12 Choose Packages

If you agree to install all the packages, select Accept All radio button and proceed by
clicking Installbutton.
Step 3 - Setup Eclipse IDE
Eclipse can be started by executing the following commands on windows machine, or you
can simply double click on eclipse.exe
%C:\eclipse\eclipse.exe
32

Eclipse can be started by executing the following commands on Linux machine:


$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display following result:

Figure 13 Eclipse Window

Step 4 - Setup Android Development Tools (ADT) Plugin


Help > Software Updates > Install New Software
Now

use

Add

button

to

add

ADT

Plugin

as

name

and

https://dl-

ssl.google.com/android/eclipse/ as the location. Then click OK to add this location, as


soon as you will click OK button to add this location, Eclipse starts searching for the
plug-in available the given location and finally lists down the found plugins.

33

Figure 14 Install ADT

Now select all the listed plug-ins using Select All button and click Next button which will
guide you ahead to install Android Development Tools and other required plugins.
Step 5 - Create Android Virtual Device
Window > AVD Manager> which will launch Android AVD Manager. Use New button
to create a new Android Virtual Device and enter the following information, before
clicking Create AVD button.

If your AVD is created successfully it means your environment is ready for Android
application development. If you like, you can close this window using top-right cross
button. Better you re-start your machine and once you are done with this last step, you
are ready to proceed for your first Android example but before that we will see few more
important concepts related to Android Application Development.

34

5.4 Architecture
Android operating system is a stack of software components which is roughly divided into
five sections and four main layers as shown below in the architecture diagram.

Figure 15 Architecture of Android


Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches. This
provides basic system functionality like process management, memory management,
device management like camera, keypad, display etc. Also, the kernel handles all the
things that Linux is really good at such as networking and a vast array of device drivers,
which take the pain out of interfacing to peripheral hardware.

35

Libraries
On top of Linux kernel there is a set of libraries including open-source Web browser engine
WebKit, well known library libc, SQLite database which is a useful repository for storage
and sharing of application data, libraries to play and record audio and video, SSL libraries
responsible for Internet security etc.

Android Runtime
This is the third section of the architecture and available on the second layer from the
bottom. This section provides a key component called Dalvik Virtual Machine which is a
kind of Java Virtual Machine specially designed and optimized for Android.
The Dalvik VM makes use of Linux core features like memory management and multithreading, which is intrinsic in the Java language. The Dalvik VM enables every Android
application to run in its own process, with its own instance of the Dalvik virtual machine.
The Android runtime also provides a set of core libraries which enable Android application
developers to write Android applications using standard Java programming language.
Application Framework
The Application Framework layer provides many higher-level services to applications in
the form of Java classes. Application developers are allowed to make use of these services
in their applications.
Applications
You will find all the Android application at the top layer. You will write your application to
be installed on this layer only. Examples of such applications are Contacts Books, Browser,
Games etc.

36

Application Components
Application components are the essential building blocks of an Android application. These
components
are loosely coupled by the application manifest file AndroidManifest.xml that describes
each component of the application and how they interact.

There are following four main components that can be used within an Android application:

Components

Description

Activities

They they dictate the UI and handle the user interaction to the
smartphone screen

Services
Broadcast
Receivers

Content Providers

They handle background processing associated with an application.


They handle communication between Android OS and applications.

They handle data and database management issues.

Activities
An activity represents a single screen with a user interface. For example, an email
application might have one activity that shows a list of new emails, another activity to
compose an email, and another activity for reading emails. If an application has more
than one activity, then one of them should be marked as the activity that is presented
when the application is launched.

37

An activity is implemented as a subclass of Activity class as follows:


public class MainActivity extends Activity {

}
Services
A service is a component that runs in the background to perform long-running
operations. For example, a service might play music in the background while the user is
in a different application, or it might fetch data over the network without blocking user
interaction with an activity.
A service is implemented as a subclass of Service class as follows:
public class MyService extends
Service { }
Broadcast Receivers
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system. For example, applications can also initiate broadcasts to let other applications
know that some data has been downloaded to the device and is available for them to use, so
this is broadcast receiver who will intercept this communication and will initiate
appropriate action.
A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each
message is broadcasted as an Intent object.
public class MyReceiver extends BroadcastReceiver
{
}

38

Content Providers
A content provider component supplies data from one application to others on request.
Such requests are handled by the methods of the ContentResolver class. The data may be
stored in the file system, the database or somewhere else entirely.
A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform transactions.
public class MyContentProvider extends ContentProvider
{
}
We will go through these tags in detail while covering application components in individual
chapters.
Additional Components
There are additional components which will be used in the construction of above mentioned
entities, their logic, and wiring between them. These components are:
Components

Description

Fragments

Represents a behavior or a portion of user interface in an Activity.

Views

UI elements that are drawn onscreen including buttons, lists forms


etc.

Layouts
Intents

View hierarchies that control screen format and appearance of the


views.
Messages wiring components together.

39

Resources

External elements, such as strings, constants and drawables pictures.

Manifest

Configuration file for the application.

5.5 Hello World Example


Let us start actual programming with Android Framework. Before you start writing your
first example using
Android SDK.
So let us proceed to write a simple Android Application which will print "Hello World!".
Create Android Application
The first step is to create a simple Android Application using Eclipse IDE. Follow the
option File -> New -> Project and finally select Android New Application wizard from
the wizard list. Now name your application as HelloWorld using the wizard window as
follows:

40

Figure 16 New Android Wizard


Next, follow the instructions provided and keep all other entries as default till the final step.
Once your project is created successfully, you will have following project screen:

41

Figure 17 Anatomy of Android Application

42

Following section will give a brief overview few of the important application files.
The Main Activity File:

Figure 18 Package Explorer

43

The main activity code is a Java file MainActivity.java. This is the actual application file
which ultimately gets converted to a Dalvik executable and runs your application.
Following is the default code generated by the application wizard for Hello World!
application:

package com.example.helloworld;

import android.os.Bundle; import


android.app.Activity; import
android.view.Menu; import
android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);

return

true;
}
}
Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout
folder. TheonCreate() method is one of many methods that are fi red when an activity is
loaded.
44

The Manifest File


Whatever component you develop as a part of your application, you must declare all its
components in a manifest file called AndroidManifest.xml which ressides at the root of the
application project directory. This file works as an interface between Android OS and your
application, so if you do not declare your component in this file, then it will not be
considered by the OS. For example, a default manifest file will look like as following file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloworld"

android:versionCode="1"

android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"

android:theme="@style/AppTheme"

>
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
Here <application>...</application>
related to

the

tags

enclosed

the

components

application.
45

Attributeandroid:icon will point to the application icon available under res/drawable-hdpi.


The application uses the image named ic_launcher.png located in the drawable folders
The <activity> tag is used to specify an activity and android:name attribute specifies the
fully qualified class name of the Activity subclass and the android:label attributes
specifies a string to use as the label for the activity. You can specify multiple activities
using <activity> tags.
The action for the intent filter is named android.intent.action.MAIN to indicate that this
activity serves as the entry point for the application. The category for the intent-filter is
namedandroid.intent.category.LAUNCHER to indicate that the application can be
launched from the device's launcher icon.
The @string refers to the strings.xml file explained below. Hence, @string/app_name
refers to theapp_name string defined in the strings.xml fi le, which is "HelloWorld".
Similar way, other strings get populated in the application.
Following is the list of tags which you will use in your manifest file to specify different
Android application components:

<activity>elements for activities

<service> elements for services

<receiver> elements for broadcast receivers

<provider> elements for content providers


The Layout File
The activity_main.xml is a layout file available in res/layout directory, that is referenced
by your application when building its interface. You will modify this file very frequently
to change the layout of your application. For your "Hello World!" application, this file
will have following content related to default layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
46

android:layout_width="match_parent" android:layout_height="match_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"

tools:context=".MainActivity" />

</RelativeLayout>
This is an example of simple RelativeLayout which we will study in a separate chapter. The
TextView is an Android control used to build the GUI and it have various attribuites like
android:layout_width,android:layout_height etc which are being used to set its width and
height etc. The @string refers to the strings.xml file located in the res/values folder. Hence,
@string/hello_world refers to the hello string defined in the strings.xml fi le, which is
"Hello World!".
Running the Application
Let's try to run our Hello World! application we just created. I assume you had created your
AVD while doing environment setup. To run the app from Eclipse, open one of your
project's activity files and click Run

icon from the toolbar. Eclipse installs the app on

your AVD and starts it and if everything is fine with your setup and application, it will
display following Emulator window:

47

Figure 19 Hello World Application

Congratulations!!! you have developed your first Android Application and now just keep
following rest of the tutorial step by step to become a great Android Developer. All the
very best.
Activities
An activity represents a single screen with a user interface. For example, an email
application might have
one activity that shows a list of new emails, another activity to compose an email, and
another activity for reading emails. If an application has more than one activity, then
one of them should be marked as the activity that is presented when the application is
launched.
48

If you have worked with C, C++ or Java programming language then you must have
seen that your program starts from main() function. Very similar way, Android system
initiates its program with in anActivity starting with a call on onCreate() callback
method. There is a sequence of callback methods that start up an activity and a sequence
of callback methods that tear down an activity as shown in the below Activity lifecycle
diagram: (image courtesy : android.com )

Figure 20 Activity Flowchart

The Activity class defines the following callbacks i.e. events. You don't need to
implement all the callbacks methods. However, it's important that you understand each
one and implement those that ensure your app behaves the way users expect.

Callback

Description

onCreate()

This is the first callback and called when the activity is first created.

onStart()

This callback is called when the activity becomes visible to the user.

onResume()

This is called when the user starts interacting with the application.

onPause()

The paused activity does not receive user input and cannot execute any
code and called when the current activity is being paused and the
49

previous activity is being resumed.


onStop()

This callback is called when the activity is no longer visible.

onDestroy()

This callback is called before the activity is destroyed by the system.

onRestart()

This callback is called when the activity restarts after stopping it.

UILayout:
The basic building block for user interface is a View object which is created from the
View class and occupies a rectangular area on the screen and is responsible for drawing
and event handling. View is the base class for widgets, which are used to create interactive
UI components like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other
Views or other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a
typical layout defines the visual structure for an Android user interface and can be created
either at run time usingView/ViewGroup objects or you can declare your layout using
simple XML file main_layout.xml which is located in the res/layout folder of your
project.
This tutorial is more about creating your GUI based on layouts defined in XML file. A
layout may contain any type of widgets such as buttons, labels, textboxes, and so on.
Following is a simple example of XML file having LinearLayout:

50

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

android:text="This is a TextView"

<Button android:id="@+id/button"

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />

<!-- More GUI components go here -->

</LinearLayout>
Once your layout is defined, you can load the layout resource from your application code,
in yourActivity.onCreate() callback implementation as shown below:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}
5.6 Android Layout Types
There are number of Layouts provided by Android which you will use in almost all the
Android applications to provide different view, look and feel.

51

S.N. Layout & Description


Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or
horizontally.
1

Relative Layout
RelativeLayout is a view group that displays child views in relative positions.

Table Layout
TableLayout is a view that groups views into rows and columns.
Absolute Layout

AbsoluteLayout enables you to specify the exact location of its children.


Frame Layout

The FrameLayout is a placeholder on screen that you can use to display a single view.

List View
ListView is a view group that displays a list of scrollable items.

Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

Linear Layout
Android LinearLayout is a view group that aligns all children in a single direction,
vertically orhorizontally.
52

UI Controls
An Android application user interface is everything that the user can see and interact with.
You have
learned about the various layouts that you can use to position your views in an activity.
This chapter will give you detail on various views.
A View is an object that draws something on the screen that the user can interact with and
aViewGroup is an object that holds other View (and ViewGroup) objects in order to define
the layout of the user interface.
You define your layout in an XML file which offers a human-readable structure for the
layout, similar to HTML. For example, a simple vertical layout with a text view and a
button looks like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />

<Button

android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />
</LinearLayout>

Android UI Controls
There are number of UI controls provided by Android that allow you to build the graphical
user interface for your app.
53

S.N. UI Control & Description

TextView
This control is used to display text to the user.

EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.
AutoCompleteTextView

The AutoCompleteTextView is a view that is similar to EditText, except that it shows


a list of completion
suggestions automatically while the user is typing.

Button
A push-button that can be pressed, or clicked, by the user to perform an action.

ImageButton
AbsoluteLayout enables you to specify the exact location of its children.

CheckBox
6

An on/off switch that can be toggled by the user. You should use checkboxes when
presenting users with a group of selectable options that are not mutually exclusive.
ToggleButton
An on/off button with a light indicator.

54

RadioButton

The RadioButton has two states: either checked or unchecked.

RadioGroup

A RadioGroup is used to group together one or more RadioButtons.


ProgressBar

10

The ProgressBar view provides visual feedback about some ongoing tasks, such as
when you are performing a task in the background.

11

Spinner
A drop-down list that allows users to select one value from a set.

TimePicker
12

The TimePicker view enables users to select a time of the day, in either 24-hour
mode or AM/PM mode.
DatePicker

13

The DatePicker view enables users to select a date of the day.

Event Handling
Events are a useful way to collect data about a user's interaction with interactive
components of your app,
like button presses or screen touch etc. The Android framework maintains an event
queue into which events are placed as they occur and then each event is removed from

55

the queue on a first-in, first-out (FIFO) basis. You can capture these events in your
program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management:

Event Listeners: The View class is mainly involved in building up a Android GUI, same
View class provides a number of Event Listeners. The Event Listener is the object that
receives notification when an event happens.

Event Listeners Registration: Event Registration is the process by which an Event Handler
gets registered with an Event Listener so that the handler is called when the Event Listener
fires the event.

Event Handlers: When an event happens and we have registered and event listener fo the
event, the event listener calls the Event Handlers, which is the method that actually handles
the event.
Event Listeners & Event Handlers
Event Handler

Event Listener & Description


OnClickListener()

onClick()

This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. You will use onClick() event
handler to handle such event.
OnLongClickListener()

onLongClick()

This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. for one or more seconds. You
will use onLongClick() event handler to handle such event.

56

OnFocusChangeListener()
onFocusChange()

This is called when the widget looses its focus ie. user goes away
from the view item. You will use onFocusChange() event handler to
handle such event.
OnFocusChangeListener()

onKey()

This is called when the user is focused on the item and presses or
releases a hardware key on the device. You will use onKey() event
handler to handle such event.

OnTouchListener()
onTouch()

This is called when the user presses the key, releases the key, or any
movement gesture on the screen. You will use onTouch() event
handler to handle such event.
OnMenuItemClickListener()

onMenuItemClick() This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.

57

6. TCP/IP
6.1 Introduction

TCP stands for Transmission Control Protocol.


TCP is a reliable, connection-oriented protocol that transmits data as a stream of
bytes.
Although TCP can be implemented to work over any transport protocol, it's usually
synonymous with IP. TCP is a connection-oriented stream protocol (like a telephone call).
TCP communication happens using a handshake process, where each data that is sent is
acknowledge by the recipient within the time of TCPs timer value. TCP provides many
services such as data reliability, error checking, and flow control. If a data packet is corrupt
or lost (not acknowledged), TCP will retransmitted the data from the client side
automatically. Because the route a packet takes can be many, one packet may arrive before
the one sent earlier. As data packets arrive, it is the job of TCP to assemble the packets into
the proper order. This is shown below with a factious network topology layout, where the
data packet takes (n) number of hops to get from the source to the destination. On a bigger
network like the Internet, there are many routes a data packet can take to arrive at its final
destination.
6.2 Networks
Most network applications can be divided into two pieces: a client and a server. A client is
the side that initiates the communication process, whereas the server responds to incoming
client requests.

Figure 21 Communication link


58

6.3 IPv4 Internet Protocol


The current version for IP supported by many modern networks is version 4, the next
generation of IP is version 6 (IPv6) which is not widely supported as of this writing. IP is
both a network addressing protocol and a network transport protocol. IP is a connectionless
protocol that provides unreliable service for data communication. Most of the properties of
data communication such as transmission reliability, flow control and error checking are
provided by TCP which we will look at shortly.
Most people know IP in its basic form as a quad dotted-numerical string, such
as192.168.1.1. Each integer value separated by a dot can have a value from 0 to 255
(8bits). Thus IPv4 is a 32 bit unsigned integer values.

Figure 22 IP Address Format

6.4 Socket Programming For TCP Server & Client

6.4.1 Steps involved in TCP connection


Transport protocol. IP is a connectionless protocol that provides unreliable service for data
communication. Most of the properties of data communication such as transmission
reliability, flow control and error checking are provided by TCP which we will look at
shortly.

59

Most people know IP in its basic form as a quad dotted-numerical string, such
as192.168.1.1. Each integer value separated by a dot can have a value from 0 to 255
(8bits). Thus IPv4 is a 32 bit unsigned integer values.

6.5 Socket Programming For TCP Server & Client


6.5.1 Steps involved in TCP connection

Creating a socket.

Binding the socket to a well-known address

Creating a connection listening queue

Connecting to a server

Accepting incoming connections

Reading and Writing data

60

Closing the socket

Figure 23 Flow chart of TCP

61

7.0 WORK DONE

Work Plan / Schedule

Month

Hardware

Software

July

Project survey, Linux OS

Basic JAVA

August

Paper Work for Raspberry Pi

Android Basic

September Interfacing Raspberry

Pi with Android Layout coding

GPIO
October

Interfacing Raspberry Pi with Wi-Fi Android With Wi-Fi connection


Dongle

November

Interfacing

GPIO

and

Android Android

(Using Wi-Fi)

With

Raspberry

Pi

Though Wi-Fi

December
January

Interfacing

Raspberry

Pi

with Android Image file Handling

camera
February

coding

Interfacing Raspberry Pi with Water Android page for water level


Sensor Circuit

control

Web server on apache with PHP

Android website coding with


Internet permissible.

March

Switch board and Relay circuit

April

Implementing

All

Modules Finalize the Apps.

together
62

7.1 Raspberry pi GPIO


Basic GPIO
The R-Pi has 17 GPIO pins brought out onto the header, most have alternated functions
other than just I/O, there are two pins for UART, two for I2C and six for SPI. All the pins
can be use for GPIO with either INPUT or OUTPUT, there also internal pull-up & pulldowns for each pin but the I2C pins have and onboard pull-up so using them for GPIO may
not work in some cases.
These pins are 3V3 not 5V like the AVR chips, and they a directly connected to the
Broadcom chip at the heart of the R-Pi. This means there is not protection, if you send 5V
down a pin there is a good chance of killing the Pi.

There will also be an issue with trying to draw to much power form the pins, according to
the data-sheet each pin programmed to current drive between 2mA and 16mA, and it has
been warned that trying to draw 16mA from several pins at once could also lead to a
damaged Pi. Also from the wiki the "maximum permitted current draw from the 3v3 pin is
50mA" and the "maximum permitted current draw from the 5v pin is the USB input current
(usually 1A) minus any current draw from the rest of the board." The current draw for
Model B is stated as 700mA so with a 1A power supply this leaves about 300mA to play
with.

63

Figure 24 Pin diagram of GPIO

Installing RPi.GPIO
RPi.GPIO is a small python library that take some of the complexity out of driving the
GPIO pins, once install a single LED can be lit with 3 lines of python. Installing the library
is almost as simple, either at a text console or using LXTerminal enter the following:
$ wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.1.0.tar.gz
$ tar zxf RPi.GPIO-0.1.0.tar.gz
$ cd RPi.GPIO-0.1.0
$ sudo python setup.py install

To run
To run the python code open LXT Teminal,open folder that contain python code file Pro
Open Leafpad text editor and save your program as prog1.py.Now to execute this
program use command line:
$ cd blink
64

$ sudo python blink.py

Figure 25 Run Python File

Digital Input-output Control:


Experiment 1: Blinking Led thought raspberry pi
Schematic

Figure 26 Schematic Interfacing LED

65

Figure 27 Interfacing LED on Bread Board

Code:
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
while 1:
GPIO.output(13, False)
sleep(1)
GPIO.output(13, True)
sleep(2)
GPIO.output(15, False)
sleep(1)
GPIO.output(15, True)
sleep(2)
GPIO.output(16, False)
sleep(1)
GPIO.output(16, True)
sleep(2)
GPIO.output(18, False)
sleep(1)
GPIO.output(18, True)
sleep(2)

66

Output

Figure 28 Output snap of Blinking LEDs


Experiment 2: To control Led by pressing the switch.
Schematic:

Figure 29 Interfacing of LEDs and Switch

67

Code:
from time import sleep
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN)
GPIO.setup(13, GPIO.OUT)
while 1:
if GPIO.input(11):
GPIO.output(13, False)
GPIO.output(15, False)
else:
GPIO.output(13, True)
GPIO.output(15, True)
if GPIO.input(12):
GPIO.output(16, False)
GPIO.output(18, False)
else:
GPIO.output(16, True)
GPIO.output(18, True)
Output:

Figure 30 Output of LEDs with Switch


68

7.2 Android Application


The android application for Home automation schematic layout is shown in figure.

Figure 31 Android Application


The first page is the Starting page which will see for few second. The second page is Home
page. It contains three Option button Home Appliance, Water control and Door Monitoring
Home Appliance Page show the four Load ON/OFF Button. By pressing these button the
four LEDs can control by TCP communication.

69

Flow Chart of Android Application:

7.3 PC to PC communication using TCP


Output:

Figure 32 Client and Server Java Application

70

7.4 PC to Raspberry Pi communication using TCP


Output:

Figure 33 Output on raspberry Pi


7.5 PC to Android Phone communication using TCP
Output:

Figure 34 PC to Android Phone communication


71

7.6 Raspberry pi GPIO from Android Application Using TCP


Circuit Schematic:

Figure 35 Schematic of interfacing LEDs

Raspberry Pi Server Python Code:


72

from time import sleep


import RPi.GPIO as GPIO
import socket
#GPIO Setup
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.output(11, True)
GPIO.output(12, True)
GPIO.output(13, True)
GPIO.output(15, True)
#TCP Setup
TCP_IP = ''
TCP_PORT = 5000
BUFFER_SIZE = 4096
# Create socket and bind it to TCP address &amp; port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print 'connect by', addr
while True:
Rec_data = conn.recv(BUFFER_SIZE)
print 'Recived',Rec_data
if Rec_data=='NO\n':
break
if Rec_data=='1\n':
73

print'Load_1 ON'
GPIO.output(11, False)
#sleep(1)
if Rec_data=='2\n':
print'Load_1 OFF'
GPIO.output(11, True)
#sleep(2)
if Rec_data=='3\n':
print'Load_2 ON'
GPIO.output(12, False)
#sleep(1)
if Rec_data=='4\n':
print'Load_2 OFF'
GPIO.output(12, True)
#sleep(2)
if Rec_data=='5\n':
print'Load_3 ON'
GPIO.output(13, False)
#sleep(1)
if Rec_data=='6\n':
print'Load_3 OFF'
GPIO.output(13, True)
#sleep(2)
if Rec_data=='7\n':
print'Load_4 ON'
GPIO.output(15, False)
#sleep(1)
if Rec_data=='8\n':
print'Load_4 OFF'
GPIO.output(15, True)
74

#sleep(2)
conn.close()
s.close()
Output:

Figure 36 Output of Raspberry pi from Android Application

Figure 37 Output of Raspberry pi GPIO from Android Application

75

CONCLUSION
Raspberry Pi is a high quality, high performance, convenient and compact electronic device
which converts the digital HDMI video signals which are outputted from Raspberry Pi, into
an analogue signal required by the widely used VGA based computer displays still widely
used around the world. Although the applications of Raspberry Pi are also used as
Industrial Automation, Office automation etc. By using this project there are mobility in
surveillance system.

76

REFERENCE:

BBC research

http://www.engineersgarage.com/ar

http://www.bccresearch.com/mark

ticles/what-is-android-introduction

et-research/instrumentation-and-

sensors/home-automation-

in C using TCP/IP

technology-products-ias031b.html

rial/tutorials/cs556-3rd-tutorial.pdf

Electronics for you magazine may

America-Wireless-Color-Video-

2013 for raspberry pi network

Door-Monitor-with-Intercom-

settings (At page no.-90).

System-VD-8810/202278744

http://www.csd.uoc.gr/~hy556/mate

Product Website:

http://www.homedepot.com/p/IQ-

Introduction to socket programming

Socket Programming
http://devmentor.org/articles/networ

Electronics for you magazine June


2013 for Raspberry pi I/O
programming (At page no.-99).

k/Socket%20Programming(v2).pdf

Basics of Android

77

APPENDIX

Android Client code:


The Main Activity File
TCP_Client.java
package com.example.has_tcp_1;
import
import
import
import
import
import
import

java.io.BufferedWriter;
java.io.IOException;
java.io.OutputStreamWriter;
java.io.PrintWriter;
java.net.InetAddress;
java.net.Socket;
java.net.UnknownHostException;

import
import
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.content.Intent;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

public class TCP_Client extends Activity


{
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "192.168.1.102";
Button bLOAD1,bLOAD2,bLOAD3,bLOAD4,bCLOSE;
EditText t1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tcp__client);
new Thread(new ClientThread()).start();
t1 = (EditText)findViewById(R.id.editText1);
bLOAD1 = (Button)findViewById(R.id.toggleButton1);
bLOAD2 = (Button)findViewById(R.id.toggleButton2);
78

bLOAD3 = (Button)findViewById(R.id.toggleButton3);
bLOAD4 = (Button)findViewById(R.id.toggleButton4);
bCLOSE = (Button)findViewById(R.id.button1);

bLOAD1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(bLOAD1.getText().equals("ON"))
{
t1.setText("L1 ON");
try
{
String str = "1";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
t1.setText("L1 OFF");
try
{
String str = "2";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
79

catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
bLOAD2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(bLOAD2.getText().equals("ON"))
{
t1.setText("L2 ON");
try
{
String str = "3";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
80

{
t1.setText("L2 OFF");
try
{
String str = "4";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
bLOAD3.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(bLOAD3.getText().equals("ON"))
{
t1.setText("L3 ON");
try
{
String str = "5";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
81

e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
t1.setText("L3 OFF");
try
{
String str = "6";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
bLOAD4.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
if(bLOAD4.getText().equals("ON"))
{
t1.setText("L4 ON");
try
{
String str = "7";
PrintWriter out = new PrintWriter(new
82

BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
t1.setText("L4 OFF");
try
{
String str = "8";
PrintWriter out = new PrintWriter(new
BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
bCLOSE.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
83

{
try
{
String str = "NO";
PrintWriter out = new
PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}

}
});
}
class ClientThread implements Runnable
{
@Override
public void run()
{
try
{
InetAddress serverAddr =
InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
}
catch (UnknownHostException e1)
{
e1.printStackTrace();
84

}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.tcp__client, menu);
return true;
}
}

The Manifest File


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.has_tcp_1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.has_tcp_1.TCP_Client"
android:label="@string/app_name" >
85

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Layout File:

86

Activity_tcp_client.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:text="load1"
android:textSize="28sp"
android:textStyle="bold" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load1" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:text="load2"
android:textSize="28sp"
android:textStyle="bold" />
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load2" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
87

android:layout_height="32dp"
android:text="load3"
android:textSize="28sp"
android:textStyle="bold" />
<ToggleButton
android:id="@+id/toggleButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load3" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="32dp"
android:text="load4"
android:textSize="28sp"
android:textStyle="bold" />
<ToggleButton
android:id="@+id/toggleButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="load4" />
</LinearLayout>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width=" 150dp"
android:text="Close"
android:layout_gravity="center_horizontal" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</LinearLayout>

88

Das könnte Ihnen auch gefallen