Wireless Sensor Based Intrusion Detection System thesis

Published on June 2016 | Categories: Types, School Work | Downloads: 55 | Comments: 0 | Views: 704
of 63
Download PDF   Embed   Report

Final year project thesisproject title:- Wireless sensor based intrusion Detection systemDiscipline:- Electrical Computer Engineer

Comments

Content


WIRELESS SENSOR BASED INTRUSION
DETECTION SYSTEM











Project Members:
Zeeshan Anjum FA09-BCE-084
Syed Emad ud din SP10-BCE-051
Muhammad Usman SP10-BCE-015

Project Supervisor:
Engr. Muhammad Ali Faisal


DEPARTMENT OF ELECTRICAL ENGINEERING
COMSATS INSTITUTE OF INFORMATION TECHNOLOGY
ABBOTTABAD


CERTIFICATE



This is to certify that the thesis entitled “WIRELESS SENSOR BASED INTRUSION
DETECTION SYSTEM” submitted by Zeeshan Anjum, Syed Emad ud din Arshad and
Muhammad Usman is an authentic work carried out by them successfully under my supervision.
To the best of my knowledge the matter embodied in the thesis has not been submitted to any
other university/ institute for the award of any degree or diploma.







Project Supervisor:




Engr. Muhammad Ali Faisal
Asst. Professor
Department of Electrical Engineering
COMSATS Institute of Information Technology
Abbottabad


ACKNOWLEDGEMENT



In the Name of Allah, Who lets it all be

We acknowledge our teachers, professors, instructors and engineers, who imparted us with the
skills and wisdom to implement this project. We acknowledge also the friends and well-wishers
who supported us. But most of all, we dedicate this work to our parents who let us reach this
station in life.











Project Students
DECLARATION


We hereby declare that this submission is our own work and that to the best of our knowledge
and belief. It does not contain any material or a fact which to a substantial extent has been
accepted for the award of any degree of any university or any other institution except where an
acknowledgement.









Zeeshan Anjum FA09-BCE-084

Syed Emad Ud din Arshad SP10-BCE-051

Muhammad Usman SP10-BCE-015




December 2013

ABSTRACT

Security is the degree of resistance to, or protection from, harm. It applies to any vulnerable and
valuable asset, such as a person, dwelling, community, nation, or organization. Security has been
an important issue not only in our country but all around the world. To overcome security
mishaps many ideas have been developed.
The purpose of our project is to provide a prototype that is able to fulfill the requirements of an
efficient, advanced and cost effective security system for getting notified when an external
breach occurs in a specific area and the intrusion is monitored and tracked by sensors deployed
on that area.
Sensor and terminal nodes were designed and created. On sensor nodes we interfaced PIR sensor
and Ultrasonic sensor with a microcontroller and a RF module. While on sensor node a GSM
module is interfaced with a RF module, Microcontroller with computer.
The output from sensors is digitized and transmitted to the terminal where it is monitored on the
screen using Graphical User Interface that is designed in Python. For ease a text message is sent
on the cell phone of in charge of that area by a GSM module. The communication between
sensor and terminal node is wireless using XBee modules (802.15.4).












Contents
1.1 Introduction: ........................................................................................................................................ 7
1.2 Concept and Motivation: ..................................................................................................................... 9
1.3 Purpose of the project: ........................................................................................................................ 9
2.1 Wireless Sensor Network: ................................................................................................................. 10
2.2 Technical Details: ............................................................................................................................. 10
2.3 XBee (802.15.4): ............................................................................................................................... 12
3.1 DESIGN OVERVIEW:................................................................................................................. 13
Block Diagram ........................................................................................................................................ 13
3.2 Description of Block diagram: ............................................................................................................ 13
3.2.1 Sensor Node: .............................................................................................................................. 14
3.2.2 Terminal Node: .......................................................................................................................... 14
3.3 Schematic Diagram: ......................................................................................................................... 14
4.3.1 Comparison of WiFi, Bluetooth and XBee ................................................................................ 16
4.3.2 Features/Benefits ................................................................................................................................ 16
4.3.3 Performance ....................................................................................................................................... 17
4.3.4 Features .............................................................................................................................................. 17
Networking & Security ............................................................................................................................... 18
Power Requirements ................................................................................................................................... 18
4.3.4 XBee Programmer pin configuration:-....................................................................................... 19
Connecting a XBee ..................................................................................................................................... 19
Setting up XBee : ........................................................................................................................................ 19
4.3.5 Modem Configuration tab .................................................................................................................. 22
4.3.6 Range test: .................................................................................................................................. 23
High Performance RISC CPU: ........................................................................................................... 30
Extreme Low-Power Management with nanoWatt XLP™: ............................................................... 31
Special Microcontroller Features: ....................................................................................................... 31
Analog Features: ................................................................................................................................. 31
Peripheral Features: ............................................................................................................................ 32
High-Performance RISC CPU: ................................................................................................................... 33
Special Microcontroller Features: ............................................................................................................... 33
Flash Technology: ....................................................................................................................................... 34


Chapter 1
INTRODUCTION
1.1 Introduction:

A security system consists of different components that are connected to each other for their
means to make a place secure. Or there may be manpower for that purpose in form of guard.
Security systems are used to provide security in premises where they ate deployed. The
efficiency and preciseness vary with design and cost.
Security suffers different types of threats e.g. intrusion in a restricted area, bomb blasts, cyber
threats, robberies etc. The focus of our project is to minimize the intrusion impact. It is one of
the most dangerous types of security threats. In the past decade incidents of intrusion occurred in
Pakistan frequently involving attacks on Armed forces bases and Headquarters that damaged
financially and have been responsible for a lot of innocent causalities.
If we look at past the first concept to provide security was to hire security guards. With the
passage of time improvements were made. New and strong weapons were invented and used. But
as the world moved towards modern era the concept of automatic and manual security systems
was developed and people started working on it in order to reduce the man power. Gradually
systems were developed that proved to be helpful and the work on such systems is not ended
here and every day new research or a product comes into the market.
New sensors and systems are developed to tackle security threat. For example a suicide attack
can be traced and minimized by using modern security systems such as metal detectors.
Electronic security systems have helped the world in many ways. Modern security systems have
minimized the manpower and risks and improved the efficiency. They have reduced the cost in a
way that we don’t have to pay many guard’s monthly bills. A Premises can be monitored by one
guard or by a person himself by using the CCTVs or other latest techniques.
The modern security systems can be used by all the people including those who cannot afford to
hire a guard. Also modern security systems have minimized the crime rate. People buy a bullet
proof car now a days instead of carrying a convoy of guards along with them.
Even if having a security system installed could be a costly endeavor, the overall benefits far
exceed its cost. Some of the most important benefits of an alarm monitoring system are:

Protection from intruders: Probably the most important benefit is that a place is be protected
24/7. While a guard might not chase off intruders, this system certainly does. In case there is no
one in the premises, the responsible person is still notified, and he will take the proper action.
Because of this, people get the peace of mind their family, possessions and property is protected.
Another main advantage and reason of the success of modern security systems is Time
efficiency. They have reduced the time consumption. For example the checking done by man
requires more time and effort while moderns systems can perform the same task in seconds and
more efficiently. Walkthrough gates and metal detectors are very common examples of that.
Many kinds of security systems are used in today’s world depending upon the nature of threats.
Radar technology, Sonar etc is used by armed forces for defense purpose.
For commercial use many systems are available in the market. Like walkthrough gates, Metal
Detectors, Burglar alarms, Fire alarms, Smart locks, CCTVs and RFID modules etc. All used for
their specific purposes.
 CCTV:
The images collected from CCTV camera are sent to a CCTV monitor and recorded on
video tape via a VCR or as digital information via a DVR. The CCTV camera lens
determines how far and much detail the CCTV camera can see.
The CCTV camera picks up the signal from the area being monitored, and in a wired
system, the CCTV camera sends the signals through a coaxial cable to the CCTV
monitor; in wireless systems, no cable is needed, instead the CCTV camera broadcasts
the signal. Monitors can be watched by CCTV controllers


 RFID:
RFID methods utilize radio waves to accomplish this. At a simple level, RFID systems
consist of three components: an RFID tag or smart label, an RFID reader, and an antenna.
RFID tags contain an integrated circuit and an antenna, which is used to transmit data to
the RFID reader (also called an interrogator). The reader then converts the radio waves to
a more usable form of data. Information collected from the tags is then transferred
through a communications interface to a host computer system, where the data can be
stored in a database and analyzed at a later time.
 Modern Radar Systems:
In modern radar system a signal is transmitted, it bounces off an object and it is later
received by some type of receiver. Radars don't use sound as a signal. Instead they use
certain kinds of electromagnetic waves called radio waves and microwaves.
Sound is used as a signal to detect objects in devices called SONAR. Another type of
signal used that is relatively new is laser light that is used in devices called LIDAR.
An intrusion detection system is a device that monitors system activities for malicious activities
produces reports to a management station. Some systems may attempt to stop an intrusion
attempt but this is neither required nor expected of a monitoring system. Intrusion detection and
prevention systems are primarily focused on identifying possible incidents. Many systems have
been developed to stop intrusion impacts like CCTV Analog Surveillance Systems can produce
images or recordings for surveillance purposes, Digital / Megapixel IP Surveillance Systems,
Bio-Metric Time Attendance & Access Controllers.

1.2 Concept and Motivation:
Our motivation is to make a security system that detects intrusion breach anywhere in restricted
area where it is deployed and give response immediately to the concerning authorities to
neutralize that impact as soon as possible.
For this purpose we developed two types of nodes i.e.
a) Sensor nodes
b) Terminal node
Sensor node detects intrusion with help of PIR (Passive Infrared radial) sensor and Ultrasonic
sensor (Microwave Motion Sensor) and transmits the data to the terminal node. On terminal node
we interfaced a microcontroller with XBee (802.15.4) and a GSM module.
The results are displayed on the GUI that is designed on the computer.

1.3 Purpose of the project:
The purpose of our project is to introduce an efficient and cost effective security system using
modern wireless technology and sensors. The system detects intrusion breach anywhere in
restricted area where it is deployed and gives response immediately to the concerning authorities
to neutralize that impact as soon as possible. The system is wireless and is monitored from a far
distance.






Chapter 2
WIRELESS SENSOR NETWORK
2.1 Wireless Sensor Network:
A wireless sensor network consists of spatially distributed autonomous
sensors to monitor physical or environmental conditions and to pass their data through the
network to a main location. The more modern networks are bi-directional, also
enabling control of sensor activity. Today such networks are used in many industrial and
consumer applications, such as industrial process monitoring and control, machine health
monitoring, and so on.

2.2 Technical Details:
The WSN is built of "nodes". Each node is connected to one or several sensors. Each such sensor
network node has several parts:
a. Radio Transceiver with an internal antenna or connection to an external antenna,
b. Microcontroller, an electronic circuit for interfacing with the sensors and an energy
source.
The size and cost of sensor nodes is variable, depending on the complexity of the individual
sensor nodes. Size and cost constraints on sensor nodes result in corresponding constraints on
resources such as energy, memory, computational speed and communications bandwidth. The
topology of the WSNs can vary from a simple star network to an advanced multi-hop wireless
mesh network. The propagation technique between the hops of the network can
be routing or flooding.


Topologies of Wireless Sensor networks
A WSN node contains several technical components. These include the radio, battery,
microcontroller, analog circuit, and sensor interface. When using WSN radio technology, you
must make important trade-offs. In battery-powered systems, higher radio data rates and more
frequent radio use consume more power. Often three years of battery life is a requirement, so
many of the WSN systems today are based on ZigBee due to its low-power consumption.
Because battery life and power management technology are constantly evolving and because of
the available IEEE 802.11 bandwidth, Wi-Fi is an interesting technology.
The second technology consideration for WSN systems is the battery. In addition to long life
requirements, you must consider the size and weight of batteries as well as international
standards for shipping batteries and battery availability. The low cost and wide availability of
carbon zinc and alkaline batteries make them a common choice.
To extend battery life, a WSN node periodically wakes up and transmits data by powering on the
radio and then powering it back off to conserve energy. WSN radio technology must efficiently
transmit a signal and allow the system to go back to sleep with minimal power use. This means
the processor involved must also be able to wake power up, and return to sleep mode efficiently.
Microprocessor trends for WSNs include reducing power consumption while maintaining or
increasing processor speed. Much like your radio choice, the power consumption and processing
speed trade-off is a key concern when selecting a processor for WSNs. This makes the x86
architecture a difficult option for battery-powered devices.



2.3 XBee (802.15.4):

The XBee RF Module was engineered to meet IEEE 802.15.4 standards and support the unique
needs of low-cost, low-power wireless sensor networks. The module requires minimal power and
provides reliable delivery of data between devices.
It currently operates in 868 MHz band at a data rate of 20Kbps in Europe, 914MHz band at
40kbps in USA, and the 2.4GHz ISM bands Worldwide at a maximum data-rate of 250kbps. It is
used to verify whether user’s truncation is possible or not. One of the main advantages of this
XBEE communication is that it provides a noise free communication, the amount of noise added
in this type of communication is very less compared to the other wireless communications
XBee is a very important protocol and device and its further details will be discussed in coming
chapters.


Chapter 3
DESIGN OVERVIEW
3.1 DESIGN OVERVIEW:
Block Diagram

The block diagram of Wireless Sensor Based Intrusion Detection System is shown in the figure
below.








3.2 Description of Block diagram:

The whole system is divided into two sections i.e.:
 Sensor Node (Transmitting Section)
 Terminal Node (Receiving Section)
3.2.1 Sensor Node:

The sensor node consists of PIR sensor and Ultrasonic sensor. These sensors are interfaced with
a microcontroller and a XBee module for data transfer from sensor node to the terminal node.
The PIR sensor detects the motion occurred in its range and it provides a signal to the
microcontroller that switches on the Ultrasonic sensor.
The output taken from PIR sensor and Ultrasonic sensor is transmitted to the terminal node by
XBee.
3.2.2 Terminal Node:
The terminal node consists of a XBee module, GSM module with microcontroller. And it is
interfaced with the computer through serial port in order to get results on the GUI developed in
the Python.
A GSM module is interfaced with the microcontroller so that the notification is sent to the cell
phone of the responsible person in order to take proper action.
3.3 Schematic Diagram:


RA4/C1OUT/SRQ/T0CKI
6
RB4/IOC0/T5G/AN11
37
RB5/IOC1/P3A/CCP3/T3CKI/T1G/AN13
38
RB6/IOC2/PGC
39
RB7/IOC3/PGD
40
RC0/P2B/T3CKI/T3G/T1CKI/SOSCO
15
RC3/SCK1/SCL1/AN15
18
RC4/SDI1/SDA1/AN16
23
RC5/SDO1/AN17
24
RC6/TX1/CK1/AN18
25
RC7/RX1/DT1/AN19
26
RC1/P2A/CCP2/SOSCI
16
RC2/CTPLS/P1A/CCP1/T5CKI/AN14
17
RA0/C12IN0-/AN0
2
RA1/C12IN1-/AN1
3
RA3/C1IN+/AN3/VREF+
5
RA2/C2IN+/AN2/DACOUT/VREF-
4
MCLR/VPP/RE3
1
RA6/CLKO/OSC2
14
RA7/CLKI/OSC1
13
RB0/INT0/FLT0/SRI/AN12
33
RB1/INT1/C12IN3-/AN10
34
RB2/INT2/CTED1/AN8
35
RB3/CTED2/P2A/CCP2/C12IN2-/AN9
36
RA5/C2OUT/SRNQ/SS1/HLVDIN/AN4
7
RD0/SCK2/SCL2/AN20
19
RD3/P2C/SS2/AN23
22
RD4/P2D/SDO2/AN24
27
RD5/P1B/AN25
28
RD6/P1C/TX2/CK2/AN26
29
RD7/P1D/RX2/DT2/AN27
30
RD1/CCP4/SDI2/SDA2/AN21
20
RD2/P2B/AN22
21
RE0/P3A/CCP3/AN5
8
RE1/P3B/AN6
9
RE2/CCP5/AN7
10
PIC18F45K22
VDD
Xmodem, Ymodem, Zmodem
VT52, VT100, ANSI
RXD
RTS
TXD
CTS
GSM
Xmodem, Ymodem, Zmodem
VT52, VT100, ANSI
RXD
RTS
TXD
CTS
XBEE
Xmodem, Ymodem, Zmodem
VT52, VT100, ANSI
RXD
RTS
TXD
CTS
PC
BUZ1
BUZZER
D
7
1
4
D
6
1
3
D
5
1
2
D
4
1
1
D
3
1
0
D
2
9
D
1
8
D
0
7
E
6
R
W
5
R
S
4
V
S
S
1
V
D
D
2
V
E
E
3
LCD1
LM016L
GSM module
Zigbee
Computer
R1
10k
Q1
NPN
Chapter 4
HARDWARE PROFILE
The detail of hardware used in the project is as follows:
4.1 Components:
 RF Modules:
o Xbee
o GSM Module SIM 900D
 PIC Micro-controllers
o PIC18F45K22
o PIC18F452
 Passive Infrared Radial Sensor
 Ultrasonic Sensor
 USB to RS232 TTL Converter(PL2303)
 Text LCD
 Buzzer
 Battery
 5V Voltage Regulator
 3.3V Voltage regulator AMS1117
4.2 RF Modules:
RF modules are used for the transmission and receiving of data transferred from sensor and
terminal nodes. On Sensor node only Xbee module is interfaced while on terminal node Xbee is
interfaced along with a GSM Module.
4.3 Xbee(802.15.4):
XBEE is new wireless technology guided by IEEE 802.15.4 Personal Area Network standard. It
is primarily designed for the wide range controlling applications and to replace the existing non-
standard technologies. It currently operates in 868 MHz band at a data rate of 20Kbps in Europe,
914MHz band at 40kbps in USA, and the 2.4GHz ISM bands Worldwide at a maximum data-
rate of 250kbps. It is used to verify whether user’s truncation is possible or not. One of the main
advantages of this XBEE communication is that it provides a noise free communication, the
amount of noise added in this type of communication is very less compared to the other wireless
communications.



4.3.1 Comparison of WiFi, Bluetooth and XBee
XBee differs from existing networking standards. It is not a rival of Bluetooth or Wi-Fi, it
simply ”fills the gap” between wireless technologies. The standard offers very much interesting
features.

Comparison of Wi-Fi, Bluetooth, XBee

4.3.2Features/Benefits
• 802.15.4/Multipoint network topologies
• 2.4 GHz for worldwide deployment
• 900 MHz for long-range deployment
• Fully interoperable with other Digi Drop-in Networking products, including gateways,
device adapters and extenders
• Common XBee footprint for a variety of RF modules
• Low-power sleeps modes
• Multiple antenna options
• Industrial temperature rating (-40ºC to 85ºC)
• Low-power and long-range variants available

4.3.3 Performance
RF Data Rate 250 kbps
Indoor/Urban Range 100 ft (30 m)
Outdoor/RF Line-of-Sight Range 300 ft (100 m)
Transmit Power 1 mW (+0 dBm)
Receiver Sensitivity (1% PER) -92 dBm
4.3.4 Features
Serial Data Interface 3.3V CMOS UART
Configuration Method API or AT Commands, local or over-the-air
Frequency Band 2.4 GHz
Interference Immunity DSSS (Direct Sequence Spread Spectrum)
Serial Data Rate 1200 bps - 250 kbps
ADC Inputs (6) 10-bit ADC inputs
Digital I/O 8
Antenna Options Chip, Wire Whip, U.FL, & RPSMA
Networking & Security
Encryption 128-bit AES
Reliable Packet Delivery Retries/Acknowledgments
IDs and Channels PAN ID, 64-bit IEEE MAC, 16 Channels
Power Requirements
Supply Voltage 2.8 - 3.4VDC
Transmit Current 45 mA @ 3.3VDC
Receive Current 50 mA @ 3.3VDC
Power-Down Current <10 uA @ 25º C





Also modules for wireless communication companies Digi classified into different categories. So
you can choose the exact model most suited to the conditions in which it will work. We have the
basic models, which are sufficient for systems that communicate with each other. These basic
models for reproducing the manufacturer operating at distances up to 300 feet. You can also
choose between models of higher category, which communicate over a distance of some 10 km.
The difference between the models is the type of antenna, at which rent or accept data. There is
classical antenna it is available on the module and chip antenna, to mount external antenna for
longer range.
4.3.4 XBee Programmer pin configuration:-
The Pin configuration of XBee is:
1. DTR For flow control into XBee
2. RST : XBee Reset
3. Common Ground
4. CTS: Flow control from XBee
5. Power to regulator i.e. 5V
6. RX: Serial data into XBee
7. TX: Serial data from XBee
8. RTS: Flow control into XBee
9. 3V input voltage
Connecting a XBee
If the module has correct power, the green LED should be blinking. If it isn't, check the wiring
and verify that the XBee is getting power. Some versions or XBees the green LED doesn’t blink,
but it is on.
Setting up XBee :
To set up your XBee we downloaded the X-CTU tool from Digi, which is a tool that configures
our XBee with whatever settings you need. X-CTU is in disk. Once installed, we are ready to
begin configuring our XBees. Since we are constructing a point-to-multi point network, meaning
two devices are going to communicate together, one of the devices must be a Coordinator (all
XBee networks require a Coordinator) and the other must be an 'endpoint' device. What we are
going to do is create a Coordinator that manages network of XBees. To begin, we need to take
our XBee and plug it into your XBee USB Dongle, and plug it into computer. Once connected,
open the X-CTU configuration tool. The tool lists all serial ports on computer, so make sure
select the one which was installed with your XBee USB Dongle. If you've only just installed
your dongle, it is likely be the highest COM port available. Here you can see we have selected
COM15, which the Virtual COM Port is created by my currently connected XBee USB Dongle.
PC Settings: Allows a customer to select the desired COM port and configure that port to fit the
radios settings.
Range Test: Allows a customer to perform a range test between two radios.
Terminal: Allows access to the computers COM port with a terminal emulation program. This
tab also allows the ability to access the radios’ firmware using AT commands (for a complete
listing of the radios’ AT commands, please see the product manuals available online).
Modem Configuration: Allows the ability to program the radios’ firmware settings via a
graphical user interface. This tab also allows customers the ability to change firmware versions.

PC Settings Tab:
When the program is launched, the default tab selected is the “PC Settings” tab. The PC Settings
tab is broken down into three basic areas: The COM port setup, the Host Setup, and the User
Com ports.


COM port setup:
The PC settings tab allows the user to select a COM port and configure the selected COM port
settings when accessing the port. Some of these settings include:
Baud Rate: Both standard and non-standard
Flow Control: Hardware, Software (Xon/Xoff), None
Data bits: 4, 5, 6, 7, and 8 data bits
Parity: None, Odd, Even, Mark and Space
Stop bit: 1, 1.5, and 2
To change any of the above settings, select the pull down menu on the left of the value and select
the desired setting. To enter a non-standard baud rate, type the baud rate into the baud rate box to
the left.
We set our baud rate 9600 initially, we can test we can connect to our XBee by pressing the Test
/ Query button. X-CTU attempts to connect to our XBee and let we know its current firmware.
All XBees programmed with the Router configuration, so we should see the following pop-up:

If X-CTU cannot find our XBee, or we have an XBee from another supplier that has not come
programmed we saw this pop-up:

If XBee correctly reports its firmware carry on, otherwise make sure that selected COM port is
correct or keep trying by selecting higher baud rate than 9600.
Now we are ready to program our XBee. The first XBee is going to be our Coordinator module.
To program an XBee we need to upload new firmware to it. To do this, navigate to the Modem
Configuration tab in X-CTU and choose the following configuration. Click Write and X-CTU
attempts to program XBee, this should take 30 seconds or so, we may be asked to press the
RESET button on our USB Dongle. Latest firmware adds additional and new features to our
XBee.
4.3.5 Modem Configuration tab
The Modem configuration tab has four basic functions:
1: Provide a Graphical User Interface with a radio’s firmware
2: Read and Write firmware to the radio’s microcontroller
3: Download updated firmware files from either the web or from a compressed file
4: Saving or loading a modem profile

When our XBee has been successfully programmed, press the Read button to retrieve the
configuration of the device.


Now we select the baud rate for communication with other XBee device. Lower the baud rate
higher the rate of success. Higher the baud rate cause more data loss and for shorter distance we
can select higher data rate as there is less interference in shorter range so less data loss. We can
also set an encryption key which sets our data encrypted.
4.3.6 Range test:
The range test tab is designed to verify the range of the radio link by sending a user-specified
data packet and verifying the response packet is the same, within the time specified. For
performing a standard range test, please follow the steps found in most Quick Start or Getting
Started Guides that ship with the product. To test the range we produced the data of 32 byte or
we can increase it and than the software by default produce any garbage data to test the range
than we click on start.





We can also change the data receiver time out to any lower value to test a device and again
follow the same procedure for range test.
And follow the same procedure for end receiver with same baud rate, no need to set source
address and destination address.

4.4 GSM Module SIM900D:
The SIM900D is a complete Quad Band GSM/GPRS module. The SIM 900D delivers
GSM/GPRS 850/900/1800/1900 MHz performance for voice,SMS, Data in a small form factor
and low power consumption.
SIMCom presents an ultra compact and reliable wireless module-SIM900D. This is a complete
Quad-band GSM/GPRS module in a SMT type and designed with a very powerful single-chip
processor integrating AMR926EJ-S core, allowing you to benefit from small dimensions and
cost-effective solutions. Furthermore, SIM900D can be compatible with SIM340DZ.
Featuring an industry-standard interface, the SIM900D delivers GSM/GPRS
850/900/1800/1900MHz performance for voice, SMS, Data, and Fax in a small form factor and
with low power consumption. With a tiny configuration of 33mm x 33mm x 3 mm, SIM900D
can fit almost all the space requirements in your M2M applications, especially for slim and
compact demands of design.
4.4.1GeneralFeatures:
Quad-Band850/900/1800/1900MHz
GPRS multi-slot class 10/8
GPRS mobile station class B
Compliant to GSM phase 2/2+
– Class 4 (2 W @850/ 900 MHz)
– Class 1 (1 W @ 1800/1900MHz)
Dimensions: 33*33*3mm
Weight: 6.2g
Control via AT commands (GSM 07.07 ,07.05 and SIMCOM enhanced AT Commands)
SIM application toolkit
Supply voltage range : 3.2 ... 4.8V
Low power consumption: 1.0mA(sleep mode)
Operation temperature: -40 °C to +85°C
4.4.2 Specifications for Data:
GPRS class 10: max. 85.6 kbps (downlink)
PBCCH support
Coding schemes CS 1, 2, 3, 4
USSD
Non transparent mode
PPP-stack
4.4.3 Software features
0710 MUX protocol
embedded TCP/UDP protocol
FTP/HTTP
4.4.4 Special firmware
FOTA
MMS
Embedded AT
4.4.5 Specifications for Voice
Tricodec
– Half rate (HR)
– Full rate (FR)
– Enhanced Full rate (EFR)
Hands-free operation
(Echo suppression)
AMR
– Half rate (HR)
– Full rate (FR)

4.4.6 Interfaces
Interface to external SIM 3V/ 1.8V
analog audio interface
RTC backup
SPI interface (option)
Serial interface
Embedded SIM (option )
Antenna pad
GPIO
ADC
Charge interface for Li battery
PWM

4.4.7 Compatibility:
AT commands for sending a text message:
 AT
 AT+CMGS=1
 AT+CMGS=”03*********”
 >>MESSAGE
 Ctrl+Z
4.4.8 Specifications for SMS via GSM/GPRS:
Point-to-point MO and MT
SMS cell broadcast
Text and PDU mode













4.5 PIR Sensor:
PIR sensors allow you to sense motion, almost always used to detect whether a human has
moved in or out of the sensors range. They are small, inexpensive, low-power, easy to use and
don't wear out. For that reason they are commonly found in appliances and gadgets used in
homes or businesses. They are often referred to as PIR, "Passive Infrared", "Pyroelectric", or "IR
motion" sensors.
PIRs are basically made of a pyroelectric sensor i.e. a round metal can with a rectangular crystal
in the center, which can detect levels of infrared radiation. Everything emits some low level
radiation, and the hotter something is, the more radiation is emitted. The sensor in a motion
detector is actually split in two halves. The reason for that is that we are looking to detect motion
(change) not average IR levels. The two halves are wired up so that they cancel each other out. If
one half sees more or less IR radiation than the other, the output is swing high or low.
This is a simple to use motion sensor. Power it up and wait 1-2 seconds for the sensor to get a
snapshot of the still room. If anything moves after that period, the 'alarm' pin goes low.

This unit works great from 5 to 12V . You can also install a jumper wire past the 5V regulator on
board to make this unit work at 3.3V. Sensor uses [email protected].

The alarm pin is an open collector meaning you needed a pull up resistor on the alarm pin. The
open drain setup allows multiple motion sensors to be connected on a single input pin. If any of
the motion sensors go off, the input pin is pulled low.

The connector is slightly odd but has a 0.1" pitch female connector making it compatible with
jumper wires and 0.1" male headers.







4.6 Ultrasonic Sensor:
HC SR04 is an ultrasonic sensor used in our project in order to calculate the distance of the
object. The HC-SR04 ultrasonic sensor uses sonar to determine distance to an object like bats or
dolphins do. It offers excellent non-contact range detection with high accuracy and stable
readings in an easy-to-use package. From 2cm to 400 cm or 1” to 13 feet. It operation is
notaffected by sunlight or black material like Sharp rangefinders are (although acoustically soft
materials like cloth can be difficult to detect). It comes complete with ultrasonic transmitter and
receiver module.
4.6.1 Features:
● Power Supply :+5V DC
● Quiescent Current : <2mA
● Working Currnt: 15mA
● Effectual Angle: <15°
● Ranging Distance : 2cm – 400 cm/1" - 13ft
● Resolution : 0.3 cm
● Measuring Angle: 30 degree
● Trigger Input Pulse width: 10uS
● Dimension: 45mm x 20mm x 15mm
Pin Configuration:
VCC = +5VDC
Trig = Trigger input of Sensor
Echo = Echo output of Sensor
GND = GND












To start measurement, Trig of SR04 must receive a pulse of high (5V) for at least 10us, this
initiates the sensor transmits out 8 cycle of
ultrasonic burst at 40kHz and wait for the reflected ultrasonic burst. When the sensor detected
ultrasonic from receiver, it sets the Echo pin to high (5V) and delay for a period (width)which
roportion to distance. To obtain the distance, measure the width (Ton) of Echo pin.
Time = Width of Echo pulse, in uS (micro second)
● Distance in centimeters = Time / 58
● Distance in inches = Time / 148
● Or you can utilize the speed of sound, which is 340m/s







4.7 PIC Microcontroller:
PIC is a family of modified Harvard architecture microcontrollers made by Microchip
Technology, derived from the PIC1650 originally developed by General Instrument's
Microelectronics Division. The name PIC initially referred to "Peripheral Interface
Controller'"
4.7.1 PIC18F45K22:
High Performance RISC CPU:
 C Compiler optimized architecture/instruction set
 Data EEPROM to 1024 bytes
 Linear program memory addressing to 64 Kbytes
 Linear data memory addressing to 4 Kbytes
 Up to 16 MIPS operation
 16-bit wide instructions, 8-bit wide data path
 Priority levels for interrupts
 31-level, software accessible hardware stack
 8 x 8 Single-Cycle Hardware Multiplier
Extreme Low-Power Management with nanoWatt XLP™:
 Sleep mode: 100 nA, typical
 Watchdog Timer: 500 nA, typical
 Timer1 Oscillator: 500 nA @ typical 32 kHz Flexible Oscillator Structure
 Precision 16 MHz internal oscillator block:
 Factory calibrated to ± 1%
 Software selectable frequencies range of 31 kHz to 16 MHz
 64 MHz performance available using PLL
 no external components required
 Four Crystal modes up to 64 MHz
 Two external Clock modes up to 64 MHz
 4X Phase Lock Loop (PLL)
 Secondary oscillator using Timer1 @ 32 kHz
 Fail-Safe Clock Monitor:
 Allows for safe shutdown if peripheral clock stops
 Two-Speed Oscillator Start-up
Special Microcontroller Features:
 Full 5.5V operation (PIC18F2XK22/4XK22)
 Low voltage option available for 1.8V-3.6V operation (PIC18LF2XK22/4XK22)
 Self-reprogrammable under software control
 Power-on Reset (POR), Power-up Timer (PWRT) and Oscillator Start-up Timer
(OST)
 Programmable Brown-out Reset (BOR)
 Extended Watchdog Timer (WDT) with on-chip oscillator and software enable
 Programmable code protection
 In-Circuit Serial Programming™ (ICSP™) via two pins
 In-Circuit Debug via two pins
Analog Features:
 Analog-to-Digital Converter (ADC) module:
 10-bit resolution
 17 analog input channels (PIC18F/LF2XK22)
 28 analog input channels (PIC18F/LF4XK22)
 Auto acquisition capability
 Conversion available during Sleep
 Programmable High/Low Voltage Detection (PLVD) module
 Charge Time Measurement Unit (CTMU) for mTouch™ support:
 Up to 28 channels for button, sensor or slider input
 Analog comparator module with:
 Two rail-to-rail analog comparators
 Comparator inputs and outputs externally accessible and configurable
 Voltage reference module with:
 Programmable On-chip Voltage Reference (CVREF) module (% of VDD)
 Selectable on-chip fixed voltage reference
Peripheral Features:
 24/35 I/O pins and 1 input-only pin:
 High current sink/source 25 mA/25 mA
 Individually programmable weak pull-ups
 Individually programmable interrupt-on-pin change
 Three external interrupt pins
 Up to seven Timer modules:
 Up to four 16-bit timers/counters with prescaler
 Up to three 8-bit timers/counters
 Dedicated, low-power Timer1 oscillator
 Up to two Capture/Compare/PWM (CCP) modules
 Up to three Enhanced Capture/Compare/PWM (ECCP) modules with:
 One, two or four PWM outputs
 Selectable polarity
 Programmable dead time
 Auto-shutdown and Auto-restart
 PWM output steering control
 Two Master Synchronous Serial Port (MSSP) modules with two modes of
operation:
 3-wire SPI (supports all 4 SPI modes)
 I2C™ Master and Slave modes (Slave mode with address masking)
 Two Enhanced Universal Synchronous Asynchronous Receiver Transmitter
modules (EUSART):
 Supports RS-232, RS-485 and LIN 2.0
 Auto-Baud Detect
 Auto Wake-up on Start bit














4.7.2 PIC18F452:
High-Performance RISC CPU:
• Linear program memory addressing up to 2 Mbytes
• Linear data memory addressing to 4 Kbytes
• Up to 10 MIPS operation
• DC – 40 MHz clock input
• 4 MHz-10 MHz oscillator/clock input with PLL active
• 16-bit wide instructions, 8-bit wide data path
• Priority levels for interrupts
• 8 x 8 Single-Cycle Hardware Multiplier

Special Microcontroller Features:
• Power-on Reset (POR), Power-up Timer (PWRT) and Oscillator Start-up Timer (OST)
• Watchdog Timer (WDT) with its own on-chip RC oscillator
• Programmable code protection
• Power-saving Sleep mode
• Selectable oscillator options, including:
- 4x Phase Lock Loop (PLL) of primary oscillator
- Secondary Oscillator (32 kHz) clock input
• In-Circuit Serial Programming TM (ICSPTM) via two pins
Flash Technology:
• Low-power, high-speed Enhanced Flash technology
• Fully static design
• Wide operating voltage range (2.0V to 5.5V)
• Industrial and Extended temperature ranges


4.8 LCD:
LCD stands for Liquid Crystal Display. It is a thin flat electronic visual display that uses the light
modulating properties of liquid crystals.
It is a 20 characters*4 lines LCD. It requires a single 5V power supply for its operation. These
modules are preferred over seven segments and other multi segment LEDs. The reasons being:
LCDs are economical; easily programmable; have no limitation of displaying special & even
custom characters, animations and so on.
A 16x2 LCD means it can display 16 characters per line and there are 2 such lines. In this LCD
each character is displayed in 5x7 pixel matrix. This LCD has two registers, namely, Command
and Data.
The command register stores the command instructions given to the LCD. A command is an
instruction given to LCD to do a predefined task like initializing it, clearing its screen, setting the
cursor position, controlling display etc. The data register stores the data to be displayed on the
LCD. The data is the ASCII value of the character to be displayed on the LCD. Click to learn
more about internal structure of a LCD.



Pin Description:
Pin
No
Function Name
1 Ground (0V) Ground
2 Supply voltage; 5V (4.7V – 5.3V) Vcc
3 Contrast adjustment; through a variable resistor V
EE
4 Selects command register when low; and data register when
high
Register
Select
5 Low to write to the register; High to read from the register Read/write
6 Sends data to data pins when a high to low pulse is given Enable
7
8-bit data pins
DB0
8 DB1
9 DB2
10 DB3
11 DB4
12 DB5
13 DB6
14 DB7
15 Backlight V
CC
(5V) Led+
16 Backlight Ground (0V) Led-











4.9 USB toRS232 TTL Converter(PL2303):
PL2303 converter was used to connect the terminal node to the computer.
The PL-2303 operates as a bridge between one USB port and one standard RS232 Serial port.
The two large on-chip buffers accommodate data flow from two different buses. The USB bulk-
type data is adopted for maximum data transfer. Automatic handshake is supported at the Serial
port. With these, a much higher baud rate can be achieved compared to the legacy UART
controller. This device is also compliant with USB power management and remote wakeup
scheme. Only minimum power is consumed from the host during Suspend. By integrating all the
function in a SSOP-28 package, this chip is suitable for cable embedding. Users just simply hook
the cable into PC or hub’s
USB port, and then they can
connect to any RS-232
devices.









4.10 3.3 V voltage Regulator(AMS1117):
The AMS 1117 is a 800mA Low Dropout Voltage Regulator. The AMS1117 series of adjustable and fixed
voltage regulators are designed to provide 800mA output current and to operate down to 1V input-to-output
differential. The dropout voltage of the device is guaranteed maximum 1.3V at maximum output current,
decreasing at lower load currents. On-chip trimming adjusts the reference voltage to 1%. Current limit is also
trimmed, minimizing the stress under overload conditions on both the regulator and power source circuitry. The
AMS1117 devices are pin compatible with other three-terminal SCSI regulators and are offered in the low profile
surface mount SOT-223 package and in the TO-252 (DPAK) plastic package.
FEATURES
Three Terminal Adjustable or Fixed Voltages*
High Efficiency Linear Regulators1.5V, 1.8V, 2.5V, 2.85V, 3.3V and 5.0V
Post Regulators for Switching Supplies
Output Current of 800mA
5V to 3.3V Linear Regulator
Operates Down to 1V Dropout
Battery Chargers
Line Regulation: 0.2% Max.
Active SCSI Terminators
Load Regulation: 0.4% Max.
Power Management for Notebook
SOT-223 and TO-252 package available




4.11 5V Voltage Regulator:
The LM2937-5 is a 5V regulator that can supply 500mA. The LM2937 differs from the common 7805 by having
a much lower dropout voltage, 0.5V vs. 2.0V. The use of a PNP power transistor provides a low
dropout voltage characteristic. With a load current of 500 mA the minimum input to output
voltage differential required for the output to remain in regulation is typically 0.5V (1V
guaranteed maximum over the full operating temperature range). Special circuitry has been
incorporated to minimize the quiescent current to typically only10 mA with a full 500 mA load
current when the input to out-put voltage differential is greater than3V.The LM2937 requires an
output bypass capacitor for stability. As with most low dropout regulators, the ESR of this
capacitor remains a critical design parameter, but theLM2937includes special compensation
circuitry that relaxes ESR requirements. TheLM2937is stable for all ESR below 3Ω. This allows
the use of low ESR chip capacitors. Ideally suited for automotive applications, the LM2937
protecst itself and any load circuitry from reverse battery connections, two-battery jumps and up
to +60V/−50V load dump transients. Familiar regulator features such as short circuit and thermal
shutdown protection are also built in. Features Fully specified for operation over −40 C to
+125 C Output current in excess of 500 mA Output trimmed for 5% tolerance under all operating
conditions Typical dropout voltage of 0.5V at full rated load current Wide output capacitor ESR
range, up to 3ΩInternal short circuit and thermal overload protection Reverse battery
protection60V input transient protection Mirror image insertion protection.

4.12 Battery:
The 9V battery is used as a power source for the sensor nodes. The 9V is regulated to 5V in
order to run the sensors and again regulated to 3.3V to turn on the Xbee module.


4.13 Buzzer:
A buzzer is connected to the output port of the microcontroller on the terminal node so that if
intrusion occurs an alarm is generated on the terminal node.










Chapter 5
RESULTS And CONCLUSIONS

After interfacing of the components on the sensor and terminal nodes with the MCU and
connecting the Terminal node to the computer we got our desired results.
The PIR sensor keeps on sensing. If PIR sensor senses any motion it triggers the ultrasonic
sensor. The ultrasonic sensor calculates the distance with the help of the MCU and then transmits
the data to terminal node through Xbee.
On the other hand Terminal node receives data from the sensor nodes and shows the distance of
the intruder on the GUI as well as on the LCD and alarms is triggered. A text message is sent to
the cell phone of the responsible person through the GSM module.
On the GUI data fro both sensor nodes is well distinguished from each other as both nodes are
named as Node A and Node B.





ANEXTURE A
Sensor Node Code:
//Sensor node
// sensor on AN1
//Communication with Terminal MCU through Zigbee (UART)
#define d_pir PORTD.RD1
#define trig PORTD.F0
#define high 1
#define low 0
int analog_pir;
char digital_pir;
char sending_buffer[16]="xxxxxxxxxxxxxxx";
char chr_Distance1[7];
char edge = 0;
char capture = 0;
unsigned int long twoByte, tOld, tNew, tMathCm, tMathIn ;
int screenNow = 1;
int screenLast = 0;

void interrupt()
{
if(PIR1.CCP1IF)
{
if(!edge)
{
CCP1CON = 0x04; //binary 0100 change to capture every falling edge

twoByte = CCPR1H; //assign 8 bit high timer bits to 16 bit twoByte variable
datasheet pg143
twoByte = twoByte << 8; //move the 8 bits from twoByte to the far left of Variable
twoByte = twoByte | CCPR1L; //assign 8 bit low timer bits to right 8 bits of twoByte
Variable
tOld = twoByte; //remember rising edge time
edge = 1; //set to enter calculation for falling edge
} else
{
twoByte = CCPR1H;
twoByte = twoByte << 8;
twoByte = twoByte | CCPR1L;
tNew = twoByte;
capture = 1;
edge = 0; //set to return to calculation for rising edge
TMR1L = 0; //clear timers to zero for next captures
TMR1H = 0;
CCPR1L = 0;
CCPR1H = 0;
}
PIR1.CCP1IF = 0;

}

}

void Calculate_Distance()
{
if(capture)
{
PIE1.CCP1IE = 0; //interupt enable bit
capture = 0; //clear capture flag
CCP1CON = 0x05; //binary 0101 set to capture rising edge

tMathCm = (((tNew - tOld)/58)-1)*2; //find distance in cm
WordToStrWithZeros(tMathCm,&sending_buffer[8]); //change values in variable to string
sending_buffer[13]='x';
PIR1.CCP1IF = 0; // clear pheripheral interupt register flag
PIE1.CCP1IE = 1; //set pheripheral interupt enable bit
}
}


void main() {
unsigned char i;
ADCON0 = 0x02;
ADCON1= 0;
TRISA = 0xFF;
TRISD.RD1=1; //digital pir output
TRISD.RD0=0;
CCP1CON = 0x05; //set ccp to capture on rising edge datasheet pg141
TRISC.F2 = 1; //set specific port C bit 2 as input this is CCP1
T1CON = 0x11; //set timer prescale to 1/2 which is binary 0001 0001
INTCON.GIE = 1; //set general interupt bit
INTCON.PEIE =1; //set pheripheral interupt bit
PIE1.CCP1IE = 1; //set pheripheral interupt enable bit
PIR1.CCP1IF = 0; //clear flag for pheripheral interupt register

Uart1_Init(9600);
sending_buffer[15]=0x0; //null character
sending_buffer[14]='*'; //end of string
sending_buffer[0]='b'; //sensor node 'a';
do {
if(d_pir==high)
{
analog_pir = ADC_Read(2); //portA pin 2 analog pir output
IntToStrWithZeros(analog_pir,&sending_buffer[1]);
sending_buffer[7]='x';
for(i=0;i<100;i++) {
trig=1; Delay_us(10); trig=0;
Calculate_Distance();
Uart1_Write_Text(sending_buffer);
Delay_ms(200);
}
}
}while(1);
}




















ANEXTURE B
Terminal Node Coding:
unsigned char pc_cmd;
unsigned char error;
unsigned char recvbuff[15];
unsigned char gsm_cmd1[]="AT\r\n";
unsigned char gsm_cmd2[]="AT+CMGF=1\r\n";
unsigned char gsm_cmd3[]="AT+CMGS=\"";
unsigned char gsm_cmd4[]="03330711115";
unsigned char gsm_cmd5[]="\"\r\n";
unsigned char gsm_msg[30]="Intrusion detected..";
unsigned char gsm_cmd6[]="ATE0\r\n";
unsigned char i;
unsigned char counter=0;
char txt1[]="-Terminal Node-";
char txt2[]="Node A: xxx cm ";
char txt3[]="Node B: xxx cm ";
char txt4[]="Waiting for PC.";
char txt5[]="PC Connected.";
char txt6[]="intrusion occurd";
char txt7[]="sending msg.";
// LCD module connections
sbit LCD_RS at RD0_bit;
sbit LCD_EN at RD1_bit;
sbit LCD_D4 at RC4_bit;
sbit LCD_D5 at RD3_bit;
sbit LCD_D6 at RD4_bit;
sbit LCD_D7 at RD5_bit;

sbit LCD_RS_Direction at TRISD0_bit;
sbit LCD_EN_Direction at TRISD1_bit;
sbit LCD_D4_Direction at TRISC4_bit;
sbit LCD_D5_Direction at TRISD3_bit;
sbit LCD_D6_Direction at TRISD4_bit;
sbit LCD_D7_Direction at TRISD5_bit;
// End LCD module connections

void main()
{
ANSELA = 0;
ANSELB = 0;
ANSELC = 0;
ANSELD = 0;
ANSELE = 0;
recvbuff[14]=0x0;
TRISB=0;
TRISD.RD2=0; //Buzzer
Lcd_Init();
UART1_Init(9600); //UART1 for zigbee
Delay_ms(100);
UART2_Init(9600); //UART2 for computer
Delay_ms(100);
Lcd_Cmd(_LCD_CLEAR); // Clear display
Lcd_Cmd(_LCD_CURSOR_OFF);
Lcd_Out(1,1,txt1);
Lcd_Out(2,1,txt4);
while(UART2_Read()!='1');
UART2_Write('1');
Lcd_Out(2,1,txt5);
error=Soft_UART_Init(&PORTB, 2, 1, 4800, 0); //PORTB for gsm softUART
Delay_ms(100);
for(i=0;gsm_cmd1[i]!=0x0;i++) //AT
Soft_UART_Write(gsm_cmd1[i]);
delay_ms(1500);
for(i=0;gsm_cmd6[i]!=0x0;i++) //echo off
Soft_UART_Write(gsm_cmd6[i]);
delay_ms(1500);
for(i=0;gsm_cmd2[i]!=0x0;i++) //AT+CMGF=1
Soft_UART_Write(gsm_cmd2[i]);
delay_ms(1500);
PORTD.RD2=0;
while(1)
{
if(UART1_Data_Ready() == 1)
{
counter++;
UART1_Read_Text(recvbuff, "*",15); // reads text until * is found
UART2_Write_Text(recvbuff);
UART2_Write('*');
if(counter%3==0) {
PORTD.RD2=~PORTD.RD2;
}
if(counter==1) {
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1,1,txt6);
Lcd_Out(2,1,txt7);
for(i=0;gsm_cmd3[i]!=0x0;i++) //AT+CMGS=...
Soft_UART_Write(gsm_cmd3[i]);
for(i=0;gsm_cmd4[i]!=0x0;i++) //number
Soft_UART_Write(gsm_cmd4[i]);
for(i=0;gsm_cmd5[i]!=0x0;i++) //extra
Soft_UART_Write(gsm_cmd5[i]);
}
else if(counter==20) {
for(i=0;gsm_msg[i]!=0x0;i++) //message
Soft_UART_Write(gsm_msg[i]);
Soft_UART_Write(26);
}
if(counter==100)
{
counter=0;
Lcd_Cmd(_LCD_CLEAR);
Lcd_Out(1,1,txt1);
Lcd_Out(2,1,txt5);
}
if(recvbuff[0]=='a') {
txt2[8]=recvbuff[10];
txt2[9]=recvbuff[11];
txt2[10]=recvbuff[12];
Lcd_Out(1,1,txt2);
}
else {
txt3[8]=recvbuff[10];
txt3[9]=recvbuff[11];
txt3[10]=recvbuff[12];
Lcd_Out(2,1,txt3);
}
}
if(UART2_Data_Ready() == 1)
{
pc_cmd=UART2_Read();
if(pc_cmd=='n')
UART2_Read_Text(gsm_cmd4, "*",12);
else if(pc_cmd=='g')
UART2_Read_Text(gsm_msg, "*",31);
}

}
}

















ANEXTURE C
Python Coding:

from __future__ import division
import gtk
import serial
import time

class IDSystemGUI(gtk.Window):
def __init__(self):
super(IDSystemGUI, self).__init__()
self.set_title('Intrusion Detection System')
self.set_size_request(600, 360)
self.set_resizable(False)
self.set_position(gtk.WIN_POS_CENTER)

TITLE = gtk.Label('Intrusion\nDetection System')

self.connect_button = gtk.Button('Connect')
self.connect_button.connect('clicked', self.connect_to_hardware)

self.com_port = gtk.Entry()
self.com_port.set_size_request(40, 20)

button_box = gtk.HBox(False, 2)
button_box.add(self.connect_button)
button_box.add(self.com_port)

# LEDs
self.connection_LED = gtk.DrawingArea()
self.connection_LED.set_size_request(10, 10)
self.connection_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('gray'))

self.connection_LED_label = gtk.Label('Not Connected')

self.node_1_LED = gtk.DrawingArea()
self.node_1_LED.set_size_request(10, 10)
self.node_1_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('red'))

self.node_1_LED_label = gtk.Label('Node A')

self.node_2_LED = gtk.DrawingArea()
self.node_2_LED.set_size_request(10, 10)
self.node_2_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('red'))

self.node_2_LED_label = gtk.Label('Node B')

LED_box = gtk.VBox(False, 2)
LED_box.add(self.connection_LED)
LED_box.add(self.node_1_LED)
LED_box.add(self.node_2_LED)
#___________________________________

node_1_label = gtk.Label('Node A')
self.node_1_distance = gtk.Label('Distance: ')
self.node_1_speed = gtk.Label('Speed: ')

node_1_box = gtk.HBox(False, 4)
node_1_box.add(node_1_label)
node_1_box.add(self.node_1_distance)
node_1_box.add(self.node_1_speed)

node_2_label = gtk.Label('Node B')
self.node_2_distance = gtk.Label('Distance: ')
self.node_2_speed = gtk.Label('Speed: ')

node_2_box = gtk.HBox(False, 4)
node_2_box.add(node_2_label)
node_2_box.add(self.node_2_distance)
node_2_box.add(self.node_2_speed)

nodes_box = gtk.VBox(False, 2)
nodes_box.add(node_1_box)
nodes_box.add(gtk.Label('=================='))
nodes_box.add(node_2_box)
#___________________________________

self.change_number_button = gtk.Button('Change Number')
self.change_number_button.connect('clicked', self.send_phone_num)
self.change_number_text = gtk.Entry()


self.change_message_button = gtk.Button('Change Message')
self.change_message_button.connect('clicked', self.send_message)
self.change_message_text = gtk.Entry()


changes_button_box = gtk.VBox(False, 2)
changes_button_box.add(self.change_number_button)
changes_button_box.add(self.change_message_button)

changes_message_box = gtk.VBox(False, 2)
changes_message_box.add(self.change_number_text)
changes_message_box.add(self.change_message_text)
#___________________________________

layout = gtk.Fixed()
layout.put(button_box, 2, 2)
layout.put(LED_box, 2, 40)
layout.put(self.connection_LED_label, 16, 38)
layout.put(self.node_1_LED_label, 16, 50)
layout.put(self.node_2_LED_label, 16, 62)
layout.put(nodes_box, 440, 2)
layout.put(changes_button_box, 340, 300)
layout.put(changes_message_box, 440, 300)
layout.put(TITLE, 2, 300)

self.add(layout)
self.show_all()

def send_phone_num(self, widget):
mobile_number = self.change_number_text.get_text()
if len(mobile_number) == 11:
if not mobile_number.isdigit:
print('Invalid phone number')
else:
self.connection(self.com_port.get_text())
self.conn.write('n' + mobile_number + '*')

def send_message(self, widget):
message = self.change_message_text.get_text()
if len(message) == 30:
self.connection(self.com_port.get_text())
self.conn.write('g' + message + '*')

def connect_to_hardware(self, widget):
try:
port = int(self.com_port.get_text())
if port <= 0:
raise ValueError
else:
port = port - 1
except ValueError:
print('A positive integer is required')
return
is_connected = self.connection(port)
if is_connected:
self.change_number_button.set_sensitive(False)
self.change_number_text.set_sensitive(False)
self.change_message_button.set_sensitive(False)
self.change_message_text.set_sensitive(False)
pass
else:
return
self.conn.write('1')
self.conn.flush()
try:
response = self.conn.read(1)
except serial.SerialException as e:
print('ReadTimeoutError: ' + e.message)
return
if str(response) == '1':
self.connection_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('green'))

self.connection_LED_label.set_label('Connected')
else:
if not response:
print('NoResponse')
return
else:
print('InvalidResponse: ' + str(response))
return
self.data_from_hardware()

def connection(self, port):
try:
self.conn.close()
except Exception:
pass
try:
self.conn = serial.Serial(port, timeout=5)
except serial.SerialException as e:
print('ConnectionError: ' + e.message)
return
return True

def data_from_hardware(self):
self.conn.timeout = None
node_1_data = None
node_1_count = 1
node_2_data = None
node_2_count = 1
data = ''
while True:
read_char = self.conn.read(1)
if read_char == '*':
time.sleep(1)
self.action_on_data(data)
data += read_char

def action_on_data(self, data):
node = ''
if data.startswith('a'):
node = 'a'
self.node_1_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('gray'))
time.sleep(1)
self.node_1_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('red'))
#self.blink(node)
elif data.startswith('b'):
node = 'b'
self.node_2_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('gray'))
time.sleep(1)
self.node_2_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('red'))
#self.blink(node)
distance = int(data[data.index('x') + 1:-1])
speed = None
if node_1_data or node_2_data:
if node == node_1_data[0]:
speed = self.calculate_speed(node_1_data, data)
self.node_1_speed.set_label('Speed: {0:.2f}'.format(speed))
elif node == node_2_data[0]:
speed = self.calculate_speed(node_2_data, data)
self.node_2_speed.set_label('Speed: {0:.2f}'.format(speed))
if node == 'a':
node_1_data = distance
node_1_count += 1
self.node_1_distance.set_label('Distance: ' + str(distance))
elif node == 'b':
node_2_data = distance
node_2_count += 1
self.node_2_distance.set_label('Distance: ' + str(distance))
if node_1_count == 100 or node_2_count == 100:
self.conn.write('m')
self.conn.flush()
if node_1_count == 100:
node_1_count = 1
elif node_2_count == 100:
node_2_count = 1

def blink(self, node):
if node == 'a':
self.node_1_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('gray'))
time.sleep(1)
self.node_1_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('red'))
if node == 'b':
self.node_2_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('gray'))
time.sleep(1)
self.node_2_LED.modify_bg(gtk.STATE_NORMAL,
gtk.gdk.color_parse('red'))

def calculate_speed(self, distance_1, distance_2):
speed = ((distance_2 - distance_1) / 100.0) / 0.102
return speed



if __name__ == '__main__':
gui = IDSystemGUI()
gui.connect('destroy', gtk.main_quit)
gtk.main()












References:
[1]Muhammad Ali Mizidi, The PIC Microcontroller and embedded systems
[2]Joe Pardue, C programming for microcontroller
[3] PIC18F452 datasheet
[4]Jason Grimes, Using XBee in Serial Communication
[5]www.digi.com, X-CTU configuration
[6]www.youtube.com(XBee I/0 tutorial)
[7]USART PROGRAMMING in PIC18
[8]Xbee tutorials
[9]PIR sensor (Datasheet)
[10]SIM 900D data sheet
[11]Digipak











Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close