Vous êtes sur la page 1sur 92

FOOL PROOF CAR SECURITY SYSTEM

A Project report submitted in partial fulfillment of the requirement for the degree of Bachelors in Electrical (Electronics) Engineering

Department of Electrical Engineering School of Electrical Engineering & Computer Science National University of Sciences & Technology Islamabad, Pakistan 2012

Page 1 of 92

CERTIFICATE
It is Certified that the contents and form of thesis entitled Car Security System submitted by Muhammad Shahid Khan(2008-NUST-BEE-376), Hassan Mujtaba(2008NUST-BEE-347), Umer Ahmad(2008-NUST-BEE-419)has been found satisfactory for the requirement of the degree.

Advisor: ______________________________ ( Mr. Kamran Zaidi )

Co-Advisor: ______________________________ ( Dr. Osman Hassan )

Page 2 of 92

DEDICATION
We dedicate this project to

Allah the Almighty & To our Parents, Faculty and Friends

Page 3 of 92

ACKNOWLEDGEMENTS
We are also thankful to Mr. Shabbir, a mechanic at G-10 market motor workshop, who took out time from his laborious routine and explained us the car electricity distribution system.

Page 4 of 92

TABLE OF CONTENTS
CERTIFICATE _________________________________________________________________________ 2 DEDICATION _________________________________________________________________________ 3 ACKNOWLEDGEMENTS _______________________________________________________________ 4 ABSTRACT __________________________________________________________________________ 10 INTRODUCTION _____________________________________________________________________ 11 1.1 BACKGROUND _________________________________________________________________ 11 1.2 IMPORTANCE __________________________________________________________________ 11 1.2.1 Facts and Figures from ISLAMABAD POLICE _____________________________________ 11 1.3 PROBLEM STATEMENT _________________________________________________________ 12

CHAPTER # 02 ____________________________________________________________________________ 14
LITERATURE SURVEY _______________________________________________________________ 14 2.1 GSM MODULE __________________________________________________________________ 14 2.1.1 Features of GSM kit ___________________________________________________________ 14 2.1.2 Interfaces____________________________________________________________________ 14 2.2 GPS MODULE __________________________________________________________________ 15 2.3 LIMIT SWITCH _________________________________________________________________ 16 2.4 ATMEGA16_____________________________________________________________________ 17 2.4.1 Clock Sources ________________________________________________________________ 17 2.4.2 Calibrated Internal RC Oscillator ________________________________________________ 18 2.4.3 Clock Division _______________________________________________________________ 18 2.4.4 USART _____________________________________________________________________ 18 2.4.4.1 Baud rate generation _______________________________________________________ 19 2.4.5 External Interrupts ____________________________________________________________ 19 2.4.6 16-bit Timer/Counter __________________________________________________________ 20 2.5 CAR SPECIFICATIONS __________________________________________________________ 20 2.5.1 Distributor ___________________________________________________________________ 20 2.5.2 Ignition _____________________________________________________________________ 20 2.5.3 Different Ways to Turn-off the Engine:____________________________________________ 21 2.5.4 Pressure Pads: ________________________________________________________________ 21 2.6 ANDROID APPLICATION ________________________________________________________ 22 2.6.1 What is Android? _____________________________________________________________ 22 2.6.2 Features___________________________________________________________________ 22 2.6.3 Android Architecture __________________________________________________________ 23 2.6.4 Application Fundamentals ____________________________________________________ 23 2.6.5 Application Framework ________________________________________________________ 25 2.6.6 Application Components _______________________________________________________ 25 2.6.6.1 Activity__________________________________________________________________ 26 2.6.1.2 Service __________________________________________________________________ 26

Page 5 of 92

2.6.1.3 Content Provider__________________________________________________________ 26 2.6.1.4 Broadcast Receiver ________________________________________________________ 26 2.6.7 Activating Components ________________________________________________________ 27 FUCNCTIONALITY AND DESIGN ______________________________________________________ 29 3.1 HARDWARE____________________________________________________________________ 30 3.1.1 Power/Regulating Circuitry _____________________________________________________ 30 3.1.2 Current Over-ratting Protection. _________________________________________________ 31 3.1.3 GSM and GPS Circuitry. _______________________________________________________ 31 3.1.4 Multiplexing and Debugging. ___________________________________________________ 32 3.1.5 Board Design Process __________________________________________________________ 32 3.1.5.1 Schematics Layout ________________________________________________________ 32 3.1.5.2 PCB Layout. _____________________________________________________________ 37 3.1.5.3 Etching and Soldering. _____________________________________________________ 38 3.2 SOFTWARE ____________________________________________________________________ 38 3.2.1 Desktop Application. __________________________________________________________ 38 3.2.1.1 Functionalities ____________________________________________________________ 38 3.2.1.2 Use of classes and functions _________________________________________________ 39 3.2.2 Android Application ___________________________________________________________ 39 IMPLEMENTATION AND RESULT DISCUSSION _________________________________________ 40 4.1 IMPLEMENTATION _____________________________________________________________ 40 4.1.1 Hardware____________________________________________________________________ 40 4.1.1.1 Controller and communication board __________________________________________ 40 4.1.1.2 Sensors and relay control board ______________________________________________ 43 4.1.2 Software ____________________________________________________________________ 44 4.1.2.1 Android application _______________________________________________________ 44 4.1.2.1.1 App features: _________________________________________________________ 44 4.1.2.1.2 Application working ___________________________________________________ 44 4.1.2.1.3 Design ______________________________________________________________ 45 4.1.2.2 .NET application __________________________________________________________ 51 4.1.3 Problems Faced ______________________________________________________________ 54 CONCLUSION AND FUTURE RECOMMENDATIONS _____________________________________ 55 5.1 EFFICIENT BOARD REDESIGN ___________________________________________________ 55 5.1.1 Using AVR Atmega8 instead of AVR Atmega16 ____________________________________ 55 5.1.2 Removing the LCD. ___________________________________________________________ 55 5.1.3 Using Uln2003 instead of Transistors. _____________________________________________ 56 5.1.4 Using the space efficiently. _____________________________________________________ 56 Demand ___________________________________________________________________________ 57 5.2 RECOMMENDATIONS. __________________________________________________________ 57 5.2.1 Future recommendations for Android App _________________________________________ 57

REFERENCES _____________________________________________________________________________ 59

Page 6 of 92

APPENDICES _____________________________________________________________________________ 60
1- CONTROLLER CODE _______________________________________________________________ 60 2- ANDROID APP SOURCE-CODE ______________________________________________________ 82 i) FYPActivity.java __________________________________________________________________ 82 ii) IncomingSMSReceiver.java_________________________________________________________ 85 iii) Map.java _______________________________________________________________________ 87

Page 7 of 92

TABLE OF FIGURES
Figure 1 Number of car thefts in recent years ----------------------------------------------------------------- 12 Figure 2 Increasing number of car thefts as by Islamabad police department ------------------------ 12 Figure 3 GSM module ------------------------------------------------------------------------------------------------ 15 Figure 4 GPS module ------------------------------------------------------------------------------------------------- 16 Figure 5 Limit switch ------------------------------------------------------------------------------------------------- 16 Figure 6 AVR ATmega16 Pin configuration --------------------------------------------------------------------- 17 Figure 7 ATmega16 Device source clock options ------------------------------------------------------------- 17 Figure 8 ATmega16 parallel instruction fetching and execution time diagram ----------------------- 18 Figure 9 AVR ATmega16 fuse bits options ---------------------------------------------------------------------- 18 Figure 10 MCU Control Register ---------------------------------------------------------------------------------- 19 Figure 11 Mode setting control bits for INT0 ------------------------------------------------------------------ 19 Figure 12 Mode setting control bits for INT1 ------------------------------------------------------------------ 20 Figure 13 Main components of car Power Distribution System ------------------------------------------- 21 Figure 14 Android Architecture ----------------------------------------------------------------------------------- 23 Figure 15 Android Activity life cycle ------------------------------------------------------------------------------ 28 Figure 16 Voltage regulating simple circuit -------------------------------------------------------------------- 30 Figure 17 Voltage regulation implemented in Proteus ------------------------------------------------------ 31 Figure 18 One Amp fuse -------------------------------------------------------------------------------------------- 31 Figure 19 Multiplexer IC--------------------------------------------------------------------------------------------- 32 Figure 20 Schematic Layout of the whole board -------------------------------------------------------------- 33 Figure 21 AND-gate 7408 IC ---------------------------------------------------------------------------------------- 33 Figure 22 Relay driving IC Uln2003 ------------------------------------------------------------------------------- 34 Figure 23 Diode Bridge ---------------------------------------------------------------------------------------------- 35 Figure 24 COMPIM Model ------------------------------------------------------------------------------------------ 36 Figure 25 Board PCB Layout ---------------------------------------------------------------------------------------- 37 Figure 26 Visual Basic 2010 ---------------------------------------------------------------------------------------- 38 Figure 27 Use of Classes--------------------------------------------------------------------------------------------- 39 Figure 28 Micro controller ATmega16 --------------------------------------------------------------------------- 40 Figure 29 Sim-900 GSM module ---------------------------------------------------------------------------------- 41 Figure 30 Holux M-89 GPS module ------------------------------------------------------------------------------- 41 Figure 31 Voltage regulating circuitry --------------------------------------------------------------------------- 42 Figure 32 Multiplexer IC--------------------------------------------------------------------------------------------- 42 Figure 33 16x02 LCD ------------------------------------------------------------------------------------------------- 42 Figure 34 Controller and Communication Board-------------------------------------------------------------- 43 Figure 35 Sensor and Relay board -------------------------------------------------------------------------------- 44 Figure 36 Gingerbread 2.3.3 --------------------------------------------------------------------------------------- 46 Figure 37 ---------------------------------------------------------------------------------------------------------------- 46 Figure 38 Application Structure ----------------------------------------------------------------------------------- 47 Figure 39 Application MAP VIEW --------------------------------------------------------------------------------- 47 Figure 40 Applications MAIN ACTIVITY ------------------------------------------------------------------------- 48 Page 8 of 92

Figure 41 MAP View Activity --------------------------------------------------------------------------------------- 49 Figure 42 Updated Map view -------------------------------------------------------------------------------------- 49 Figure 43 App Request Acknowledgements ------------------------------------------------------------------- 50 Figure 44 Car-locking Activity -------------------------------------------------------------------------------------- 50 Figure 45 Visual basic Tool box ------------------------------------------------------------------------------------ 51 Figure 46 Functions assigned to their respective objects --------------------------------------------------- 52 Figure 47 Reusable Functions-------------------------------------------------------------------------------------- 53 Figure 48 .NET Visual Basic application GUI -------------------------------------------------------------------- 53 Figure 49 Old Board dimensions ---------------------------------------------------------------------------------- 56 Figure 50 Redesigned Board dimensions ----------------------------------------------------------------------- 57

Page 9 of 92

ABSTRACT
We designed a smart, simple and sophisticated embedded system to enhance cars security and owners control over his/her vehicle. It has much more features than the traditional car security systems.

Page 10 of 92

Chapter 1 INTRODUCTION
1.1 BACKGROUND
The project basically is focused on designing a system that is different from traditional security systems and is much difficult to hack. It also provides the owner much more control over his vehicle. The project provides solution for car thefts which are of various types as discussed below: Theft of an unattended vehicle without keys: The removal of a parked vehicle either by breaking and entry, followed by hotwiring or other tampering methods to start the vehicle, or else towing. Opportunistic theft: The removal of a vehicle that the owner or operator has left unattended with the keys visibly present, sometimes idling. Carjacking: Refers to the taking of a vehicle by force or threat of force from its owner or operator. In most places, this is the most serious form of theft, since assault also occurs. In some car jackings, the operators and passengers are forced from the vehicle while the thief drives it away him/herself, while in other incidents, the operator and/or passenger(s) are forced to remain in the vehicle as hostages. Some less common car jackings result in the operator being forced to drive the assailant in accordance with the assailant's demands.

1.2 IMPORTANCE
The below cited facts and figure from reliable resources also underpins the importance of the project. 1.2.1 Facts and Figures from ISLAMABAD POLICE The previously existing security solutions are not that much reliable as mentioned categorically on Islamabad traffic police website as Experience has shown that Suzuki &Toyota make cars are the most vulnerable due to their defective lock systems (door and ignition) which provides the thieves with an easy opportunity to steal them.

Facts and figures taken from Islamabad police official website are:

Page 11 of 92

Figure 1 Number of car thefts in recent years

Figure 2 Increasing number of car thefts as by Islamabad police department

1.3 PROBLEM STATEMENT


There are small numbers of competitors in the market and the security system provided by them is easily hacked. What we are suggesting is a smart, simple and sophisticated embedded system to enhance cars security and owners control over his/her vehicle. It has much more features than the traditional car security systems. The distinguishing features of our product are:
Page 12 of 92

Immediate Smartphone and PC alert. Whenever there is a break-in the system immediately takes all the safety measures and alerts the car owner. Total seizure of engine and self-motor. This feature works when the system receives a lock command or when the car is in armed state. In both the cases the self-starter and spark-plugs are cut out of any power. Intelligent placement of sensors. Sensors are placed smartly at three locations. The pressure pads, the hood and the hot-wiring area. Position locking after the car park. This feature enables the car owner to lock the car position after the vehicle is parked. After the position is locked if there appear any changes in the car position an alert is sent to the owner and alarm are raised. Two way arm/disarm of the system. This attribute includes two options provided to the customer for arming/disarming his vehicle. One is through the cars central locking key and the other is through SMS. The system after arming the vehicle replies back with an acknowledgement. Remote locking and location retrieving feature available from virtually anywhere. The system always responds to the remote-locking call by totally seizing the cars engine and to the location call by responding to the owners mobile with the coordinates which are then plotted on Google maps automatically. Its in the range. The system cost is cheap enough to target all the mediocre, high-end and low-end car buyers. The car security solution is also accompanied with an Android and a desktop application, all the said features works with both the applications and also with a simple mobile phone*.

Page 13 of 92

Chapter # 02 LITERATURE SURVEY


As the technology is much more advance now it has affected all the fields of life and with time more and more sophisticated systems for car security are in market but they are not in the range of every person. The project employs GSM and GPS chips and integrates them with the sensors and controlling circuitry.

2.1 GSM MODULE


We want to use a module sim300 which is available in the local market. The specifications are given below and are just what we need. Designed for global market, SIM300 is a Tri-band GSM/GPRS engine works on frequencies EGSM 900 MHz, DCS 1800 MHz and PCS 1900 MHz SIM300 features GPRS multi-slot class 10/ class 8 (optional) and supports the GPRS coding schemes CS1, CS-2, CS-3 and CS-4.With a tiny configuration of 40mm x 33mm x 2.85mm, SIM300 can fit almost all the space requirements in your applications, such as smart phone, PDA phone and other mobile devices 2.1.1 Features of GSM kit 1. This GSM modem is a highly flexible plug and play quad band GSM modem 2. For direct and asy integration to RS232. 3. Supports features like Voice, Data/Fax, SMS,GPRS and integrated TCP/IP stack. 4. Control via AT commands(GSM 07.07,07.05 and enhanced AT commands) 5. Use AC DC Power Adaptor with following ratings DC Voltage : 12V /1A 6. Current Consumption in normal operation 250mA, can rise up to 1Amp while transmission. 2.1.2 Interfaces 1. RS-232 through D-TYPE 9 pin connector, 2. Serial port baud rate adjustable 1200 to115200 bps (9600 default) 3. BRK connector for MIC & SPK, SIM card holder 4. Power supply through DC socket 5. SMA antenna connector and Murata Antenna ( optional) 6. LED status of GSM / GPRS module

Page 14 of 92

Figure 3 GSM module

2.2 GPS MODULE


The Global Positioning System (GPS) is a space-based global navigation satellite system (GNSS) that provides location and time information in all weather, anywhere on or near the Earth, where there is an unobstructed line of sight to four or more GPS satellites. It is maintained by the United States government and is freely accessible by anyone with a GPS receiver with some technical limitations which are only removed for military users. The GPS program provides critical capabilities to military, civil and commercial users around the world. It is an engine of economic growth and jobs, and has generated billions of dollars of economic activity. It maintains future war fighter advantage over opponents and is one of the four core military capabilities. In addition, GPS is the backbone for modernizing the global air traffic system. The GPS project was developed in 1973 to overcome the limitations of previous navigation systems, integrating ideas from several predecessors, including a number of classified engineering design studies from the 1960s. GPS was created and realized by the U.S. Department of Defense (DoD) and was originally run with 24 satellites. It became fully operational in 1994. Advances in technology and new demands on the existing system have now led to efforts to modernize the GPS system and implement the next generation of GPS III satellites and Next Generation Operational Control System (OCX). Announcements from the Vice President and the White House in 1998 initiated these changes. In 2000, U.S. Congress authorized the modernization effort, referred to as GPS III. In addition to GPS, other systems are in use or under development. The Russian Global Navigation Satellite System (GLONASS) was in use by only the Russian military, until it was made Page 15 of 92

fully available to civilians in 2007. There are also the planned European Union Galileo positioning system, Chinese Compass navigation system, and Indian Regional Navigational Satellite System.

Figure 4 GPS module

2.3 LIMIT SWITCH


The car bonnet will have a limit switch through which we can find whether the bonnet is opened or not

Figure 5 Limit switch

Page 16 of 92

2.4 ATMEGA16
We used AVR ATmega16 for our project as it is high performance, low power 8-bit MCU. It is a very robust MCU and can bear temperature up to 75oC. It has 16KB program and 1KB data memory.

Figure 6 AVR ATmega16 Pin configuration

2.4.1 Clock Sources The device has the following clock sources which can be selected by Flash Fuse bits.

Figure 7 ATmega16 Device source clock options

Page 17 of 92

2.4.2 Calibrated Internal RC Oscillator We used controller internal oscillator which provide a range of nominal frequencies as below. 2.4.3 Clock Division The AVR CPU is driven by the CPU clock, directly generated from the selected clock source for the chip. No internal clock division is used. The controller employs parallel instruction fetching and execution enabled by Harvard architecture. The controller does 1 MIPS per MHz using pipelining.

Figure 8 ATmega16 parallel instruction fetching and execution time diagram

2.4.4 USART The Universal Synchronous and Asynchronous serial Receiver and Transmitter (USART) is a highly flexible serial communication device.

Figure 9 AVR ATmega16 fuse bits options

Page 18 of 92

We used 8MHz internal oscillator by setting CKSEL3=0, CKSEL2=1, CKSEL1=0, CKSEL0=0. 2.4.4.1 Baud rate generation To generate a specific baud rate USART baud rate register (UBRR) is used. Baud rate can be calculated using the following formula

Using the above formula the UBRR value for GSM (9600) and GPS (4800) are 51 and 103 respectively. 2.4.5 External Interrupts The External Interrupts are triggered by the INT0, INT1, and INT2 pins. Observe that, if enabled, the interrupts will trigger even if the INT0..2 pins are configured as outputs. This feature provides a way of generating a software interrupt. The external interrupts can be triggered by a falling or rising edge or a low level (INT2 is only an edge triggered interrupt). This is set up as indicated in the specification for the MCU Control Register MCUCR.

Figure 10 MCU Control Register

The interrupt sense control table for INT0 and INT1 are as under. We used INT0 as positive edge triggered and INT1 as low-level triggered.

Figure 11 Mode setting control bits for INT0

Page 19 of 92

Figure 12 Mode setting control bits for INT1

2.4.6 16-bit Timer/Counter The 16-bit Timer/Counter unit allows accurate program execution timing (event management), wave generation, and signal timing measurement. We used timer for parking position lock feature.

2.5 CAR SPECIFICATIONS


We decided to use a corolla 1999 XEG for our experiments. We surveyed the car electric system and found out the following things we could use to our advantage. 2.5.1 Distributor A car distributor draws its power from the car battery and provides it to the spark plug. But, the distributor itself does not turn on until the car ignition is on. The key controls this ignition. 2.5.2 Ignition The car ignition is turned on when the key is inserted then if the key is half rotated then it turns on the half ignition if it is fully rotated then full ignition is turned on and the car can now be started using self-start motor.

Page 20 of 92

Figure 13 Main components of car Power Distribution System

2.5.3 Different Ways to Turn-off the Engine: When we surveyed we found out a few ways to turn the engine off which are, Disable the power flowing from battery to the ignition switch using a relay. Disable the current flowing to the distributor. In this case the car lights, audio system and all other electrical appliances will turn on but the engine wont start. This is a much better way as it will confuse the burglar. 2.5.4 Pressure Pads: The car we are using has built-in pressure pads at the door which tell us whether the door is closed or not. We will use these pads to find out if a burglar opens a door. These will be connected to the microcontroller.
Page 21 of 92

2.6 ANDROID APPLICATION


2.6.1 What is Android? Android is a Linux-based operating system for mobile devices such as smart phones and tablet computers. It is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language. Android has a large community of developers writing applications ("apps") that extend the functionality of the devices. Developers write primarily in a customized version of Java-Apps can be downloaded from third-party sites or through online stores such as Google Play (formerly Android Market), the app store run by Google. In October 2011, there were more than 500,000 apps available for Android, and the estimated number of applications downloaded from the Android Market as of December 2011 exceeded 10 billion. Android became the worlds leading Smartphone platform at the end of 2010. For the first quarter of 2012, Android had a 59% Smartphone market share worldwide, with a 331 million devices installed base and 85 million activations or 934,000 per day. Analysts points to the advantage for Android to be a multi-channel, multi-carrier OS. 2.6.2 Features

Application framework: enabling reuse and replacement of components Dalvik virtual machine: optimized for mobile devices Integrated browser: based on the open source WebKit engine Optimized graphics: powered by a custom 2D graphics library; 3D graphics based on the OpenGL ES 1.0 specification (hardware acceleration optional) SQLite: for structured data storage Media support: for common audio, video, and still image formats (MPEG4, H.264, MP3, AAC, AMR, JPG, PNG, and GIF) GSM Telephony: (hardware dependent) Bluetooth, EDGE, 3G, and WiFi: (hardware dependent) Camera, GPS, compass, and accelerometer: (hardware dependent)

Page 22 of 92

Rich development environment: Including a device emulator, tools for debugging, memory and performance profiling, and a plugin for the Eclipse IDE Android applications are developed using the Java language. Android relies heavily on Java fundamentals. The Android SDK includes many standard Java libraries (data structure libraries, math libraries, graphics libraries, networking libraries and everything else) as well as special Android libraries that help in developing awesome Android applications. Android applications run in a special virtual machine called the Dalvik VM. While the details of this VM are unimportant to the average developer, it can be helpful to think of the Dalvik VM as a bubble in which your Android application runs, allowing you to not have to worry about whether the device is a Motorola Droid, an HTC Evo, or the latest toaster running Android. You dont care so long as the device is Dalvik VM friendly. 2.6.3 Android Architecture
The following diagram shows the major components of the Android operating system:

Figure 14 Android Architecture

2.6.4 Application Fundamentals The Android SDK tools compile the codealong with any data and resource filesinto an Android package, an archive file with an .apk suffix. All the code in a single .apk file is considered to be one application and is the file that Android-powered devices use to install the application.
Page 23 of 92

Quick View Android applications are composed of one or more application components (activities, services, content providers, and broadcast receivers) Each component performs a different role in the overall application behavior, and each one can be activated individually (even by other applications) The manifest file must declare all components in the application and should also declare all application requirements, such as the minimum version of Android required and any hardware configurations required Non-code application resources (images, strings, layout files, etc.) should include alternatives for different device configurations (such as different strings for different languages and different layouts for different screen sizes) Once installed on a device, each Android application lives in its own security sandbox: The Android operating system is a multi-user Linux system in which each application is a different user. By default, the system assigns each application a unique Linux user ID (the ID is used only by the system and is unknown to the application). The system sets permissions for all the files in an application so that only the user ID assigned to that application can access them. Each process has its own virtual machine (VM), so an application's code runs in isolation from other applications. By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications. In this way, the Android system implements the principle of least privilege. That is, each application, by default, has access only to the components that it requires to do its work and no more. This creates a very secure environment in which an application cannot access parts of the system for which it is not given permission. However, there are ways for an application to share data with other applications and for an application to access system services: An application can request permission to access device data such as the user's contacts, SMS messages, the mountable storage (SD card), camera, Bluetooth, and more. All application permissions must be granted by the user at install time.
Page 24 of 92

2.6.5 Application Framework By providing an open development platform, Android offers developers the ability to build extremely rich and innovative applications. Developers are free to take advantage of the device hardware, access location information, run background services, set alarms, add notifications to the status bar, and much, much more. Developers have full access to the same framework APIs used by the core applications. The application architecture is designed to simplify the reuse of components; any application can publish its capabilities and any other application may then make use of those capabilities (subject to security constraints enforced by the framework). This same mechanism allows components to be replaced by the user. Underlying all applications is a set of services and systems, including: A rich and extensible set of Views that can be used to build an application, including lists, grids, text boxes, buttons, and even an embeddable web browser Content Providers that enable applications to access data from other applications (such as Contacts), or to share their own data. A Resource Manager, providing access to non-code resources such as localized strings, graphics, and layout files. A Notification Manager that enables all applications to display custom alerts in the status bar. An Activity Manager that manages the lifecycle of applications and provides a common navigation back stack.

2.6.6 Application Components Application components are the essential building blocks of an Android application. Each component is a different point through which the system can enter your application. Not all components are actual entry points for the user and some depend on each other, but each one exists as its own entity and plays a specific roleeach one is a unique building block that helps define your application's overall behavior. There are four different types of application components. Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed. Here are the four types of application components:
Page 25 of 92

2.6.6.1 Activity 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. Although the activities work together to form a cohesive user experience in the email application, each one is independent of the others. As such, a different application can start any one of these activities (if the email application allows it). For example, a camera application can start the activity in the email application that composes new mail, in order for the user to share a picture. 2.6.1.2 Service A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. 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. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it. 2.6.1.3 Content Provider A content provider manages a shared set of application data. You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your application can access. Through the content provider, other applications can query or even modify the data (if the content provider allows it). For example, the Android system provides a content provider that manages the user's contact information. Content providers are also useful for reading and writing data that is private to your application and not shared. 2.6.1.4 Broadcast Receiver A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the systemfor example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcastsfor example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event. A unique aspect of the Android system design is that any application can start another applications component. For example, if you want the user to capture a photo with the device camera, there's probably another application that does that and your
Page 26 of 92

application can use it, instead of developing an activity to capture a photo yourself. You don't need to incorporate or even link to the code from the camera application. Instead, you can simply start the activity in the camera application that captures a photo. When complete, the photo is even returned to your application so you can use it. To the user, it seems as if the camera is actually a part of your application. When the system starts a component, it starts the process for that application (if it's not already running) and instantiates the classes needed for the component. For example, if your application starts the activity in the camera application that captures a photo, that activity runs in the process that belongs to the camera application, not in your application's process. Therefore, unlike applications on most other systems, Android applications don't have a single entry point (there's no main() function, for example).Because the system runs each application in a separate process with file permissions that restrict access to other applications, your application cannot directly activate a component from another application. The Android system, however, can. So, to activate a component in another application, you must deliver a message to the system that specifies your intent to start a particular component. The system then activates the component for you. 2.6.7 Activating Components Three of the four component typesactivities, services, and broadcast receiversare activated by an asynchronous message called an intent. Intents bind individual components to each other at runtime (you can think of them as the messengers that request an action from other components), whether the component belongs to your application or another. For broadcast receivers, the intent simply defines the announcement being broadcast (for example, a broadcast to indicate the device battery is low includes only a known action string that indicates "battery is low").

Page 27 of 92

ANDROID ACTIVITY LIFECYCLE

Figure 15 Android Activity life cycle

Page 28 of 92

Chapter # 03 FUCNCTIONALITY AND DESIGN


The chapter includes design and functionality of the project and describes why and how the specific design was used and also describes the design functionality in detail. The project consists of two major parts. 1. HARDWARE 2. SOFTWARE Below is the block diagram giving an overview of the project.

Page 29 of 92

3.1 HARDWARE
3.1.1 Power/Regulating Circuitry Controlling the power input to GPS and GSM module is of paramount importance especially the GSM module is very sensitive to power fluctuations and is prone to burn out if sudden changes in output voltages occur.

The GSM modem was fed with voltage from LM317 voltage regulator which also provides line and load regulation useful for our circuits because in peak data rate time the GSM draws more current than normal which may cause a decrease in input voltage which is harmful for the GSM module and this IC provides a peak current of 1.5A while maintaining load and line regulation. The generic regulating circuit with capacitors to inhibit fluctuations was employed in the circuit board.

Figure 16 Voltage regulating simple circuit

The GPS module was also maintained at 5V but it does not take as much current as GSM. The regulating voltage to GPS is provided by ST7805 IC . This IC has maximum current rating up to 1A.

Page 30 of 92

Figure 17 Voltage regulation implemented in Proteus

Thermal regulation protection is also provided by both of the regulators used in the circuit which is quite a useful feature. 3.1.2 Current Over-ratting Protection. Though some of the over-ratting protection is provided by GSM sim900 itself but still it is very sensitive. Protection from higher current is provided by regulators by line and load regulation features of regulator ICs but still we used a 2A fuse for the board so that if the current is increased more than this the circuit will be protected.

Figure 18 One Amp fuse

3.1.3 GSM and GPS Circuitry. The GPS just need power to start and when it is turned on it keeps on sending the coordinates in NMEA format unless and until it is powered off.

Page 31 of 92

But this is not the case with GSM module. GSM module is provided with the power and the power key pin of GSM is kept low for some micro second and then turned off again to start the GSM. This functionality is provided in the board in two ways one is manual and the other is from controller with a switch to select which one to use. 3.1.4 Multiplexing and Debugging. As the controller we are using has only one transmitter and receiver pin and we have to take input from both the GSM transmitter pin and GPS transmitter pin so for that purpose multiplexer IC 74LS157 was used with the select pin coming from controller and the output multiplexed pin to the receiver of controller.

Figure 19 Multiplexer IC

3.1.5 Board Design Process 3.1.5.1 Schematics Layout First of all we designed the schematics layout of our board on Proteus and checked many times for any fault. Below is the main schematics diagram of our board which includes all the hardware components except the sensors.

Page 32 of 92

Figure 20 Schematic Layout of the whole board

LM 7408 The LM7408 integrated circuit contains four AND gates. We employed two of its and gates. Output from three different sensor are fed to the AND gate inputs the output of is fed to the controller at INT1.

Figure 21 AND-gate 7408 IC

Page 33 of 92

ULN 2003 The integrated circuit ULN2003 is a high voltage high current Darlington transistor arrays. The collector current has rating up to 500mA. It works well with TTL and CMOS devices. It could be used for many purposes but we used the IC to drive relays in our project.

Figure 22 Relay driving IC Uln2003

Diode Bridge
A diode bridge is a device containing four (or more) diodes in a bridge circuit configuration that provides the same polarity of output for either polarity of input.

Page 34 of 92

Figure 23 Diode Bridge

Proteus COMPIM serial port model Traditionally, simulation systems have had no direct connection to the physical world around them. This meant that if you wanted to simulate part of a much bigger system of interconnected units, one had to either create simulations of the other units, or create files containing test data. The Virtual System Modeling capabilities of Proteus VSM allow the creation of models that can actually interact with the physical world. We call such models Physical Interface Models or PIMs for short.

Page 35 of 92

The COMPIM model is a Physical Interface Model of a serial port. Incoming serial data is buffered and presented to the circuit as a digital signal, whilst serial digital data generated by a CPU or UART model appears at the PC's physical COM port. The COMPIM model also provides for baud rate translation, and for optional hardware or software handshaking on both the physical and virtual sides of the device. This allows any real world hardware equipped with a serial port to interact with a VSM simulation. For example, you could use it to develop a program for a microprocessor within Proteus VSM that would operate a real physical modem, perhaps as part of a security or home automation system. Alternatively, a monitor debugger running on one PC can be used to debug a simulated design running within VSM. The COMPIM model can also be used for some simple digital I/O: the CTS, DSR, DCD and RI lines on the physical serial port can act as rudimentary digital inputs from external stimulus, such as switches; the RTS and DTR lines on the physical serial port can act as rudimentary outputs. Bear in mind that these signals may need addition physical signal conditioning, depending on application and port type.

Figure 24 COMPIM Model

Page 36 of 92

3.1.5.2 PCB Layout. PCB Layout was designed on ARIES but it was very difficult to design because the PCB packages of various components were not available and we have to place PCB packages of other components and rearranging them. Below is the PCB layout of our board.

Figure 25 Board PCB Layout

Page 37 of 92

3.1.5.3 Etching and Soldering. Etching when done for the first time the tracks oxidized and we had to etch a new PCB again then we soldered the components and debugged the circuit.

3.2 SOFTWARE
3.2.1 Desktop Application. The Desktop application is developed on Visual Basic 2010 Express using .NET programming. This is the standard interface of a visual basic program downloaded from Microsofts website.

Figure 26 Visual Basic 2010

3.2.1.1 Functionalities 1. The connection button checks whether a GSM modem is connected or not. 2. The car location button fetches the car location in longitude and latitude and displays it in the web browser below. 3. The turn off engine command sends a command to shutoff the engine and then waits for the confirmation.
Page 38 of 92

4. The Arm/Unarm checklist arms or disarms the security protocol on the car. 5. The exit button closes the application.

3.2.1.2 Use of classes and functions The inbuilt classes, establishes a connection between the GSM modem and the application. Thereadinbox class reads the memory for unread messages. Thesendsms class sends required SMS and the license class stores licensing info.

Figure 27 Use of Classes

3.2.2 Android Application The functionality and design of Android application is explained in chapter 04 section 4.1.2.1

Page 39 of 92

Chapter # 04 IMPLEMENTATION AND RESULT DISCUSSION


4.1 IMPLEMENTATION
We implemented our project on XEG corolla car which was already fitted with a traditional central locking security system. To incorporate our security system with this already existing system was a huge problem for us. 4.1.1 Hardware Hardware was implemented according to the design and simulations done in Proteus and Aries as explained in Functionality and Design chapter. Two boards are made for the implementation of the project. 1. Controller and communication board. 2. Sensors and relay control board. 4.1.1.1 Controller and communication board This board does the main and the most difficult tasks of the project. The board includes AVR ATmega16 controller Sim-900 GSM module Holux M-89 GPS module Regulating circuitry for both the said modules Multiplexing for GSM and GPS An LCD for the debugging of code Outputs and inputs for and from the Sensor and relay board.

Figure 28 Micro controller ATmega16

Page 40 of 92

Figure 29 Sim-900 GSM module

Figure 30 Holux M-89 GPS module

Page 41 of 92

Figure 31 Voltage regulating circuitry

Figure 32 Multiplexer IC

Figure 33 16x02 LCD

Page 42 of 92

Figure 34 Controller and Communication Board

4.1.1.2 Sensors and relay control board This is the second board which does many important tasks for example making sensors output signals compatible to the controller and provides the output connections. It also contains the relay driver circuitry and relays.

Page 43 of 92

Figure 35 Sensor and Relay board

4.1.2 Software We implemented our idea on two software applications that in turn control the controls that we have introduced to the owners car by installing our system in the car. 4.1.2.1 Android application 4.1.2.1.1 App features: 1. Embedded Google maps 2. Remote Engine locking& starting 3. Alerts 4. Parking Mode

4.1.2.1.2 Application working We have used Android Ginger Bread 2.3.3 version for development of our car security app.

Page 44 of 92

The app has a very user friendly interface which is easy to use and is very interactive. It includes dialogue boxes, alerts and button click sounds which overall enhance the app experience. The app has a registered Incoming SMS receiver that listens for specific SMS messages. All major events of the phone e.g. SMS arrival, Call arrival, Low battery, Low signal strength are broadcasted all over the system and the receivers that have registered for a particular broadcast can filter them and take actions when such events or broadcasts occur. Our App uses this concept to extract GPS coordinates from a particular type of SMS and plot them on Google map using a Map view layout. Further on each update a marker is placed at the current location. The App also has an alarm which goes off in case an alert SMS is received from the car. A Parking mode is also available which allows the user to safely park the car. The security system informs the app if the car is moved from its parking position and the app alerts the user. The App also provides automatic ignition feature to the user.

4.1.2.1.3 Design The Gingerbread 2.3.3 version was used because of its overall market distribution and latest features.

Page 45 of 92

Figure 36 Gingerbread 2.3.3

The app extracts alerts and GPS coordinates from SMS using Wi-Fi or Mobile internet.

Figure 37

Page 46 of 92

The app has the structure shown on the right for receiving coordinates& alerts. Arrival of SMS is broadcasted throughoutthe system. The App has a defined broadcast listener which listens for SMS arrivals and informs the app. On the arrival of SMS, the App calls the systems default SMS manager to retrieve the SMS. It then extracts the number and the message from the SMS. If the number matches with that of the security system then the app further processes what type of SMS has been received and takes action accordingly.
Figure ccc 38 Application Structure

The app has a MAP VIEW that embeds Google maps. The Map View activity processes on the received coordinates and plots them on Google map. The received coordinates are converted to Google maps readable format and then fed to the map view which plots them.
Figure 4.11 39 Application MAP VIEW

Page 47 of 92

Figure 4.12 40 Applications MAIN ACTIVITY

Shown above is the main activity or the main screen of the app. It includes 5 buttons:

Lock- Pressing this button sends an SMS to the car telling it to arm itself. Unlock- Pressing this button sends an SMS to the car telling it to unarm itself. Find Car- Pressing this buttons opens a Map view activity and also sends an SMS to car requesting GPS coordinates. Park Car- This button activates Parking mode. Ignition- This button automatically starts the car.

Further on each button click a sound is played and a toast is displayed. Toasta notification displayed for a short time on the bottom of the screen.

Page 48 of 92

The image shown on the right is a map view activity embedding a Google map. This activity updates on every SMS from the car containing GPS coordinates. pressing the Menu button while on this activity shows an Update Location icon which allows the user to further request update on his current car location

Figure dd 41 MAP View Activity

The image on the right shows an updated map view activity with markers. Each update places a marker at the received location. The map adjusts itself with the latest update and places the marker at the center of the map. The map also has zooming functionality, however he default zoom level is set to 16.

Figure Figure 42 4.14 Updated Map view

Page 49 of 92

The app confirms lock, unlock, park and ignition status through an SMS from the car and displays an alert dialogue box informing the user that the security system acknowledges his command. The image on the right shows the confirmation dialogue box shown when the Lock button is pressed

Figure 4.15 43 App Request Acknowledgements

The image on the right shows a toast displayed on pressing the Lock button. The app also has an Aboutsection which tells the user about different features of the app and how to use it. It can be accessed from the main screen by pressing the menu button.

Figure Car-locking Activity Figure 44 4.16

Page 50 of 92

CODE:
The java code is divided into 3 main classes: FYPActivity.java IncomingSMSReceiver.java Map.java

The source code of the application is attached in appendice2. 4.1.2.2 .NET application First of all we made a project with type as windows application. Multiple items can be added easily. The tool box provided by the visual basic provided us with lot of options.

Figure 45 Visual basic Tool box

Page 51 of 92

We added many objects to our GUI and then wrote the underlying code of that object.

Figure 46 Functions assigned to their respective objects

The above picture shows the different functions assigned to multiple objects taken from the toolbox mentioned before. Below are shown the different functions we made to be used in the code which are reusable. For example one of the function establishes a connection with the GSM modem setting different parameters to their desired values. The readinbox function scans the inbox for new messages. The sendmsg function sends an SMS while the license button sets licensing information for a library (mcorelib) we used.

Page 52 of 92

Figure 47 Reusable Functions

Below is the snapshot of the GUI of our application.

Figure 48 .NET Visual Basic application GUI

Page 53 of 92

4.1.3 Problems Faced During the implementation of the project we faced quite lot of problems. Some of which are cited below. 1. 2. 3. 4. 5. Understanding the car power distributions system. Car distributor, spark plugs connections and full and half ignition. The already installed security systems wires and connections were quite complex. The whole of car body is grounded so we have to be extra careful with live wires. We spotted a wire for locking and unlocking signal coming from the car key, we tried every possible way to guess what the waveform shape is like without the oscilloscope but we could not. 6. GSM power key pin is extra sensitive and we got one of our GSM module burnt because of switching it with a transistor. 7. GPS was not giving right coordinates. 8. Incorporating the whole of our security system there were a lot of Grounding issues. 9. Checking and debugging the system while in the car was quite exacting. 10. There were high voltage jitters in car circuitry at times like when starting the car, during locking and unlocking of the car, these spikes were giving unusual interrupts which were quite troublesome. 11. Developing Android application was quite difficult because we had no previous knowledge about java development. 12. Similarly developing .NET application was difficult than what we were expecting.

Page 54 of 92

Chapter # 05 CONCLUSION AND FUTURE RECOMMENDATIONS


After the implementation of the project we came to the conclusion that there are more ways to enhance the security but then it will cost the customer more. The solution we suggested is sufficiently fulfilling the security needs and is in the range. The security solution is totally in commensurate with what the customer will pay.

5.1 EFFICIENT BOARD REDESIGN


We redesign the board excluding the unnecessary items and introducing more efficient devices. The redesign was to make it more attractive for the market. To make it happen we did four main changes. 5.1.1 Using AVR Atmega8 instead of AVR Atmega16 There were many reasons to use Atmega8 instead of Atmega16 because after the compilation of our final code we observed that it was using a very small percentage of controllers program and data memory so we searched for another microcontroller with the features like 1. Smaller size. 2. Less program and data memory that would be sufficient for us. 3. We dont have to trade off other features that we cannot put aside. 4. It has less or preferably no compatibility issues with our code. 5. Last but not least is easily available in market After much consideration and thought we came up with Atmega8 that fortunately possess all the above features. 5.1.2 Removing the LCD. We were using a 16*2 LCD for debugging our code practically on hardware but as the code is final now. The LCD was redundant so we thought of removing it, saving some precious space.

Page 55 of 92

5.1.3 Using Uln2003 instead of Transistors. Previously we were using a transistor and two resistors for driving each relay. This means that to drive four relays we were using four transistors and 8 resistors. In the redesigned board we used Uln2003 integrated circuit that derives relays quite efficiently and a single IC can drive up to 7 relays. 5.1.4 Using the space efficiently. As we had already implemented a board we were totally aware of where we have used PCB space wastefully, in the redesigned board we made it sure that no space is wasted but still it was not an SMT PCB, so there is still room for improvement. Below are the dimensions of Old and New design respectively.

Figure 49 Old Board dimensions

Page 56 of 92

Figure 50 Redesigned Board dimensions

Demand
Because of the project features and customer demands we were approached by a person in G-10 auto workshop who asked us that after totally completing the project we should contact him to launch the product in the market. Also several acquaintances have asked us to install the product in their car once it is completed.

5.2 RECOMMENDATIONS.
We would suggest the following recommendations to the existing project. 1. Introducing key based locking and unlocking. 2. Central locking and unlocking of car locks. 3. SMT design of the whole board to make it more commercial. 4. Introducing features other than security like trunk and bonnet opening, remote start etc. 5.2.1 Future recommendations for Android App The App is currently in its beta form and can be further developed and many more features can be included. Following are some of the suggestions for improving the app:

Page 57 of 92

The app can be used to provide restrictions on the car such as to remote lock it if it goes out of a particular region or city. The app can also inform the user about the speed at which the car is moving. Further on improving the security system the app can interact more with the car and inform the user about car statistics such as sensors status, car temperature, fuel usage etc. Although the app plays an alarm on security failure but it requires the user to at least open the app once so that it goes back in the background and starts monitoring. This headache can be removed by automatically starting the app on system reboot or startup. The Maps currently display a maker at one specific position. A real time tracking feature can also be implemented by using a path on top of the Google maps which will show the course of the car movement. Terrain view and Street view can also be added. The app can also have a history feature which automatically takes car location and updates the history. The users can then look up history and know where the car has been for the past few days or months. (this is in case you lend your car to someone)

Page 58 of 92

REFERENCES

Page 59 of 92

APPENDICES
1- CONTROLLER CODE
#define F_CPU 8000000UL /*--------------------------------------------------------------------------------HEADER FILES-----------------------------------------------------------------------------------------------------*/ #include <avr/io.h> #include <util/delay.h> #include <stdio.h> #include <string.h> #include <avr/interrupt.h> /*----------------------------------------------------------------------------------DEFINITIONS----------------------------------------------------------------------------------------------------*/ char modem_mode[] = "AT+CNMI=2,2,0,0,0\r\n"; char modem_text[] = "AT+CMGF=1\r\n"; char modem_echo[] = "ATE0\r\n"; char modem_showsms[] = "AT+CMGL=\"ALL\"\r\n" ; char modem_deleteall[] = "AT+CMGD=1,4\r\n"; char modem_sms[] = "AT+CMGS=\"+923235514569\"\r"; char number_recv[14]; char sms_recv[20]; char sms_real[20]; char coordinates[45]; char check_number[] = "+923235514569"; char check_immob[] = "Immobilize"; char total[100]; char speed[10]; char a; int action;

Page 60 of 92

int flag = 0; int ic = 0; int l,ip; int pehla = 0; int speed1; int speed2; int iop = 0; int interupt = 0; unsigned char value,i,lati_value[15],lati_dir, longi_value[31], longi_dir, alti[5];

/*-------------------------------------------------------------------------------CONNECTION BETWEEN LCD AND ATMEGA---------------------------------------------------------------------------------*/

#define LCD_DATA PORTA // LCD data port #define ctrl PORTB #define en PB5 // enable signal #define rw PB4 // read/write signal #define rs PB3 // register select signal

/*-----------------------------------------------------------------------------------------FUNCTIONS-----------------------------------------------------------------------------------------------*/ void InitUART(unsigned char baudrate); unsigned char ReceiveByte(void); void TransmitByte(unsigned char data);

void gps(void); void getgsm(char* x); void sendgsm(char* x);

Page 61 of 92

void send_sms(char* x); void setgsm(); void smswait(char* total); void sms(); void buffer_empty(); void sms_parse(char* sms,char* number,char* total);

void LCD_cmd(unsigned char cmd); void LCD_write(unsigned char data); void LCD_string(unsigned char *disp); void init_LCD(void);

void init_timer1(); void init_interrupt0(); void init_interrupt1();

void getgpspeed(); void getsms(); /*-----------------------------------------------------------------------------------INTERRUPT ROUTINES--------------------------------------------------------------------------------------------*/

ISR(TIMER1_COMPA_vect) { cli(); iop++;

if(iop == 15) {

Page 62 of 92

getgpspeed(); speed2 = atoi(speed); PORTC = PORTC | 1; // multiplex for GSM

if(speed2>0) { LCD_cmd(0x01); LCD_string("1 minute up"); send_sms("The car is being moved without your permission"); } iop = 0; } sei(); }

ISR (INT1_vect) { interupt = interupt+1; cli();

LCD_cmd(0x01); _delay_ms(500); LCD_string("int1"); _delay_ms(1000); send_sms("ALERT"); GICR = GICR & 127; LCD_cmd(0x01); _delay_ms(500); LCD_string("Alert sent!"); _delay_ms(1000);

Page 63 of 92

sei(); }

ISR (INT0_vect) { interupt = interupt+1; cli();

LCD_cmd(0x01); _delay_ms(500); LCD_string("int0"); _delay_ms(1000); PORTC = PORTC | 4;

if(interupt == 2) { //getgpspeed(); //speed1=atoi(speed); PORTC= PORTC | 128 ; //IGNITION OFF

PORTC = PORTC | 1; // multiplex for GSM init_timer1(); init_interrupt1(); //enabling INT1 LCD_cmd(0x01); LCD_string("P1"); _delay_ms(500); }

else if(interupt == 4)

Page 64 of 92

{ TIMSK|= (0 << OCIE1A); //Disable compare interrupt routine TCCR1A = 0; TCCR1B = 0; stop the timer) // set entire TCCR1A register to 0 // same for TCCR1B(These two commands will

GICR = GICR & 127; //disabling INT1 PORTC = PORTC & 127; // ignition on 0111111 LCD_cmd(0x01); LCD_string("P0"); _delay_ms(500); interupt = 0; }

sei(); }

/*-----------------------------------------------------------------------------------MAIN FUNCTION-------------------------------------------------------------------------------------------------*/

int main(void) {

DDRC = 0xFF; init_LCD(); InitUART( 51 ); // initializing GSM

PORTC = PORTC | 1; // multiplex for GSM

Page 65 of 92

sendgsm(modem_mode); _delay_ms(500) ;

sendgsm(modem_text); _delay_ms(500) ;

sendgsm(modem_echo); _delay_ms(500); //sendgsm(modem_deleteall); //_delay_ms(500);

while(1) { LCD_cmd(0x01); LCD_string("Waiting.."); init_interrupt0(); for(ip=0; ip<100; ip++) total[ip] = NULL; for(ip=0; ip<20; ip++) { sms_real[ip] = NULL; sms_recv[ip] = NULL; }

sms(); } } /*-----------------------------------------------------------------------------------END OF MAIN FUNCTION------------------------------------------------------------------------------------------*/ /*----------------------------------------------------------------

Page 66 of 92

-------------------FUNCTION getgsm(char* x) --------------------------------------------------------------------------------------*/ void getgsm(char* x) { int z = 0; while(1) { *x = ReceiveByte(); if(*x == '\r') z = z+1; x = x+1; if(z == 2) break; } } /*----------------------------------------------------------------------------------FUNCTION sendgsm(char* x)--------------------------------------------------------------------------------------*/ void sendgsm(char* x) { int l = strlen(x); for(int p=0; p<l; p++) { TransmitByte(*x); x = x+1; } }

Page 67 of 92

/*----------------------------------------------------------------------------------FUNCTION send_sms(char* x)-------------------------------------------------------------------------------------*/

void send_sms(char* x) { sendgsm(modem_text); _delay_ms(500) ;

sendgsm(modem_sms); _delay_ms(500); sendgsm(x); _delay_ms(1000); TransmitByte(26); _delay_ms(1000); } void send_sms1() { sendgsm(modem_text); _delay_ms(500); sendgsm(modem_sms); _delay_ms(500); sendgsm(longi_value); sendgsm(lati_value); _delay_ms(500); TransmitByte(26); _delay_ms(500); } /*----------------------------------------------------------------------------------FUNCTION setgsm()----------------------------------------------------------------------------------------------*/

Page 68 of 92

void setgsm() { UBRRL = 0x19; } /*GPS coordinate calculation 3338.5756,7259.4490 38.5756/60=0.6429267, 59.4490/60=...

33+0.6429267=33.642927 */ /*----------------------------------------------------------------------------------FUNCTION smswait(char* total)----------------------------------------------------------------------------------*/ void smswait(char* total) { int i = 0, ok = 0; char a; while(1) { a = ReceiveByte(); if(a =='+') { if(ReceiveByte()=='C') { if(ReceiveByte()=='M') { if(ReceiveByte()=='T') { for(i = 0; i<200; i++) { *total = ReceiveByte(); if(*total =='\n')

Page 69 of 92

ok = ok+1;

if(ok == 2) break;

total=total+1;

// for ends here

break; } } } } } // while ends here } /*----------------------------------------------------------------------------------FUNCTION getsms() ---------------------------------------------------------------------------------------------*/ void getsms() { int co; for(co=0;co<strlen(sms_recv);co++) { if(co==(strlen(sms_recv)-3)) break; sms_real[co]=sms_recv[co+1]; }

Page 70 of 92

/*------------------------------------------------------------------------------------FUNCTION sms()-----------------------------------------------------------------------------------------------*/ void sms() { _delay_ms(500); smswait(total); sms_parse(sms_recv,number_recv,total); getsms();

if(strcmp(number_recv,check_number)==0) { if(strcmp(sms_real,check_immob)==0) { LCD_cmd(0x01); _delay_ms(10); LCD_write('A'); PORTD = PORTD | 128; send_sms("Car Locked"); LCD_string(sms_real); _delay_ms(1000); LCD_cmd(0x01); LCD_string(number_recv); _delay_ms(1000); }

else if(strcmp(sms_real,"location")==0) { gps();

Page 71 of 92

LCD_cmd(0x01); _delay_ms(10); LCD_write('B'); LCD_string(longi_value); _delay_ms(1000); PORTC = PORTC | 1; // multiplex for GSM strncat(longi_value,lati_value,11); _delay_ms(300); send_sms(longi_value); }

/*locking and unlocking through SMS*/

else if(strcmp(sms_real,"lock")==0) {

//lock

PORTC = PORTC | 128 ; //IGNITION OFF init_interrupt1(); pehla=0; LCD_cmd(0x01); LCD_string("lock-recv"); _delay_ms(500); //reply 'status' to the owner of car send_sms("Armed"); }

else if(strcmp(sms_real,"unlock")==0) {

//unlock

GICR = GICR & 127;//disabling interrup1 pehla = 1; PORTC = PORTC & 127;

Page 72 of 92

LCD_cmd(0x01); LCD_string("unlock-recv"); _delay_ms(500); send_sms("Unarmed"); } } } /*---------------------------------------------------------------------FUNCTION sms_parse(char* sms,char*number,char* total )----------------------------------------------------------------------*/ void sms_parse(char* sms,char*number,char* total ) { int x = strlen(total); int j=0,k=0,l=0,sk=0,pk=0; for(l=0; l<x; l++) { if(total[l]=='+') { j = j+1;

if(j==1) { for(k=0; k<13; k++) { *number = total[l]; l = l+1; number = number+1; } } }

Page 73 of 92

if(total[l]=='\r') { pk = pk+1; for(sk=0; sk<30; sk++) { *sms = total[l+1]; sms = sms+1; l = l+1; if(*sms=='\r') break; } } } } /*----------------------------------------------------------------------------------------FUNCTION gps() ------------------------------------------------------------------------------------------*/ void gps() { InitUART( 103 ); PORTC = PORTC & 254; // multiplex for GPS (254 = 11111110) _delay_ms(50); while(1) { value=ReceiveByte(); if(value=='$') { value=ReceiveByte(); if(value=='G')

Page 74 of 92

{ value=ReceiveByte(); if(value=='P') { value=ReceiveByte(); if(value=='G') { value=ReceiveByte(); if(value=='G') { value=ReceiveByte(); if(value=='A') { value=ReceiveByte(); if(value==',') { value=ReceiveByte(); while(value!=',') value=ReceiveByte(); lati_value[0]=ReceiveByte(); value = lati_value[0]; for(i=1; value!=','; i++) { lati_value[i]=ReceiveByte(); value = lati_value[i] lati_dir=ReceiveByte(); value=ReceiveByte(); }

while(value!=',') value=ReceiveByte();

Page 75 of 92

longi_value[0]=ReceiveByte(); value = longi_value[0]; for(i=1; value!=','; i++) { longi_value[i]=ReceiveByte(); value = longi_value[i]; } longi_dir=ReceiveByte(); _delay_ms(100); break; } } } } } } } } }

/*----------------------------------------------------------------------------------------FUNCTION getgpspeed() -----------------------------------------------------------------------------------*/ void getgpspeed() { InitUART( 103 ); PORTC = PORTC & 254; // multiplex for GPS (254 = 11111110) int count = 0;

Page 76 of 92

_delay_ms(50); // delay of 50 mili seconds while(1) { value=ReceiveByte(); if(value=='$') { value=ReceiveByte(); if(value=='G') { value=ReceiveByte(); if(value=='P') { value=ReceiveByte(); if(value=='V') { value=ReceiveByte(); if(value=='T') { value=ReceiveByte(); if(value=='G') { //LCD_string("yahan"); while(count<7) { a=ReceiveByte(); if(a==',') count=count+1; }

count=0;

Page 77 of 92

while(1) { a=ReceiveByte(); if(a!=',') speed[count]=a; count++; if(a==',') break; }

break; } } } } } } } } /*-------------------------------------------------------------------------------FUNCTION TO Initialize UART---------------------------------------------------------------------------------------*/ void InitUART( unsigned char baudrate ) { UBRRL = baudrate; /* Set the baud rate */

/* Enable UART receiver and transmitter */ UCSRB = (UCSRB | _BV(RXEN) | _BV(TXEN) ); } /*-----------------------------------------------------------------------------------FUNCTION TO READ UART-------------------------

Page 78 of 92

-----------------------------------------------------------------*/ unsigned char ReceiveByte( void ) { while ( !(UCSRA & return UDR; } /*----------------------------------------------------------------------------------FUNCTIONS TO WRITE UART----------------------------------------------------------------------------------------*/ void TransmitByte( unsigned char data ) { while ( !(UCSRA & (_BV(UDRE))) ); /* Wait for empty transmit buffer */ UDR = } /*----------------------------------------------------------------------------------------LCD CODES------------------------------------------------------------------------------------------------*/ void LCD_cmd( unsigned char cmd ) { LCD_DATA=cmd; ctrl =(0<<rs)|(0<<rw)|(1<<en); // RS and RW as LOW and EN as HIGH _delay_ms(10); ctrl =(0<<rs)|(0<<rw)|(0<<en); // RS, RW , LOW and EN as LOW _delay_ms(50); } void LCD_write( unsigned char data ) { LCD_DATA = data; ctrl = (1<<rs)|(0<<rw)|(1<<en); // RW as LOW and RS, EN as HIGH _delay_ms(10); data; /* Start transmission */ (_BV(RXC))) ); /* Wait for incoming data */

/* Return the data */

Page 79 of 92

ctrl = (1<<rs)|(0<<rw)|(0<<en); // EN and RW as LOW and RS HIGH _delay_ms(25); // delay to get things executed } void LCD_string( unsigned char *disp ) { int x; for(x=0;disp[x]!=0;x++) { LCD_write(disp[x]); _delay_ms(5); } } void init_LCD( void ) { DDRA = 0xFF; DDRB = 0xFF; LCD_cmd(0x38); // initialization of 16X2 LCD in 8bit mode _delay_ms(10); LCD_cmd(0x01); // clear LCD _delay_ms(10); LCD_cmd(0x0E); // cursor ON _delay_ms(10); LCD_cmd(0x80); // ---8 go to first line and --0 is for 0th position _delay_ms(10); } void init_interrupt0( void ) { cli(); //Disable Global Interrupts GICR = GICR | 64; //Set Bit6 of GICR to unmask INT0 interrupt.

Page 80 of 92

MCUCR = MCUCR | 3; //Configuring MCUCR for Rising Edge interrupt for INT0 sei(); //Enable Global Interrupts } void init_interrupt1( void ) { cli(); //Disable Global Interrupts GICR = GICR | 128; //Set Bit7 of GICR to unmask INT0 interrupt. MCUCR = MCUCR & 243; sei(); //Enable Global Interrupts } void init_timer1() { // initialize Timer1 cli(); TCCR1A = 0; TCCR1B = 0; // disable global interrupts // set entire TCCR1A register to 0 // same for TCCR1B

// set compare match register to desired timer count: OCR1A = 7811; /*(target time) = (timer resolution) * (# timer counts + 1) where target time is 1s ,timer resolution is (1/(8M/1024(prescaler))*/ // turn on CTC mode: TCCR1B |= (1 << WGM12); // Set CS10 and CS12 bits for 1024 prescaler: TCCR1B |= (1 << CS10); TCCR1B |= (1 << CS12); // enable timer compare interrupt: TIMSK |= (1 << OCIE1A); // enable global interrupts: sei(); }

Page 81 of 92

2- ANDROID APP SOURCE-CODE


i) FYPActivity.java
packagecar.gps; importandroid.app.Activity; importandroid.app.Dialog; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.content.IntentFilter; importandroid.media.MediaPlayer; importandroid.os.Bundle; importandroid.telephony.SmsManager; importandroid.view.Menu; importandroid.view.MenuInflater; importandroid.view.MenuItem; importandroid.view.View; importandroid.widget.ImageButton; importandroid.widget.Toast; publicclassFYPActivityextends Activity { /** Called when the activity is first created. */ final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; IntentFilterfilterz = newIntentFilter(SMS_RECEIVED); BroadcastReceiverreceiver = newIncomingSMSReceiver(); SmsManagersm = SmsManager.getDefault(); @Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); registerReceiver(receiver, filterz); finalMediaPlayermpp = MediaPlayer.create(this, car.gps.R.raw.car); finalMediaPlayermp = MediaPlayer.create(this, car.gps.R.raw.doorun); finalMediaPlayerig = MediaPlayer .create(this, car.gps.R.raw.carmp3cut); finalMediaPlayergp = MediaPlayer.create(this, car.gps.R.raw.smoke); ImageButton ignition = (ImageButton) findViewById(R.id.imageButton4); ignition.setOnClickListener(newView.OnClickListener() { publicvoidonClick(View v) { // TODO Auto-generated method stub ig.start();

Page 82 of 92

sm.sendTextMessage("+923445844031", null, "ignite", null, null); Toast.makeText(getBaseContext(), "Engine Starting", Toast.LENGTH_LONG).show(); } }); ImageButton track = (ImageButton) findViewById(R.id.imageButton1); track.setOnClickListener(newView.OnClickListener() { publicvoidonClick(View v) { // TODO Auto-generated method stub gp.start(); sm.sendTextMessage("+923445844031", null, "location", null, null); startActivity(new Intent("car.gps.map")); Toast.makeText(getBaseContext(), "Loading..", Toast.LENGTH_SHORT).show(); } }); ImageButton lock = (ImageButton) findViewById(R.id.imageButton2); lock.setOnClickListener(newView.OnClickListener() { publicvoidonClick(View v) { // TODO Auto-generated method stub mpp.start(); sm.sendTextMessage("+923445844031", null, "Immobilize", null, null); Toast.makeText(getBaseContext(), "Arming Car..Please wait", Toast.LENGTH_LONG).show(); } }); ImageButton unlock = (ImageButton) findViewById(R.id.imageButton3); unlock.setOnClickListener(newView.OnClickListener() { publicvoidonClick(View v) { // TODO Auto-generated method stub mp.start(); sm.sendTextMessage("+923445844031", null, "unlock", null, null); Toast.makeText(getBaseContext(), "Disarming Car..Please wait",

Page 83 of 92

Toast.LENGTH_LONG).show(); } }); ImageButton park = (ImageButton) findViewById(R.id.imageButton5); park.setOnClickListener(newView.OnClickListener() { publicvoidonClick(View v) { // TODO Auto-generated method stub mp.start(); sm.sendTextMessage("+923445844031", null, "park", null, null); Toast.makeText(getBaseContext(), "Activating Parking Mode", Toast.LENGTH_LONG).show(); } }); } @Override publicbooleanonOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.new_game2: Context mContext = getApplicationContext(); Dialog dialog = newDialog(mContext); // dialog.setContentView(R.layout.custom_dialog); dialog.setTitle("ABOUT"); dialog.show(); returntrue; default: returnsuper.onOptionsItemSelected(item); } } @Override publicbooleanonCreateOptionsMenu(Menu menu) { MenuInflaterinflater = getMenuInflater(); inflater.inflate(R.menu.menubutton2, menu); returntrue; } @Override protectedvoidonResume() { // TODO Auto-generated method stub super.onResume(); } }

Page 84 of 92

ii) IncomingSMSReceiver.java
packagecar.gps; importjava.io.IOException; importandroid.app.AlertDialog; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.DialogInterface; importandroid.content.Intent; importandroid.media.MediaPlayer; importandroid.os.Bundle; importandroid.telephony.SmsMessage; importandroid.util.Log; publicclassIncomingSMSReceiverextendsBroadcastReceiver { privatestaticfinal String Alarmstring privatestaticfinal String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; String num = ""; String msg = ""; publicvoidonReceive(Context _context,Intent _intent){ if (_intent.getAction().equals(SMS_RECEIVED)) { Bundle bundle = _intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = newSmsMessage[pdus.length]; for (int i = 0; i <pdus.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); num = messages[i].getOriginatingAddress(); } for (SmsMessage message : messages) { String msg = message.getMessageBody(); Log.d("sms", msg); if(num.equals("+923445844031")){ if (msg.toLowerCase().startsWith("c")) { AlertDialog.Builder builder = newAlertDialog.Builder(_context); = "$";

Page 85 of 92

builder.setMessage("Your Car has been Armed").setCancelable(false).setNeutralButton("OK", newDialogInterface.OnClickListener() { publicvoidonClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); AlertDialog alert = builder.create(); alert.show(); }

elseif (msg.toLowerCase().startsWith(Alarmstring)) { //distress signal MediaPlayermPlayer = MediaPlayer.create(_context,car.gps.R.raw.caralarm); try { mPlayer.prepare(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mPlayer.start(); } elseif (msg.toLowerCase().startsWith("p")) { AlertDialog.Builder builder = newAlertDialog.Builder(_context); builder.setMessage("Parking Mode Activated!").setCancelable(false).setNeutralButton("OK", newDialogInterface.OnClickListener() { publicvoidonClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } });

Page 86 of 92

AlertDialog alert = builder.create(); alert.show(); } } } } } } }

iii) Map.java
packagecar.gps; importjava.util.ArrayList; importjava.util.List; importcom.google.android.maps.*; importandroid.content.BroadcastReceiver; importandroid.content.Context; importandroid.content.Intent; importandroid.content.IntentFilter; importandroid.graphics.Canvas; importandroid.graphics.drawable.Drawable; importandroid.location.Location; importandroid.location.LocationListener; importandroid.os.Bundle; importandroid.telephony.SmsManager; importandroid.telephony.SmsMessage; importandroid.util.Log; importandroid.view.Menu; importandroid.view.MenuInflater; importandroid.view.MenuItem; importandroid.widget.Toast; public class Map extends MapActivity implements LocationListener { final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED"; MapViewmapView = null; SmsManagersms = SmsManager.getDefault(); MapControllermapCtrl = null; String number = ""; Location L; GeoPoint point = new GeoPoint(33716667, 73066667); // 19240000,-99120000 // 07259.4490,3338.5756,

Page 87 of 92

IntentFilter filter = new IntentFilter(SMS_RECEIVED); BroadcastReceiverSMSReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if (intent.getAction().equals(SMS_RECEIVED)) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i <pdus.length; i++) { messages[i] = SmsMessage .createFromPdu((byte[]) pdus[i]); number = messages[i].getOriginatingAddress(); } for (SmsMessage message : messages) { String msg = message.getMessageBody(); if (msg.toLowerCase().startsWith("0")) { Toast.makeText(context, "Updating..", Toast.LENGTH_SHORT).show(); char buffer[] = { '0', '0', '0', '0', '0', '0', '0', '0', '0' }; char buffer2[] = { '0', '0', '0', '0', '0', '0', '0', '0', '0' }; msg.getChars(1, 10, buffer, 0); msg.getChars(11, 20, buffer2, 0); Log.d("extracted1", String.valueOf(buffer)); Log.d("extracted2", String.valueOf(buffer2)); double x, y, i,j;

Page 88 of 92

int m, n,a,b,c,d; String buf, buf2; buf = String.valueOf(buffer, 0, 9); x = Double.parseDouble(String.valueOf(buf)); i = x % 100; i = i/60; i = i*1000000; n = (int) i; m = (int) x/100; m = m*1000000; d = m+n;

buf2 = String.valueOf(buffer2, 0, 9); y = Double.parseDouble(String.valueOf(buf2)); j = y % 100; j = j/60; j = j*1000000; a = (int) j; b = (int) y/100; b = b*1000000; c = a+b;

point = new GeoPoint(c, d); mapCtrl.animateTo(point); placeMarker(c, d); mapCtrl.setZoom(16); } } } } } }; @Override protected void onCreate(Bundle icicle) { // TODO Auto-generated method stub super.onCreate(icicle); setContentView(R.layout.map); mapView = (MapView) findViewById(R.id.mapview); mapCtrl = mapView.getController();

Page 89 of 92

mapView.setBuiltInZoomControls(true); registerReceiver(SMSReceiver, filter); } @Override protectedbooleanisRouteDisplayed() { // TODO Auto-generated method stub return false; } private void placeMarker(intmarkerLatitude, intmarkerLongitude) { Drawable marker = getResources().getDrawable(R.drawable.marker); marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight()); mapView.getOverlays().add( newInterestingLocations(marker, markerLatitude, markerLongitude)); } classInterestingLocations extends ItemizedOverlay<OverlayItem> { private List<OverlayItem> locations = new ArrayList<OverlayItem>(); privateDrawable marker; publicInterestingLocations(DrawabledefaultMarker, int LatitudeE6, int LongitudeE6) { super(defaultMarker); // TODO Auto-generated constructor stub this.marker = defaultMarker; // create locations of interest GeoPointmyPlace = new GeoPoint(LatitudeE6, LongitudeE6); locations.add(new OverlayItem(myPlace, "My Place", "My Place")); populate(); } @Override protectedOverlayItemcreateItem(int arg0) { // TODO Auto-generated method stub returnlocations.get(arg0); } @Override publicint size() { // TODO Auto-generated method stub returnlocations.size(); } @Override public void draw(Canvas canvas, MapViewmapView, boolean shadow) { // TODO Auto-generated method stub

Page 90 of 92

super.draw(canvas, mapView, shadow); boundCenterBottom(marker); } } public void onLocationChanged(Location arg0) { // TODO Auto-generated method stub } public void onProviderDisabled(String arg0) { // TODO Auto-generated method stub } public void onProviderEnabled(String arg0) { // TODO Auto-generated method stub } public void onStatusChanged(String arg0, int arg1, Bundle arg2) { // TODO Auto-generated method stub } @Override publicbooleanonOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { caseR.id.new_game: sms.sendTextMessage("+923445844031", null, "location", null, null); return true; default: returnsuper.onOptionsItemSelected(item); } } @Override publicbooleanonCreateOptionsMenu(Menu menu) { MenuInflaterinflater = getMenuInflater(); inflater.inflate(R.menu.menubutton, menu); return true; } }

Page 91 of 92

Page 92 of 92

Vous aimerez peut-être aussi