You are on page 1of 101

Vehicle Accident Automatic Reporter/Responder

1.4

List of Definitions (PDA) - a handheld device that combines

Personal digital assistant

computing, telephone/fax, Internet and networking features. A typical PDA can function as a cellular phone, fax sender, web browser and personal organizer. Global positioning system (GPS) - a worldwide satellite navigational system formed by 24 satellites orbiting the earth and their corresponding receivers on the earth. The GPS satellites continuously transmit digital radio signals that contain data on the satellites location and the exact time to the earth-bound receivers. From this data the receiver unit can calculate its location. Accelerometer - an instrument or device for measuring the change in acceleration. On-Star - commercial accident detection and remote vehicle locator installed on some General Motors vehicles. SR-232 serial port - A data port/connection standard that is usually used to connect modems and mice. Evaluation board - An integrated circuit used to simplify making connections to the accelerometer

iv

but not every vehicle on the road is equipped to notify authorities in case of an emergency. Follow-on work might focus on implementing such features. o Output is fed into the processing unit by USB serial link • Processing/Reporting o A processing unit (a laptop computer in this prototype) takes input from the detection and positioning units. Also. assumptions and limitations. who can notify emergency response teams. o Output is fed into the processing unit by RS-232 serial link • Positioning o A GPS unit monitors the position of the vehicle.1 Executive Summary A vehicle collision can occur at any time. universal solution that allows any . dedicated system. this position is included in an accident report to an operator.Introductory Materials The introductory materials contains the project abstract. 1 The Vehicle Accident Automatic Responder/Reporter is a portable. due to cost and scheduling limitations. 2. vehicle to notify a response team if necessary. Systems like OnStar are proprietary and are installed only in certain vehicles. operating environment.Abstract. generates an accident report Currently. acknowledgements. In the instance of a collision. Time spent during group activities was divided among research and development of the following units: • Detection o An accelerometer detects deceleration sufficient in magnitude to assume that it was produced by a collision. problem statement. the prototype does not support cellular communication. and expected end product and other deliverables. the processing unit would ideally be a smaller. intended users and uses. such as a PDA or a microcontroller circuit.

3 Problem Statement General Motors (GM) introduced the first Cadillac equipped with the On-Star system in 1996. including automatic accident detection and response and manual aid request. a communications device automatically notifies a call station of the accident and relays the position of the car.2.2 Acknowledgement The design team would like to thank our faculty advisors. 2. In addition to automatic detection.3. If the acceleration is greater than the set threshold. The unit is available as an after-market purchase and adaptable to all vehicle makes and models. obtained via GPS. it allows the user to manually request assistance. Therefore. 2 . 2. 2. nearly all GM models offer the technology as a factory-installed option. The final unit is a stand alone system that automatically detects an accident and relays the cars location through a communications device to a designated call center. The problem is that the On-Star system is limited to GM vehicles as a factory-installed option. Randall Geiger. Using this information.2 General Solution Approach The system utilizes an accelerometer to sense rapid acceleration in two axes. the technology is limited to those wishing to purchase a new GM vehicle. the call station operator can determine the response needs. Dr. Srikanta Tirthapura and Dr. Since then. to the call station operator.3. They have greatly assisted our team by donating their time and technical advice. Their support is appreciated. The On-Star system has a variety of functions.1 General Problem Statement Vehicle accidents can occur at any time and can involve any type of vehicle.

2. The components are also exposed to vibrations from the car and sudden jarring from a rough road or collision. 2.5 Intended Users and Uses The following two sections include information about the intended uses and users for the Vehicle Accident Automatic Reporter/Responder.4 Operating Environment The end product is mounted inside a motor vehicle and thereby exposed to partially controlled environment. but is susceptible to extreme temperatures and humidity. Normal operating temperatures are between -30 º F and 200 º F along with any range of relative humidity.5. The product is sheltered from high winds. and precipitation. direct sunlight.Figure 2-1 Component Layout 2. The unit is exposed to dirt and dust particles found within the vehicle.1 Intended Users The Vehicle Accident Automatic Reporter/Responder was developed for any vehicle owner or operator needing prompt assistance and emergency response 3 .

USB. Wireless MODEMs like other MODEM devices use serial communication to interface with and need Hayes compatible AT commands for communication with the computer (any microprocessor or microcontroller system). These are manufactured for specific cellular network (GSM/UMTS/CDMA) or specific cellular data standard (GSM/UMTS/GPRS/EDGE/HSDPA) or technology (GPS/SIM).GSM/GPRS module consists of a GSM/GPRS modem assembled together with power supply circuit and communication interfaces (like RS-232. Global System for Mobile communication (GSM) is an architecture used for mobile communication in most of the countries. for establishing communication between the cellular network and the computer.GSM/GPRS module is used to establish communication between a computer and a GSMGPRS system. . Global Packet Radio Service (GPRS) is an extension of GSM that enables higher data transmission rate. The MODEM is the soul of such modules. etc) for computer. Wireless MODEMs Wireless MODEMs are the MODEM devices that generate. transmit or decode data from a cellular network.

. add. Read. send or delete SMS messages in a SIM. 3. These commands are sent by the controller/processor. Also they have IMEI (International Mobile Equipment Identity) number similar to mobile phones for their identification.GSM/GPRS MODEM GSM/GPRS MODEM is a class of wireless MODEM devices that are designed for communication of a computer with the GSM and GPRS network. for interacting with processor or controller. search phonebook entries of the SIM. Make.. Receive. The MODEM sends back a result after it receives a command. GSM/GPRS Module A GSM/GPRS module assembles a GSM/GPRS modem with standard communication interfaces like RS-232 (Serial Port). It requires a SIM (Subscriber Identity Module) card just like mobile phones to activate communication with the network. USB etc. A GSM/GPRS MODEM can perform the following operations: 1. Receive. The MODEM needs AT commands. 2. The power supply circuit is also built in the module that can be activated by using a suitable adaptor. Different AT commands supported by the MODEM can be sent by the processor/controller/computer to interact with the GSM and GPRS cellular network. so that it can be easily interfaced with a computer or a microprocessor / microcontroller based system. or reject a voice call. which are communicated through serial communication.

How GSM/GPRS Works Mobile Termination is interfaced with the GSM mobile network and is controlled by a baseband processor. A mobile phone comprises of Mobile Termination. Terminal Equipment and Terminal Adapter. signaling and other network related tasks. speech encoding and decoding. . The communication with the network in a GSM/GPRS mobile is carried out by the baseband processor. The Terminal Adapter establishes communication between the Terminal Equipment and the Mobile Termination using AT commands. screen. phone memory and other hardware and software services embedded into the handset. Modem Mobile Station (Cell phones and SIM) A mobile phone and Subscriber Identity Module (SIM) together form a mobile station. The Terminal Equipment is an application processor that deals with handling operations related to keypad. It is the user equipment that communicates with the mobile network. It handles access to SIM.GSM/GPR S Module.

AT Commands AT commands are used to control MODEMs. These are mainly employed for computer based SMS and MMS services. The dial up and wireless MODEMs (devices that involve machine to machine communication) need AT commands to interact with a computer. This is followed by a Result Code. 5. The Hayes subset commands are called the basic commands and the commands specific to a GSM network are called extended AT commands. Information response and Result Codes: The AT commands are sent by the computer to the MODEM/ mobile phone. The GSM/GPRS module. but it may or may not support AT commands from the computer or an external processor/controller. always needs a computer or external processor/controller to receive AT commands from. These commands come from Hayes commands that were used by the Hayes smart modems. The Hayes commands started with AT to indicate the attention from the MODEM. on the other hand.e. . but the computer to which module is connected is the interface between user and network. The mobile handset can also be equipped with a USB interface to connect with a computer. 2. GSM/GPRS module itself does not provide any interface between the user and the network. An advantage that GSM/GPRS modules offer is that they support concatenated SMS which may not be supported in some GSM mobile handsets. Fax services. along with other extended AT commands. Also some mobile handsets can’t receive MMS when connected to a computer. AT commands with a GSM/GPRS MODEM or mobile phone can be used to access following information and services: 1. They can feature all the functionalities of a mobile phone through computer like making and receiving calls. The MODEM sends back an Information Response i. MMS services. the information requested by or pertaining to the action initiated by the AT command. Information and configuration pertaining to mobile device or MODEM and SIM card. AT is the abbreviation for Attention.Difference between GSM mobile and GSM/GPRS module A GSM mobile is a complete system in itself with embedded processors that are dedicated to provide an interface between the user and the mobile network. The AT commands are served between the processors of the mobile termination and the terminal equipment. SMS services. MMS etc. Data and Voice link over mobile network. Applications of GSM/GPRS module The GSM/GPRS module demonstrates the use of AT commands. 3. SMS. These include the Hayes command set as a subset. Command. 4. The result code tells about the successful execution of that command.

E There are also unsolicited Result Codes that are returned automatically by the MODEM to notify the occurrence of an event. Single Command The AT commands include a prefix AT which indicates the beginning of the command to MODEM. . However some MODEMs and mobile phones allow both uppercase and small case letters. For example the reception of a SMS will force MODEM to return an unsolicited result code. AT commands' syntax Case Sensitivity The AT commands are generally used in uppercase letters. and a carriage return which indicates the end of the command.

For example: AT+CGMI. For example: AT+CGMI<Carriage return> Command Line Multiple AT commands can be sent to MODEM in a single command line. The extended AT commands have a ‘+’ in the command name. have a carriage return and line feed in the beginning as well as at the end. returned by the MODEM.Using a Single AT Command However string ‘AT’ itself is not the part of the command. For example in ATD. . For example: AT+CGML=”ALL”<Carriage return> Information Response and Result Code – The Information Response and Result Codes. The commands in a line are separated by a semi-colon (.). +CBS<Carriage return> String in Command Line Strings in a command line are enclosed in double quotes. D is the command name not ATD.

For example: <Carriage return><Line feed>OK<Carriage return><Line feed> <Carriage return><Line feed>ERROR<Carriage return><Line feed> <Carriage return><Line feed>+CBC: 0. the command appearing first is executed first. Sequence of Execution In the command line. Different Result Codes: RESULT CODE DESCRIPTION OK Successful Execution of a command ERROR Execution of a command failed +CMS ERROR Message service failure. 60<Carriage return><Line feed> etc. The execution then follows for second appeared command and so on. Types of commands: There are four types of AT commands: Test commands Read commands Set commands Execution commands For more details. an error result code is returned by the MODEM and the execution of the command line is terminated irrespective of presence of other commands next in the command line. The execution of commands in a command line takes place in sequential manner. If an error occurs in the execution of a command. is returned with an error code Unsolicited Result Codes +CDS Notify receipt of SMS status report of a new message to computer +CDSI Notify receipt of SMS status report of a new message and its location in memory to computer +CMT Notify forwarding of a new SMS to computer +CMTI Notify receipt of SMS status report of a new message and its location in memory to computer 1) 2) 3) 4) . see AT Commands.

Set parameters. parity bit as none.2 Intended Uses Upon completion. stop bit as 1 and data bit as 8. Insert a SIM card in the module. The interfacing of the GSM/GPRS module with the serial port of the computer involves following steps: 1) 2) 3) 4) Connect RS-232 port of GSM module with the serial port of the computer. and Limitations for the .5. the Vehicle Accident Automatic Reporter/Responder: • Automatically detects when an accident has occurred • Automatically notifies call center of accident • Sends the location of the vehicle to the call center • Allows for manual aid request technician to install and 2.6 Assumption and Limitations The two following sections are lists of the Assumptions project.Interfacing MODEM/Mobile phone with Windows platform The Windows (XP and lower versions) comes with an application called HyperTerminal for data communication through serial port of the computer. 2. 5) Create a new connection set on HyperTerminal. handshaking mode as none. Enter a name for the connection and press OK. Now select the communication port (COM) at which GSM module is connected. in the event of an emergency. like baud rate as 9600. Open HyperTerminal from Start -> All Programs -> Accessories -> Communications > HyperTerminal. The complexity of the unit requires a trained maintain the system.

2.6.1 Updated Assumptions List The following assumptions were made when determining design: • The unit will not be exposed to any direct liquid spills • Any accident must produce an acceleration of at least 6 g’s to be detected • The acceleration/deceleration must be in the horizontal plane of the car the product plan and

Figure 2-2 Impact Directions Requirements

4

2.6.2 Updated Limitations List The following limitations were taken into consideration: • The complete end-product must not weigh more than one pound • The unit must be no larger than one cubic foot for easy storage within the car • The power supply must be taken from the car’s battery • All systems must be contained within the units encasement 2.7 Expected End Product and Other Deliverables The end product of the device is a completed vehicle accident reporting unit. The components of the finished product are as follows: Accelerometer circuit - The accelerometer was shipped as an integrated circuit mounted on an evaluation board. detector Input processing program GPS unit. An integral part of the project development involved writing a program to accept input from the accelerometer circuit and Using the information obtained, the program generates an accident report and notifies a call center. Prototype unit - The completed prototype unit includes the individual components assembled into one cohesive unit. device. Essentially, it is a black-box The output pins wired to a female RS-232 serial connector for input into a computer. In this model leaf switch as Accident

Section 3 - Project Approach and Results
Section 3 contains detailed explanation of the approach and results of this project. The approach used in solving design problems will be explained thoroughly. In addition, the results of the approached used will be given in detail.

5

3.1 End Product Functional Requirements The system meets the requirements listed below. Detect analyze and control: The main goal of the system is to detect the

change of speed in the car and analyze the data to determine whether it is above a set threshold or not. The accelerometer output is fed into a computer, after which the data processing program decides how to act upon it. Software integration: After the accident is detected, the software developed by the team for this project integrates the components of the system to achieve the desired results. Specifically, it reads the accelerometer output via the RS-232 serial port. If that data indicates an accident, the software reads positional data from the GPS receiver, generates SMS, and sends it to the response center. Internet Access: The system connects to the internet using wireless Ethernet. This is for prototyping purposes; the original idea was to use a cellular modem, but due to cost constraints, the group settled for wireless Ethernet. Call center notification: Using wireless internet, the system establishes a

connection with a call center to notify a response technician. 3.2 Design Constraints

The following are constraints the system will need to meet to ensure that the system will operate effectively. Durability: The completed end-product can withstand temperatures ranging from between -30 º F and 200 º F along with any range of relative humidity. sudden acceleration changes due to an accident. The endproduct can also withstand vibrations from the road and from the car and

6

independent of car make and model o Easy way to determine whether or not car has been involved in collision 7 . and the software. The other option was to use an accelerometer. the MCU PCB. the team was unable to meet the size requirements recorded in the design document.Size: Since the end prototype includes a laptop computer. Cost Effective Design: between 11000 RS. One idea was to try to use an inductor to detect the presence of electrical current in the airbag system to trigger the automatic reporting process. Adding up the cost of the . the entire unit SensorTechnology Two ideas evolved as possible sensing methods. likely more sensitive than airbag sensor Easier to install. The pros and cons are listed below: • Airbag Sensor o Pros: ♣ o Cons ♣ ♣ ♣ • More difficult installation than accelerometer Depends on proper functionality of airbag(s) Restricts accident reporting capability to owners of cars with airbags Accelerometer o Pros: ♣ ♣ Cons: Reliable. Exchanging the computer for a PDA. 3. however. would cost the GPS receiver. would shrink the end-product to under one cubic foot in size and a weight of no more than three pounds.3 Approaches Considered and One Used The system is affordable.

whereas a cell phone could serve double-duty as a communications unit and positioning unit • Cellular Triangulation o Pros ♣ ♣ o Cons ♣ ♣ Slower and less accurate Potential for lost cellular signal may inhibit triangulation Less expensive than GPS Requires less hardware Faster and more accurate than cellular triangulation o Another option The pros and cons associated with each are listed The group chose GPS as the positioning unit of choice for reliability and accuracy. below: • Global Positioning System o Pros ♣ Cons ♣ ♣ GPS units more expensive than cell phones Requires additional hardware. was cellular triangulation. Postitioning Technology For positioning units. 8 . despite the additional hardware and higher cost.♣ ♣ More likely to report a smaller accident. software will have to account for this More complex circuitry required to interface with computer The group decided that an accelerometer would be a better choice for the purpose of reliability and portability. the group instinctively considered GPS.

headset.Communications Technology For communications technology. • E-mail through Cellular Modem o Pros ♣ Cons ♣ ♣ • o Pros ♣ ♣ o Cons ♣ ♣ • Requires additional hardware such as a car speakerphone system. also. which lends itself to the risk of losing the cellular signal and the cost of cellular service. or other such device Difficult to directly manipulate a cell phone to dial numbers or self-initiate speed dial Text (SMS) Message o Pros ♣ Cons ♣ Even more difficult to directly manipulate a cell phone to send text messages Easy to generate a message with accident location o Allows direct communication between vehicle and call center operator Enables operator to gauge accident severity (see Executive Summary) Call center would require a program that constantly monitors incoming e-mail. e-mails may get lost Cellular Phone Call Easy to generate an e-mail message with accident location o 9 . which may not be very efficient Relies on internet connectivity. the group looked at using a cellular modem to connect to the internet or directly manipulate a cell phone to place a phone call or send a text (SMS) message. Universal cons associated with each method are that they all require cellular service.

Circuit diagram .The group decided to use the email through wireless ethernet because the other choices are beyond the scope of the project and would be very difficult to implement. which then relays the information to the call center through the communications system. and a communications system. and functions are specified in the next section. a data processing.4 Detailed Design The end product design consists of an accident sensing unit. a tracking system. including parts lists. The sensing and tracking units send information to the data processor. prices. 3. A detailed description of each component.

The evaluation board is part of the entire EK3L02DQ evaluation kit which contains the evaluation board and the software to make it work properly. The acceleration data is communicated from the board to the external host through an RS232/UART standard interface connection. part number LIS3L02DQ. The accelerometer. The team decided to use an accelerometer produced by STMicroelectronics and an evaluation board produced by the same manufacturer.Accident Sensing Unit in real time Vehicle The detection unit consists of a 2g three axis accelerometer with digital output in conjunction with an evaluation kit. 10 . The software then collects the data by either snapshot acceleration data acquisition or continuous acceleration data acquisition from a register inside the acceleration sensor. allows the detection of acceleration in all three axis in a 2g scale. This accelerometer is then mounted in the evaluation board for easy data acquisition.

Table 3-1 Accelerometer Pin Description Figure 3-2 Accelerometer Pin Connection 11 .

12 .

Table 3-1 Accelerometer Electrical Characteristics Figure 3-4 Accelerometer Block Diagram Part Part Number Price Supplier Accelerometer LIS3L02DQ 15000rs Digi-Key Combined Evaluation Kit EK3L02DQ Table 3-2 Parts List Tracking System The tracking system consists of a GPS unit that tracks the location of the vehicle using satellite signals. The information from the GPS is transmitted to the MCU via RS232 13 .

Processing Station The processing unit is PIC microcontroller based circuit data sensing unit from via the serial the port. 3. the bulk of the implementation process was spent in researching parts and materials. 14 . In the event of an accident. retrieves the vehicles location from the GPS unit. GPS unit. so combing all parts into one unit was relatively easy. Communications Unit To communicate the position and acceleration data to the response center. and connection routes to the computer. Many hours were spent finding a suitable accelerometer. This . This gave the team a working knowledge of each component. After acquiring the proper equipment. the team decided to use the wireless internet on campus to send an electronic message to the center. each part was connected to the computer and ran on an individual basis.5 Implementation Process Description Research and Implementation In order to achieve the proper design. The PIC receives information is processed by a data processing program. The extra time spent on research paid off greatly in the implementation process. and generates and sends SMS to the response center. this program reads the output from the accelerometer.. Below is a list of the unit’s components and the materials used for each.

• RS232 interfacing was more difficult than expected.Component Accident Sensing Acelerometer Evaluation Kit Tracking Communications Table 3-2 Parts List Problems Encountered • Parts Used LIS3L02DQ EK3L02DQ USB GPS device Computer Connection Standard serial connection with accompanying data collecting software. USB connection ISU wireless internet N/A Writing a program to allow all the components to speak with each other proved far more difficult than first imagined. Bench Test: • The team tested the accelerometer and its software by utilizing a laptop computer and shaking it to determine how it responds to accelerations. This problem was solved by further research into the individual components software output. 3.6 End-Product Testing Description The following are methods the team used to test the end-product. Interface GPS significantly better in pic have • Trouble reading GSM output file: the formatting and timing of the output presented a programming challenge. 15 .

and pressing the leaf switch. components Prototype Test: The prototype testing consisted of connecting the leaf switch and GPS receiver to the MCU. The response threshold was set low intentionally so that the response could be triggered by the force that a human can exert. write an SMS to a group member.• The team tested the GPS using a laptop to the accuracy of its output using the supplied software.7 Project End Results The group tested SMS functionality by having the program The project’s end result was a working prototype that correctly to of The identified a the correct an response unit accident. center. The accident sensing unit correctly identified the and sent a signal to the computer through the serial location of the vehicle was determined from the GPS . 3. and relayed the information acceleration connection. tracked the vehicles location. check • The team tested communication of all of the and the software using a laptop RS-232 serial port connection.

5. Micro controller Section. C2 and C5are used to remove the EMI noises. 3. Power Supply Regulation Stage. The primary resistance of the transformer is about 700 ohms. COMPONENT LEVEL WORKING PRINCIPLE 1. By this capacitor D. secondary resistance is about 4 ohms.C mains supply into 12 volts A. LCD Display Section.unit program and program contained and written relayed by to the the sent the team GPS an location to computer through the RS232 connection. 2. . Power Supply Section:. These are used to filter the unregulated D. 4.C into 12 volt D. 12 volt A. The current handling capacity of this diode is 1 amps and voltage handling capacity is 1000 volts. Power Supply Section 2.e. .C supply. These 8 diodes are used rectifier the low voltage i. which unit’s for emergency response.Two transformers are used in this section to powering the Micro Controller section and Relay Driving. Capacitors are 10MFD25 volt.This section is 8 bridge rectifier diode D1 to D8 identification No is 1N4007. This two transformers are used to step down the 220 volts A. 1.C C1and C4 1000mf 25 volt electrolyte capacitor.C voltage. Power Supply Regulation Stage: .C ripples are removed. Current handling capacity of the transformer is 500 ma. Sensor section. The electronic message to the response center. The main gather all the data correctly analyzed the acceleration gathered then the data when the accident threshold was reached.

D-eight 10-bit A/D channels.The PIC16f877a is a 40-pin popular PIC microcontroller. On-chip USART. 33 bidirectional I/O pins. Micro Controller Section:. Capture. 78 means positive end regulations 05 stands for 5 volt regulation. C3 and C6 are used to as final filter capacitors values are 10MFD25 volt 3. 14 interrupt sources. Current carrying capacity of this IC is 1 amps. The identification of IC1 and IC 2 are 7805. 368 x 8 Ram data memory. . 256 x 8 bytes of EEPROM data memory.C power. Watchdog timer. compare and PWM modules.IC 1 and IC 2 are used to regulate the unregulated D. Two 8-bit and one 16-bit timer. The device offers the following features: 8K x 14 words flash program memory.

Setting TRISA bit (= 1) will make the corresponding PORTA pin an input (i.2.2PORTA AND THE TRISA REGISTER PORTA is a 6-bit wide. bi-directional port. whereas writing to it will write to the port latch. that pin may not be used as a general purpose I/O pin. a write to a port implies that the port pins are read.2..e. In general.2. All write operations are read-modify-write operations. The corresponding data direction register is TRISA. put the corresponding output driver in a HiImpedance mode). Therefore. .1I/O PORTS Some pins for these I/O ports are multiplexed with an alternate function for the peripheral features on the device.. Reading the PORTA register reads the status of the pins. 2.e. when a peripheral is enabled. put the contents of the output latch on the selected pin).Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output (i.1 HARD WARE CONFIGURATION 2. the value is modified and then written to the port data latch.

RP1. The TRISA register controls the direction of the RA pins. 2. clearing output data latches BSF STATUS.3INITIALIZING PORTA BCF STATUS. Select Bank 1 . even when they are being used as analog inputs. Other PORTA pins are Multiplexed with analog inputs and analog VREF input. RP0.Pin RA4 is multi-plexed with the Timer0 module clock input to become the RA4/T0CKI pin. The user must ensure the bits in the TRISA register are Maintained set when using them as analog inputs. BCF STATUS. RP0. Initialize PORTA by. The RA4/T0CKI pin is a Schmitt Trigger input and an open drain output. All other PORTA pins have TTL input levels and full CMOS output drivers. Bank0 CLRF PORTA.2. The operation of each pin is selected by clearing/setting the control bits in the ADCON 1 register (A /D control Register1).

Set RA<3:0> as inputs. Output is open drain type. 2.4PORTA FUNCTIONS RA0/AN0 bit0 TTL Input/output or analog input. RA<5:4> as outputs TRISA<7:6>are always read as '0'. RA1/AN1 bit1 TTL Input/output or analog input. ST = Schmitt Trigger input 2.2. Legend: TTL = TTL input. RA3/AN3/VREF bit3 TTL Input/output or analog input or VREF.5PORTB AND THE TRISB REGISTER . Value used to initialize data Directions MOVWF TRISA. as digital inputs MOVLW 0xCF. RA4/T0CKI bit4 ST Input/output or external clock input for Timer0.2.MOVLW 0x06. Configure all pins MOVWF ADCON1. RA2/AN2 bit2 TTL Input/output or analog input. RA5/SS/AN4 bit5 TTL Input/output or slave select input for synchronous serial port or analog input.

RB6/PGC and RB7/PGD.. The alternate functions of these pins are described in the Special Features Section. Four of the PORTB pins.PORTB is an 8-bit wide.change comparison). Three pins of PORTB are multiplexed with the Low Voltage Programming function: RB3/PGM. RB7:RB4. Setting a TRISB bit (= 1) will make the corresponding PORTB pin an input (i. A single control bit can turn on all the pull-ups. . bi-directional port. Clearing a TRISB bit (= 0) will make the corresponding PORTB pin an output (i.e. The pull-ups are disabled on a Power-on Reset.e. The weak pull-up is automatically turned off when the port pin is configured as an output. The corresponding data direction register is TRISB.. This is performed by clearing bit RBPU OPTION_REG<7>). have an interrupt on-Change feature. anyRB7:RB4 pin configured as an output is excluded from the interrupt on. The input pins (of RB7:RB4) are compared with the old value latched on the last read of PORTB.. put the corresponding output driver in a Hi-Impedance mode). The "mismatch" outputs of RB7:RB4 are OR'ed together to generate the RB Port Change Interrupt with flag bit RBIF INTCON<0>). Each of the PORTB pins has a weak internal pull-up.e. Only pins configured as inputs can cause this interrupt to occur (i. put the contents of the output latch on the selected pin).

The user. can clear the interrupt in the following manner: a) Any read or write of PORTB. b) Clear flag bit RBIF. together with software configurable pullups on these four pins allow easy interface to a keypad and make it possible for wake-up on key depression. A mismatch condition will continue to set flag bit RBIF. . Internal software programmable weak pull-up. This interrupt-on-mismatch feature.This interrupt can wake the device from SLEEP. Internal software programmable weak pullup. Option REG<6>). in the Interrupt Service Routine. RB0/INT bit0 TTL/ST (1) Input/output pin or external interrupt input. Internal software programmable weak pullup. RB0/INT is an external interrupt input pin and is configured using the intedg bit. RB1 bit1 TTL Input/output pin. Polling of PORTB is not recommended while using the interrupt-on-change feature. The interrupt-on-change feature is recommended for wake-up on key depression operation and operations where PORTB is only used for the interrupt-on-change feature. This will end the mismatch condition. RB2 bit2 TTL Input/output pin. Reading PORTB will end the mismatch condition and allow flag bit RBIF to be cleared.

2) This buffer is a Schmitt Trigger input when used in Serial Programming mode. .RB3/PGM (3) bit3 TTL Input/output pin or programming pin in LVP mode. RB6/PGC bit6 TTL/ST(2) Input/output pin (with interrupt-on-change) or InCircuit Debugger pin. Internal software programmable weak pull-up. Internal software programmable weak pull-up. Serial programming clock. Internal software programmable weak pull-up.RB7/PGD bit7 TTL/ST (2) Input/output pin (with interrupt-on-change) or In-Circuit Debugger pin. Internal software programmable weak pull-up. Internal software programmable weak pull-up. ST = Schmitt Trigger input Note: 1) This buffer is a Schmitt Trigger input when configured as the external interrupt. Legend: TTL = TTL input. Serial programming data. RB5 bit5 TTL Input/output pin (with interrupt-on-change). RB4 bit4 TTL Input/output pin (with interrupt-on-change).

3) Low Voltage ICSP Programming (LVP) is enabled by default. which disables the RB3 I/O function. . LVP must be disabled to enable RB3 as an I/O pin and allow maximum compatibility to the other 28-pin and 40pin mid-range devices.

or with SMBus levels by using the CKE bit SSPSTAT<6>). When enabling peripheral functions. Setting a TRISC bit (= 1) will make the corresponding PORTC pin an input (i. care should be taken in defining TRIS bits for each PORTC pin. Clearing a TRISC bit=0) will make the corresponding PORTC pin an output (i.e. should be avoided. put the corresponding output driver in a Hi-Impedance mode)..2. read-modify. the PORTC<4:3> pins can be configured with normal I2C levels.6PORTC AND THE TRISC REGISTER PORTC is an 8-bit wide. write instructions (BSF.e. When the I2C module is enabled. . Some peripherals override the TRIS bit to make a pin an output. The corresponding data direction register is TRISC. put the contents of the output latch on the selected pin). PORTC pins have Schmitt Trigger input buffers.2. bi-directional port.. while other peripherals override the TRIS bit to make a pin an input. PORTC is multiplexed with several peripheral functions. BCF. Since the TRIS bit override is in effect while the peripheral is enabled. XORWF) with TRISC as destination.

2. RC5/SDO bit5 ST Input/output port pin or Synchronous Serial Port data output. RC4/SDI/SDA bit4 ST RC4 can also be the SPI Data In (SPI mode) or data I/O (I2C mode).2.RC0/T1OSO/T1CKI bit0 ST Input/output port pin or Timer1 oscillator output/Timer1 clock input. RC1/T1OSI/CCP2 bit1 ST Input/output port pin or Timer1 oscillator input or Capture2 input/ Compare2 output/PWM2 output.7PORTD AND TRISD REGISTERS .RC7/RX/DT bit7 ST Input/output port pin or USART Asynchronous Receive or Synchronous Data. RC2/CCP1 bit2 ST Input/output port pin or Capture 1 input /Compare 1 output /PWM 1 output. RC3/SCK/SCL bit3 ST RC3 can also be the synchronous serial clock for both SPI and I2C modes.The user should refer to the corresponding peripheral section for the correct TRIS bit settings. RC6/TX/CK bit6 ST Input/output port pin or U S A RT A s y n c h r o n o u s Tr a n s m i t o r Synchronous Clock.

TTL = TTL input Note: . 2. PORTD can be configured as an 8-bit wide microprocessor port (parallel slave port) by setting control bit PSPMODE (TRISE<4>).2. Legend: ST = Schmitt Trigger input.PORTD and TRISD are an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configurable as an input or output. In this mode. RD2/PSP2 bit2 ST/TTL(1) Input/output port pin or parallel slave port bit2. RD1/PSP1 bit1 ST/TTL (1) Input/output port pin or parallel slave port bit1. RD5/PSP5 bit5 ST/TTL(1) Input/output port pin or parallel slave port bit5. RD6/PSP6 bit6 ST/TTL(1) Input/output port pin or parallel slave port bit6.8PORTD FUNCTIONS RD0/PSP0 bit0 ST/TTL (1) Input/output port pin or parallel slave port bit0. RD7/PSP7 bit7 ST/TTL(1) Input/output port pin or parallel slave port bit7. RD3/PSP3 bit3 ST/TTL(1) Input/output port pin or parallel slave port bit3. the input buffers are TTL. RD4/PSP4 bit4 ST/TTL(1) Input/output port pin or parallel slave port bit4.

Porte pins are multiplexed with analog inputs. which also controls the parallel slave port operation. Contents of . In this mode. the user must make certain that the TRISE<2:0> bits are set. When selected for analog input. These pins have Schmitt Trigger input buffers. 2. The PORTE pins become the I/O control inputs for the microprocessor port when bit PSPMODE (TRISE<4>) is set.10 PORTE FUNCTIONS RE0/RD/AN5 bit0 ST/TTL I/O port pin or read control input in Parallel Slave Port mode or analog input: RD 1 = Idle 0 = Read operation. TRISE controls the direction of the RE pins. and RE2/CS/AN7) which are individually configurable inputs or outputs.1: Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode. 2. RE1/WR/AN6.2. The tries register. The user must make sure to keep the pins configured as inputs when using them as analog inputs. these pins will read as '0's. the input buffers are TTL.2. In this mode. and that the pins are configured as digital inputs. Also ensure that ADCON1 is configured for digital I/O. even when they are being used as analog inputs.9PORTE AND TRISE REGISTERS PORTE has three pins (RE 0 /RD /AN 5.

Value of PORTD I/O pins is latched into PORTD register (if chip selected) RE2/CS/AN7 bit2 ST/TTL I/O port pin or chip select control input in Parallel Slave Port mode or analog input:CS 1 = Device is not selected 0 = Device is selected Legend: ST = Schmitt Trigger input. WR 1 = Idle 0 = Write operation. A bulk erase operation may not be issued from user code (which includes removing code protection). 2.2. TTL = TTL input Note 1: Input buffers are Schmitt Triggers when in I/O mode and TTL buffers when in Parallel Slave Port mode. Access to program memory allows for . These operations take place on a single byte for Data EEPROM memory and a single word for Program memory.11 DATA EEPROM AND FLASH PROGRAM MEMORY The Data EEPROM and FLASH Program Memory are readable and writable during normal operation over the entire VDD range.PORTD register are output to PORTD I/O pins (if chip selected) RE1/WR/AN6 bit1 ST/TTL I/O port pin or write control input in Parallel Slave Port mode or analog input. A write operation causes an erase-thenwrite operation to take place on the specified byte or word.

Therefore. packed 7-bit ASCII. Writing to EEPROM data memory does not impact the operation of the device. A byte or word write automatically erases the location and writes the new value (erase before write. Writing to program memory will cease the execution of instructions until the write is complete. Please refer to the specifications for exact limits (specifications D122 and D133). up to 14-bit numbers can be stored in memory for use as calibration parameters. .checksum calculation. the oscillator continues to run. Executing a program memory location containing data that form an invalid instruction. etc. serial numbers. The values written to program memory do not need to be valid instructions. The program memory cannot be accessed during the write. The FLASH program memory is rated much lower (specificationD130). as well as from chip to chip. During the write operation. The EEPROM Data memories are rated for high erase/ write cycles (specification D120). results in the execution of a NOP instruction. because EEPROM data memory can be used to store frequently updated values An on-chip timer controls the write time and it will vary with voltage and temperature.

When interfacing to EEPROM data memory. if the interrupt is enabled and occurred during the write. the EEDATA register . Read and write access to both memories take place indirectly through aset of Special Function Registers (SFR).the peripherals continue to function and interrupt events will be detected and essentially "queued" until the write is complete. When the write completes. the EEADR register holds the address to be accessed. the next instruction in the pipeline is executed and the branch to the interrupt vector will take place. Depending on the operation. The six SFRs used are: EEDATA EEDATH EEADR EEADRH EECON1 EECON2 The EEPROM data memory allows byte read and writes operations without interfering with the normal operation of the microcontroller.

. The PIC16F873/874 devices have 128 bytes of EEPROM data memory and therefore. or the data read. the EEADRHEEADR registers form a two-byte word.e. Addresses outside of this range do not wrap around to 0000h (i. The FLASH program memory allows non-intrusive read access.. or reflects the value of program memory after a read operation. depending on the device : 00 00 h to 1 FFFh for the PIC16F873/874 or 0000h to 3FFFh for the PIC16F876/877. 0x80 in the EEADR does not map to 0x00. which holds the 13-bit address of the memory location being accessed. require that the MSB of EEADR remain clear. The EEPROM data memory on these devices does not wrap around to 0. 4000h does not map to 0000h on the PIC16F877). at the address in EEADR.e. executing . The PIC16F876/877 devices have 256 bytes of EEPROM data memory and therefore. until the write completes. the value of the EEADRH:EEADR registers must be within the valid range of program memory. Just as in EEPROM data memory accesses . but write operations cause the device to stop instructions.holds the data to be written. use all 8bits of the EEADR. i. When interfacing to the program memory. The register combination of EEDATH EEDATA holds the 14-bit data for writes.

any subsequent operations will work on the EEPROM data memory. When set.2.12 EECON1 AND EECON2 REGISTERS The EECON1 register is the control register for configuring and initiating the access. This bit cannot be cleared by firmware. but is used exclusively in the memory write sequence to prevent inadvertent writes. following the second instruction after the RD . the data will be available in the EEDATA register in the very next instruction cycle after the RD bit is set. all subsequent operations will operate in the program memory. RD. For EEPROM data memory reads.2. The EECON2 register is not a physically imple-mented register. For program memory reads. When clear. the data will be loaded into the EEDATHEEDATA registers. Read operations only use one additional bit. the value of the desired memory location will be available in the data registers. which initiates the read operation from the desired memory location. The EEPGD bit determines if the access will be a program or data memory access. There are many bits used to control the read and write operations to EEPROM data and FLASH program memory. Once this bit is set. It is automatically cleared at the end of the read operation.

once the WREN bit and the WR bit have been set. the EEIF flag bit will be set. The WRERR bit is used to indicate when the PIC16F87X device has . This flag must be cleared in software before setting the WR bit. the WREN bit must be set before executing a write operation. The WREN bit is used to enable or disable the write operation. followed by a write of the detain EEDATA. WRERR and EEIF. WR and WREN. the EEIF flag bit will be set and the microcontroller will continue to execute code. and two status bits. the data value in EEDATH: EEDATA will be programmed. This operation takes place in parallel with the microcontroller continuing to execute normally. When WREN is clear. the write operation will be disabled. Therefore. Then. The WR bit is used to initiate the write operation. the microcontroller will cease to execute instructions. When the write is complete. The interrupt flag EEIF is used to determine when the memory write completes. The desired memory location pointed to by EEADRH EEADR will be erased. Write operations have two control bits.bit is set. When complete. For program memory. the desired memory address in EEADR will be erased. For EEPROM data memory. It also is automatically cleared at the end of the write operation. once the WREN bit and the WR bit have been set.

address registers and EEPGD bit are not affected by either MCLR Reset. WRERR should be cleared after Power-on Reset. during normal operation. if set. Thereafter. In these situations. The contents of the data registers. 2. The WRERR bit is set when a write operation is interrupted by a MCLR Reset. or a WDT Time-out Reset. the user should check the WRERR bit and rewrite the memory location. it should be checked on any other RESET.2. during normal operation.been reset during a write operation.13 ECON1 REGISTER (ADDRESS 18Ch) bit 7 EEPGD: Program/Data EEPROM Select bit 1 = Accesses program memory 0 = Accesses data memory This bit cannot be changed while a read or write operation is in progress) bit 6-4 Unimplemented: Read as '0' bit 3 WRERR: EEPROM Error Flag bit 1 =A write operation is prematurely terminated (any MCLR Reset or any WDT Reset during normal operation The write operation completed bit 2 WREN: EEPROM Write Enable bit 1 = Allows write cycles0 = Inhibits write to the EEPROM bit 1 WR: Write . following a RESET. or WDT Timeout Reset.

memory size of the PIC16F87X  Clear the EEPGD bit to point to EEPROM data memory. The steps to reading the EEPROM data memory are:  Write the address to EEDATA.Control bit = Initiates a write cycle. The RD bit can only be set (not cleared) in software.) 0 Does not initiate an EEPROM read Legend: R = Readable bit W = Writable bit U =Unimplemented bit. After the RD bit is set. (The bit is cleared by hardware once write is complete. data will be available in the EEDATA register on the very next instruction cycle. Make sure that the address is not larger than the device. The WR bit can only be set (not cleared) in software.) 0= Write cycle to the EEPROM is complete bit 0 RD: Read Control bit = Initiates an EEPROM read. (RD is cleared in hardware. EEDATA will hold this value until another read operation is initiated or until it is written by firm ware. . read as '0' n = Value at POR '1' = Bit is set '0' = Bit is cleared x = Bit is un known Reading the EEPROM Data Memory Reading EEPROM data memory only requires that the desired address to access be written to the EEADR register and clear the EEPGD bit.

Writing to the EEPROM Data Memory There are many steps in writing to the EEPROM data memory. except when writing to the EEPROM data. and the WREN bit must be set.  Read the data from the EEDATA register. they both cannot be set in the same operation. before starting another cycle. Both address and data values must be written to the SFRs. Writes to EEPROM data memory must also be prefaced with a special sequence of instructions that prevent inadvertent write operations. The WREN bit should then be cleared by firmware after the write. Clearing the WREN bit before the write actually completes will not terminate the write in progress.. The steps to write To EEPROM data memory is: . i. This is a sequence of five instructions that must be executed without interruptions. The EEPGD bit must be cleared. The WR bit can only be set if the WREN bit was set in a previous operation. The firmware should verify that a write is not in progress. The WREN bit should be kept clear at all times. to enable writes. Set the RD bit to start the read operation.e.

 Write the 8-bit data value to be programmed in the EEDATA register. At the completion of the write cycle.  Write the address to EEADR.  Disable interrupts (if enabled). The WR bit is cleared and the EEIF interrupt flag bit is set. check the WR bit to see if a write is in progress. Make sure that the address is not larger than the memory size of the PIC16F87X device. then to EECON2)Set the WR bit )  Enable interrupts (if using interrupts  Clear the WREN bit to disable program operations. then firmware should .  Set the WREN bit to enable program operations.  Execute the special five instruction sequence: Write 55h to EECON2 in two steps (first to W.  . If step 10 is not implemented.) If step 1 is not implemented. (EEIF must be cleared by firmware.  Clear the EEPGD bit to point to EEPROM data memory. then to EECON2)Write A Ah to EECON2 in two steps (first to W.

check for EEIF to be set. 2. RP1. RP0. RP0. Bank 2 MOVF ADDR.2. BSF STATUS. RP0. Wait for . to read from BSF STATUS. WR.15 EPROM DATA WRITE BSF STATUS. RP0. or WR to clear. RD. Point to Data memory BSF EECON1. W. W. BCF STATUS.2. Bank 2 MOVF EEDATA.14 EEPROM DATA READ BSF STATUS. W = EEDATA 2. Bank 3 BCF EECON1. to indicate the end of the program cycle. EEPGD. Write address MOVWF EEADR. Bank 3 BTFSC EECON1. Start read operation BCF STATUS. RP1.

write to MOVF VALUE. W. if already enabled. only enable interrupts . Point to Data memory BSF EECON1. Start write operation. WR. otherwise discard MOVLW 0x55. WREN. Write A Ah to MOVWF EECON2. EECON2 MOVLW 0xAA. Bank 3 BCF EECON1. EEPGD. write to finish BCF STATUS.GOTO $-1. RP0. Data to MOVWF EEDATA. W. write BSF STATUS. GIE. Enable writes Only disable interrupts BCF INTCON. Bank 2 MOVF ADDR. Write 55h to MOVWF EECON2. EECON2 BSF EECON1. RP0. Address to MOVWF EEADR.

The incrementing edge is deter-mined by the Timer0 Source Edge Select bit. In Counter mode. or falling edge of pinRA4/T0CKI. In Timer mode. otherwise discard BCF EECON1. . The prescaler is mutually exclusively shared between the Timer0 module and the Watchdog Timer. The user can work around this by writing an adjusted value to the TMR0 register. the Timer0 module will increment every instruction cycle without prescaler).BSF INTCON. The prescaler is not readable or writable. Clearing bit T0SE selects the rising edge. Timer mode is selected by clearing bit to C S OPTION_REG<5>). WREN. GIE. Disable writes TIMER0 MODULE The Timer0 module timer/counter has the following features: 8-bit timer/counter Readable and writable 8-bit software programmable prescaler Internal or external clock select Interrupt on overflow from FFh to 00h Edge select for external clock the prescaler shared with the WDT. Counter mode is selected by setting bit T0CSOPTION_REG<5>). the increment is inhibited for the following two instruction cycles. Timer0 will increment either on every rising. If the TMR0 register is written. if using interrupts. T0SEOPTION_REG<4>).

The interrupt can be masked by clearing bit T0IE (INTCON<5>). since the timer is shut-off during SLEEP. The TMR1 Interrupt. This interrupt can be enabled/disabled by setting/clearing TMR1 interrupt enable bit TMR1IE (PIE1<0>). Bit T0IF must be cleared in software by the Timer0 module Interrupt Service Routine before re-enabling this interrupt. which is latched in interrupt flag bit TMR1IF (PIR1<0). is generated on overflow. which are readable and writable. Timer1 can operate in one of two modes: 1) As a timer 2) As a counter .16 TIMER1 MODULE The Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L). The TMR1 Register pair (TMR1H:TMR1L) increments from 0000h to Offhand rolls over to 0000h.2. 2. This overflow sets bitT0IF (INTCON<2>).Timer0 Interrupt the TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h. TheTMR0 interrupt cannot awaken the processor from SLEEP. if enabled.

or 1:16. the RC1/T1OSI/CCP2 and RC0/T1OSO/T1CKI pins become inputs. It can be used as the PWM time-base for the PWM mode of the CCP module(s). 1:4. The TMR2 register is readable and writable. In Timer mode.2. the TRISC<1:0> value is ignored. and is cleared on any device RESET. The input clock (FOSC/4) has a prescale option of 1:1. In Counter mode. it increments on every rising edge of the external clock input. Timer1 can be enabled/disabled by setting/clearing control bit TMR1ON (T1CON<0>). The match output of TMR2 . This RESET can be generated by either of the two CCP modules When the Timer1 oscillator is enabled T1OSCEN is set). The Timer2 module has an 8-bit period register. The PR2 register is initialized to FFh upon RESET. PR2. PR2 is a readable and writable register. 2.The operating mode is determined by the clock select bit. Timer1 increments every instruction cycle. TMR1CS (T1CON<1>). That is. Timer1 also has an internal "RESET input". Timer2 increments from 00h until it match PR2 and then resets to 00h on the next increment cycle.17 TIMER 2 MODULE Timer2 is an 8-bit timer with a prescaler and a postscaler. selected by control bitsT2CKPS1:T2CKPS0 (T2CON<1:0>). and these pins read as '0'.

WDT Reset. . or BOR)TMR2 is not cleared when T2CON is written. (PIR1<1>)). Output of TMR2The output of TMR2 (before the postscaler) is fed to the SSP module. to minimize power consumption. The output of the sample and hold capacitor is the input into the converter.18 ANALOG-TO-DIGITAL CONVERTER (A/D) MODULE The Analog-to-Digital (A/D) Converter module has five inputs for the 28-pin devices and eight for the other devices. Timer2 Prescaler and Postscaler The prescaler and postscaler counters are cleared when any of the following occurs:a write to the TMR2 register a write to the T2CON register any device RESET (POR. MCLR Reset. which optionally uses it to generate shift clock. 2. The converter then generates a digital result of this analog level via successive approximation. The analog input charges a sample and hold capacitor.goes through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling inclusive) to generate a TMR2 interrupt (latched in flag bit TMR2IF.2. Timer2 can be shut-off by clearing control bit TMR2ON (T2CON<2>).

These registers are: A/D Result High Register (ADRESH) A/D Result Low Register (ADRESL) A/D Control Register0 (ADCON0) A/D Control Register1 (ADCON1) The ADCON0 register controls the operation of the A/D module. The ADCON1 register. . A/D's internal RC oscillator The A/D module has four registers.The A/D conversion of the analog input signal results in a corresponding 10-bit digital number. configures the functions of the port pins. The A/D module has high and low voltage reference input that is software selectable to some combination of VDD. shown in Register 11-2. The A/D converter has a unique feature of being able to operate while the device is in SLEEP mode. VSS. RA2. or RA3.

(RA3/AN3) 100 = channel 4. (RE1/AN6) 111 = channel 7. (RA2/AN2) 011 = channel 3. (RA1/AN1) 010 = channel 2. (RA0/AN0( 001 = channel 1. (RE2/AN7) . Bit 7-6 ADCS1:ADCS0: A/D Conversion Clock Select bits 00 = FOSC/2 01 = FOSC/8 10 = FOSC/32 11 = FRC (clock derived from the internal A/D module RC oscillator)bit 5-3 CHS2:CHS0: Analog Channel Select bits 000 = channel 0. (RE0/AN5) 110 = channel 6. or as digital I/O.The port pins can be configured as analog inputs (RA3 can also be the voltage reference). (RA5/AN4) 101 = channel 5.

the GO /DONE bit (ADCON0<2>) is cleared and the A/D interrupt flag bit ADIF is set. When the A/D conversions complete.  Left justified. the result is loaded into this A/D result register pair.Bit 2 GO/DONE: A/D Conversion Status bit If ADON = 1:  A/D conversion not in progress (this bit is automatically cleared by hardware when the  A/D conversion is complete)bit 1 Unimplemented: Read as '0'bit 0 ADON: A/D On bit  A/D converter module is operating  A/D converter module is shut-off and consumes no operating currentADCON1 REGISTER (ADDRESS 9Fh) bit 7 ADFM: A/D Result Format Select bit  Right justified. 6 Most Significant bits of ADRESH are read as '0'. bit 6-4 Unimplemented: Read as '0'bit 3-0 PCFG3:PCFG0: A/D Port Configuration Control bits:The ADRESH:ADRESL registers contain the 10-bit result of the A/D conversion. 6 Least Significant bits of ADRESL are read as '0'. the . After the A/D module has been configured as desired.

The analog input channels must have their corresponding TRIS bits selected as inputs. Set PEIE bit c. Set ADIE bit b.Selected channel must be acquired before the conversion is started. Configure the A/D module: 2. Configure analog pins/voltage reference and digital I/O (ADCON1) Select A/D input channel (ADCON0) Select A/D conversion clock (ADCON0) Turn on A/D module (ADCON0) 3. Wait the required acquisition time. Set GIE bit 4. Start conversion:Set GO/DONE bit (ADCON0) . Configure A/D interrupt (if desired): Clear ADIF bit a. These steps should be followed for doing an A/D Conversion: 1. 5.

6us. 32TOSC Internal A/D module RC oscillator For correct A/D conversions. The port pins that are desired as analog inputs must have their corresponding TRIS bits set (input). The A/D conversion time per bit is defined as TAD. the . 2. A minimum wait of 2TAD is required before the next acquisition starts. The four possible options for TADare: 2TOSC. as required.19 ELECTING THE A/D CONVERSION CLOCK The A/D conversion time per bit is defined as TAD.20 CONFIGURING ANALOG POPR PINS The ADCON1 and TRIS registers control the operation of the A/D port pins. the A/D conversion clock must be selected to ensure a minimum TAD time of 1.2. Read A / D result register pair (ADRESH:ADRESL). 2. OR Waiting for the A/D interrupt 7. The A/D conversion requires a minimum 12TAD per 10-bitconversion. by either: Polling for the GO/DONE bit to be cleared with interrupts enabled). 8TOSC. The source of the A/D conversion clock is software selected. Wait for A/D conversion to complete.2. For the next conversion. go to step 1 or step 2. 7. clear bit ADIF if required.6. If the TRIS bit is cleared (output).

The ADRESH: ADRESL register pair is the location where the 10-bit A/D result is loaded at the completion of the A/D conversion. Figure 11-4 shows the operation of the A/D result justification. acquisition on the selected channel is automatically started. After the GO bit is set. . The A/D Format Select bit (ADFM) controls this justification. The A/D operation is independent of the state of theCHS2:CHS0 bits and the TRIS bits. the ADRESH: ADRESL registers will continue to contain the value of the last completed conversion (or the last value written to the ADRESH:ADRESL registers). That is. The extra bits are loaded with '0's'. This register pair is 16-bits wide. The A/D result register pair will not be updated with the partially completed A/D conversion sample. After this 2TAD wait.digital output level (VOH or VOL) will be converted. a 2TAD wait is required before the next acquisition is started. When an A/D result will not overwrite these locations (A/D disable). these registers may be used as two general purpose 8-bit registers. After the A/D conversion is aborted. The GO/DONE bit can then be set to start the conversion. the first time segment has a minimum of TCY and a maximum of TAD. The A/D module gives the flexibility to left or right justify the 10-bit result in the 16-bit result register. A/D Conversions Clearing the GO/DONE bit during a conversion will abort the current conversion.

2 SOFTWARE CONFIGURATION 1. The ADRESH: ADRESL registers will contain unknown data after a Power-on Reset. The value that is in the ADRESH:ADRESL registers is not modified for a Power-on Reset.1SOFTWARE CONFIGURATION OVERVIEW This Software has been written in assembly language. This forces the A/D module to be turned off.2. 2.software instruction sets 3.3.PIC chip special function registers over view 4.The A/D module can operate during SLEEP mode.The software program 2. LCD used in 4-wire mode of . All A/D input pins are configured as analog inputs. 2.21 EFFECTS OF A RESET A device RESET forces all registers to their RESET state.Software configuration over view 2.PIC chip memory map 5. and any conversion is aborted.

D5. clear (display (00000001) finally cursor at row one and first column (10000000). RB2. To send this bit pattern microcontroller first send Upper nibble to data lines of LCD D7.D6. RB1. R/W=0 and a pulse at EN pin of LCD through PORTB pin RB0.D4 via microcontroller PORTB pin RB7. provide 10mV/ C. After initializing LCD microcontroller. increment cursor (00000110). system raises alarm.Operation to initialize LCD in 4-bit mode a binary value 00101000 is supplied to command resistor of LCD controller. This system allows user to define a threshold temperature. configure PORTA as analog input for reading temperature sensor.RB5.RB4 then applying RS=0 . R/W=0 and a pulse at EN pin of LCD through PORTB pin RB0.RB6. D6. D5. Next it will set display on cursor blinking by bit pattern 00001110). after reading temperature from the LM35DZ microcontroller convert it into temperature value and display on LCD. For entering threshold temperature user has to press ENT Key then UP/DWN key to set threshold temperature and . D4 via microcontroller PORTB pin RB7.RB6. RB2 There after it sends lower nibble to the same data lines D7.RB5.RB4 then applying RS=0 . when system temperature goes above the user define threshold temperature. RB1.

3. This allows the SLEEP instruction to be executed.2SOFTWARE INSTRUCTION SETS . interrupt is enabled. 2. When the RC clock source is selected. Software is provided here. a SLEEP If the A/D instruction will cause the present conversion to be aborted and the A/D module to be turned off. When the conversion is completed. When the A/D clock source is another clock option (not RC). Turning off the A/D places the A/D module in its lowest current consumption state. though the ADON bit will remain set. the A/D module will then be turned off.then ENT to finalize the threshold temperature. If the A/D interrupt is not enabled.void tag temperature. although the ADON bit will remain set. the GO/DONE bit will be cleared and the result loaded into the ADRES register. the device will wake-up from SLEEP. the A/D module waits one instruction cycle before starting the conversion. which eliminates all digitals witching noise from the conversion.

3.Fig.3.2 2.3PIC CHIP SPECIAL FUNCTION REGISTERS STRUCTURE . 2.

3 . 2.Fig.3.

3.3. 2.4PIC CHIP MEMORY MAP Fig.4 .2.

Pin no 19. This is done by using PR4 variable resister 10k. Pin no 17 use to indicate the system performance with the help of LED. This LED is connected with 1k current limiting resister. One is connected to the ground another pin is connected to the microcontrollers key input pin. Pin no 2 is connected to the VCC+5 volts. These connected with 4 numbers of switches namely up button. C7 and C8 are 22pf ceramic capacitors. .22 are key board input pin. Pin no 27 to Pin no 40 is connected with the LCD. R2. These are called as pull up resister. The role of the resistors is to limit the current i. This capacitors one end is connected to the ground anther end is connected to the crystal and micro controller. . This provides a relatively simple interface between a processor and LCD. . LCD Display Section: . R3. This is called as snubber capacitor. R5 are 10k resister. This LCD having 16 characters and 2 lines characteristics. Pin no 13 and 14 are connected with 4 MHz crystal. 20.Pin no1 is reset pin it is connected through 1k resister with the power supply. R4. down button. is drained by the LED. . This is used to reset through the micro controller when it is switched on.The most common type of LCD controller is HITACHI4470. 4. As name says this is used to snub the over oscillated generated by the crystal.e. This is used to give a correct logic level to the micro controllers key board input pin. Pin No 12 and 31 are the ground pins . This is because of static electricity. enter button. Pin no 1 of this display is connected to the ground. Without these 4 resisters micro controllers will not under stand whether the key board input pins are in high or low stage. This crystal is used to give a known clock frequency to the microcontroller to perform a given task.21. start button these buttons are having two pins. Pin no 3 contrast adjustment pin.

3 . 2 or 4 rows. Pin out of 16X2 LCD is shown in (figure1) One of the best solutions for devices that require visualizing the data is the "smart" LCD display. 20 or 40 segments. LCD is interfaced to microcontroller by using four Data lines D7. LCD DISPLAY LCD is used for user interaction with the system. 3. D4 and control signals RS. 16*2 LCD display based on Hitachi HD 44780 controller is used. R/W and En. 16. D5.Pin no 7 to 14 are data pins. D6. LCD display can have 1. LCD can be connected to a microcontroller via 8-bit or 4-bit bus (4 or 8 lines). write pin. Pin no 5 is read. . Segment dimensions are 7x5 dots and one row can consist of 8. Printing the data on this type of display is performed on the dot segments arranged to form a row.

there are control lines E (enable).Resources and Schedules Within this section are the final resources and schedules. 3.1 Besides these. . R/W signal is on the ground.3. Section 4 . because there is one-way communication toward the LCD display.Fig. R/W (read/write) and RS (register select) for a total of 7 lines.

4. 1 6 .1 Resource Requirements In this section the resources necessary to complete the project are defined.

of several hours because after getting into actual work it was realized that some tasks would not require as much time as originally thought. Original estimates for the financial requirements included a PDA and padded accelerometer cost. financial requirements included the actual price for the accelerometer purchased. The progress of the project and the amount of time each team member spent was documented in the weekly email. Below are the first and second estimates for the personal effort The second estimate was trimmed Most of the tasks requirement and the final effort requirement.1 Personnel Effort Requirement The personnel effort is the amount of time each team member spent on a specific task within the project. 4. The cost of labor also .1. The biggest decrease was the in the end- product testing. to the other team members and the faculty advisors.1.4. went down because fewer hours were needed to complete the project then originally expected. The reason for this was it was determined that we were going to recruit other people to help test the end-product. were trimmed a couple of hours. The original estimate also included buying a cell phone The final which was later deleted in favor of using a group member’s cell phone. sent by the communications coordinator.3 Estimated Financial Requirements The financial requirements for implementation are dependent upon the technology considerations and the end product design that was chosen. The PDA was also taken out because of limited budget.

20 22 .

Throughout this process. group members and advisors to inform and track the progress of the project. implementation.2 Project Schedules This section contains the project schedule and the schedule of deliverables. and again for the industrial review panel. This process was followed by Testing followed the the end-product design and implementation process. End product documentation was developed and the end product was demonstrated to the advising faculty. available technologies were considered and the appropriate technology was selected for use in the design of the end product. 23 . Both are represented by Gantt charts. The project concluded with this final report stating the conclusions and Throughout this process weekly emails were sent to all outcome of the project. The project schedule begins with defining the problem and determining the desired end product through research and comparison.4.

.

not met. End Product Testing The system was fully tested. End Product Documentation The team fully met the documentation requirements for this project. This definition had to be modified several times to make the project feasible which resulted in the definition process being greatly exceeded. However. fully met. All the technology considerations and progress of the project was fully documented to keep track of individual work and share it among others. 4.The above Gantt chart provides the dates of the deliverables. The accelerometer was able to sense rapid movements of the laptop and the GPS supplied the coordinates for the location. Research was done up to a few weeks before the completion of the end product. All the data was sent via e-mail using the internet. Project definition An appropriate definition was formulated for this project with the help of the advisors. 25 . Technology Considerations and Selections The research process for this project was greatly exceeded. End Product Demonstration The demonstration for this project was not carried out yet since this report was completed before the demonstration date on December 6. In fact this document is one of the documentation requirements. End Product Design The design of the end product for this project was partially met due to shortage of funding. A new accelerometer had to be ordered and java libraries and files had to be downloaded to have the software running. or not attempted. partially met. exceeded. There was no need to draw three lines for this chart because the team submitted all the deliverables on time. the demonstration of the end product is expected to be partially met due to the altered design of the end product. The end product design had to be altered from the original design to accommodate the changes. Each milestone within the project was rated as greatly exceeded. 2005.3 Project Evaluation This section evaluates the degree of success of the overall project.

Due to lack of time and shortage of funding. In addition.5 Recommendations for Additional Work Additional work to be done for the system would be to actually implement the product described in the design report. Attending meetings helped keep the project within the scope and maintained coordination between members on how the system is building up. the research procedure for the product was very broad and strengthened the ability of the team to perform efficient research. built in modem for wireless connection. the team learned how to add 26 . Team members would always put a deadline for a part of the end product to be done and aim for that date. the java API that identifies the ports and makes them available for the programmer to access was not yet completed for windows operating system. and individual work had to be carried out and then formulated back together. Some of the lessons learned from both the bad and good experiences are discussed in the following paragraphs. Scheduling deadlines and meetings was a crucial issue for this project. As a result no future commercialization plans are expected for this end product especially with already market existing. and off road alert. Pin connections and what each pin represented on the serial port is one of the most important things that the team became very familiar with. the project was broken down into all the different stages discussed through out this report and finally a working end product was developed. a stand alone system with its own power supply.4 Commercialization The end product did not turn out as a stand alone system. lots of problems were at hand. weather forecast. During that time. It was simulated on a laptop with GPS and accelerometer serial port connections to it. and integrated microprocessor was not feasible. The work had to be split up among the team. 4. Technical knowledge related to reading data from USB and serial RS-232 ports was gained from working on this project. more sophisticated. 4. and cheaper systems with the same and even more advanced functionalities. To overcome that.4. In addition to that. Such technologies would involve road assistance. On the other hand. some things went well and as anticipated by the team. Advanced technologies could also be added to the end product to have it stand out from all other market products available.6 Lessons Learned Starting with the problem definition.

4. shortage of funding. Instead of being a stand alone system with its own microprocessor and internal modem. Concerning parts not being delivered on time. Each member of the team contributed a certain amount of money to accommodate for the accelerometer and the team got back on track. 27 . Even though the project was already over budget. Loosing a team member would not have been a huge set back for the team since the members worked very closely together and shared all the information about any piece of the product. The team came across an unexpected risk related to the accelerometer. shortage of funding was actually a big concern for this project and it did actually alter the design of the whole system. and on-time delivery of ordered equipment. the end product was assimilated on a laptop using the internet service provided.certain files to the path of the Java compiler in order for it to recognize certain hardware. the team ordered parts ahead of time to allow room for delay. a new accelerometer had to be researched and ordered due to the essential part it played in the system. The accelerometer received had no pin connections and was impossible to connect to the serial port of the computer.7 Risk and Risk Management The team did a great job of identifying possible risks that could arise during the development of the end product. Some of the anticipated risks were the lose of a team member. Finally.

2 Closing Summary Because traffic accidents happen everyday it is important that a system be developed to detect an accident and report it to a call center. SIO4-00 'GSM Supervision and control system 'Sends alarms as SMS text through a GSM modem 'Receives SMS commands for switching on a relay 'Ready for flash for PCB: SIO4-00 'version no.Section 5 . and the project website. 5. as 'input' to tri-state I/O driver 'Declare variables Dim i As Word .b unitekmail@rediffmail.com '********************************** 'configure the appropriate port and pin directions TRISA = %11110110 TRISB = %01011111 'RS232 output must be conf.Closure Material Contained within this section are the project team information and the conclusion.1 Project Team Information This section contains information about the client. team members. The end product will be able to decrease emergency vehicle response time and possibly save GSM SMS '********************************** 'The fault finder. 0. someone's life. 5. faculty advisors.

Dim j As Byte Dim k As Byte Dim x As Byte Dim y As Byte Dim n As Byte Dim a As Byte Dim temp As Byte Dim data(64) As Byte Dim serdata As Byte 'buffer for serial data Dim startmark As Bit Dim quote As Bit Dim pincode As Bit Dim smsreceived As Bit Dim modem_ready As Bit Dim check_sms_count As Byte Dim alarmcount As Byte Dim delaycount As Byte 'Number of sec. before turning off the output 'No.clock not used Dim hw_enable_status As Bit Dim armed As Bit 'input enabled = 1 Dim z1trigged As Bit Dim z2trigged As Bit Dim z3trigged As Bit Dim z4trigged As Bit 'set if zone is trigged 'set if zone is trigged 'set if zone is trigged 'set if zone is trigged Dim pwr_status As Bit Dim powerfailure As Bit . Dim hour As Byte Dim min As Byte Dim sec As Byte 'variables for the internal clock . before next check of SMS 'Number of sec. of delays per sec.

low=active 'input: zone 3. low=active 'input: zone 2.0 Symbol zone4 = PORTA.3 Symbol led = PORTB. low=active 'input: zone 4.2 Symbol zone1 = PORTB.port used for modem Hseropen 9600 'more uart specific initialization ASM: ASM: ASM: ASM: bcf status.rx9 bcf rcsta.5 'high= inputs enabled 'input: zone 1.sren .3 Symbol zone3 = PORTB.'Definition of I/O ports 'remember to set TRISA and TRISB according to I/O definition Symbol hw_enable = PORTA. low=active 'Siren port 'output relay 'status LED 'input for power monitoring Symbol pwr_sense = PORTA.spen bcf rcsta.1 '**** MAIN PROGRAM **** main: 'disable comperator in RA0-3 ASM: ASM: relay = 0 aux_out = 0 MOVLW 0x07 MOVWF CMCON WaitMs 2000 'wait for system to stabilize (charge pumps in rs232 drivers) 'initialize serial hw port .4 Symbol zone2 = PORTB.rp0 bsf rcsta.0 Symbol relay = PORTA.4 Symbol aux_out = PORTA.

CrLf WaitMs 500 Hserout "AT+CMGF=1" 'setup text mode for SMS format 'default value. Modem sends no respons for new message 'use memory on SIM card 'disable echo from modem.ASM: ASM: ASM: bsf rcsta.rx9d 'clear peripheral flags ASM: clrf pir1 'clear uart receiver ASM: ASM: ASM: movf RCREG.0".cren bcf rcsta. Repeat until respons received led = 1 Gosub modem_ready If modem_ready = True Then 'initialise modem Hserout "ate0". 0x22.6 'SW serial port RX PORTB. "SM".W movf RCREG. CrLf Gosub waiting Hserout "at+cpms=".7 '**** Initialize modem ********* start: 'Send AT command to modem and check respons.0.W 'initiating txif flag by sending anything ASM: ASM: movlw 0 movwf txreg 'disable interrupts ASM: clrf pie1 Define SEROUT_DELAYUS = 5000 'SW serial port TX PORTB.W movf RCREG.0.ferr bcf rcsta. 0x22. . CrLf Gosub waiting Hserout "at+cnmi=0.

Gosub waiting Hserout "at+cmgd=1" Gosub waiting Else Goto start Endif 'delete message in first position if any.

'read primary phone number Gosub waiting read_first_phoneno: Hserout "at+cpbf=", 0x22, "PRI", 0x22, CrLf Gosub get_number If j > 0 Then Write 0, j j = j - 1 'number of digits

For k = 0 To j Step 1 temp = data(k) n = k + 1 Write n, temp Next k Else WaitMs 1000 Goto read_first_phoneno Endif 'store number in eeprom

'********** Main loop ****************** hw_enable_status = 0 armed = 0 delaycount = 0 alarmcount = 0 check_sms_count = 0

hour = 0 min = 0 sec = 0

led = 0 menu: WaitMs 250 'stroke signal

Gosub decrement_counters Gosub check_arming Gosub check_zones Gosub update_siren Gosub check_power Gosub check_sms Goto menu End

'* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * decrement_counters: 'all timed events are based on counters. If delaycount = 0 Then 'all counters/timers are in seconds If check_sms_count > 0 Then check_sms_count = check_sms_count - 1 Endif If alarmcount > 0 Then alarmcount = alarmcount - 1 Endif 'count the hours from power on... If min = 60 Then hour = hour + 1 min = 0 Else If sec = 60 Then

min = min + 1 sec = 0 Else sec = sec + 1 Endif Endif delaycount = 4 Else delaycount = delaycount - 1 Endif Return 'one count is 250 mS

check_arming: '******************************** 'hw = 1 (åben) -> hw_status = 0/armed = 0, armed 0 -> 1, hw_status 0->1 'hw = 0 -> rutine afvikles ikke, armed = 0, siren shut-off

If hw_enable <> hw_enable_status Then 'HW enable input changed. armed = hw_enable hw_enable_status = hw_enable Endif If armed = 1 Then led = 0 Else led = 1 alarmcount = 0 Endif Return

check_zones: '*********************************************** 'check zones in every scan

0x1a alarmcount = 180 Gosub waiting Endif Else z1trigged = False Endif If zone2 = 0 Then If z2trigged = False Then 'zone activated z2trigged = True aux_out = 1 Gosub init_sms Hserout "*************************!".If armed = 1 Then If zone1 = 1 Then If z1trigged = False Then 'zone activated z1trigged = True aux_out = 1 Gosub init_sms Hserout "**************************!". 0x1a alarmcount = 180 Gosub waiting Endif Else z2trigged = False Endif If zone3 = 0 Then If z3trigged = False Then 'zone activated z3trigged = True aux_out = 1 Gosub init_sms Hserout "***********************!". 0x1a .

alarmcount = 180 Gosub waiting Endif Else z3trigged = False Endif If zone4 = 1 Then If z4trigged = False Then 'zone activated z4trigged = True aux_out = 1 Gosub init_sms Hserout "******************* 0x1a alarmcount = 180 Gosub waiting Endif Else z4trigged = False Endif Endif Return check_power: '************************************************ If pwr_sense <> pwr_status Then 'send SMS if changed Gosub init_sms If pwr_sense = False Then 'power lost Hserout "power down" Else 'power restored powerfailure = True Hserout "power OK" Endif .

If check_sms_count = 0 Then Toggle led Gosub check_for_message 'check if a message is received If smsreceived = True Then Hserout "AT". CrLf Gosub waiting Endif 'delete message 'delete message . CrLf Gosub waiting Hserout "at+cmgd=1". CrLf Gosub waiting Hserout "at+cmgd=1".Hserout 0x1a 'Ascii 26 pwr_status = pwr_sense Endif Return update_siren: '****************************** 'sound alarm if armed (alarmcount will only be set if armed) If armed = 1 Then If alarmcount > 0 Then aux_out = 1 Else aux_out = 0 Endif Else alarmcount = 0 aux_out = 0 Endif Return check_sms: '*********************************** 'check for new SMS message every 10 sec.

"+45xxxxxxxx".g.. e. CrLf Gosub waiting Toggle led Return 'read no. check_for_message: '**************** 'check for message in pos. 1 'respons: 'if no massage available in this position: '+CMS ERROR: 321 'if message available in this position. of digits in phone no. x Hserout x Next j Hserout 0x22."dd/mm/yy.: '+CMGR: "REC UNREAD". temp '+4530123456 For j = 1 To temp Read j. CrLf Gosub waiting 'send SMS Hserout "at+cmgs=".Gosub check_command Toggle led check_sms_count = 8 Endif Return 'Set number of counts for next check init_sms: '******************************* 'send initial string to modem Toggle led Hserout "AT".hh:mm:ss+08" '#1268:0' . 0x22 Read 0.

j contains no. CrLf loop: Gosub hserget2 If serdata > 0 Then 'check if quote is found->this is not an error message If serdata = 0x22 Then smsreceived = True Endif If serdata = "#" And smsreceived = True Then startmark = True Endif If startmark = True Then data(j) = serdata If j = 64 Then j = 0 Else j = j + 1 Endif Endif Endif i = i + 1 If i = 10000 Then Return Goto loop Return 'timeout 'store data in buffer 'handle buffer overflow check_command: '**************************** If j > 0 Then 'buffer contains data . CrLf Gosub waiting Hserout "at+cmgr=1".'read data and store in buffer if '#' found. of characters stored j = 0 i = 0 startmark = False smsreceived = False Hserout "AT".

Til/fra of alarm/inputs 'r 'v '? .j = j . start position for pin-code compare For j = 1 To 4 Step 1 y = y + 1 Read y. start from 0000 . 'this is compared with the last 4 digits of primary phone number stored 'in eeprom (1st position is the length of the stored phone number pincode = True Read 0.Status request (relay and alarm) If data(6) = "1" Then relay = 1 Gosub init_sms 'relay on Hserout "Udgang: TIL".send version number of firmware .4 'read number of digits in phone number 'cal. x y = x .on/off of relay output 'T/F .1 'check pincode in command 'pin code is 4 digit after #-sign in SMS stored in data(). 'read digit in 1/0 . 0x1a Endif If data(6) = "0" Then relay = 0 Gosub init_sms Hserout "Udgang: FRA". a x = data(j) If x <> a Then pincode = False Next j 'execute command if pincode is valid If pincode = True Then If data(5) = ":" Then 'commands: 'check for command separator 'calculate relative offset for phone no. 0x1a Endif If data(6) = "F" Or data(6) = "f" Then 'disable inputs 'Disable inputs 'relay off .reboot system.

armed = 0 Gosub init_sms Hserout "Alarm: FRA". 0x1a Endif If data(6) = "r" Then Goto main 'reboot system 'send version no.b". 0x1a Else armed = 1 Hserout "Alarm: TIL". 0x1a Endif Endif 'Enable inputs If data(6) = "?" Then Gosub init_sms 'command for system status If relay = 1 Then Hserout "Udgang: TIL". CrLf Else Hserout "Udgang: FRA". CrLf Endif If armed = 0 Then Hserout "Alarm: FRA" Else Hserout "Alarm: TIL" Endif Hserout 0x1a Endif If data(6) = "v" Then Gosub init_sms Hserout "GSM-SIO4 v0. . 0x1a Endif If data(6) = "T" Or data(6) = "t" Then 'enable input Gosub init_sms If hw_enable = 0 Then Hserout "Valg ej muligt".

"+").145. Otherwise j is the number of chars in the buffer.Endif Endif Endif 'clear buffer For k = 0 To 40 Step 1 data(k) = 0xff Next k Endif Return get_number: '**************** 'read phone number from SIM card 'read from serial port and search after " and + and store from + to last " in buffer."+45xxxxxxxx". k If serdata = temp Then k = k + 1 If k = 2 Then startmark = True Endif Endif If serdata = 0x22 And startmark = True Then 'search for " and then for + . found: +CPBF: 1."PRIMARY!" 'respond if not found: ??? 'if j=0 no data found. j = 0 i = 0 k = 0 startmark = False loop_nr: Gosub hserget2 If serdata > 0 Then temp = LookUp(0x22. 'respond if no.

'respond will be ERROR or OK. CrLf loop_mr: Gosub hserget2 If serdata > 0 Then If serdata = "K" Then 'OK received modem_ready = True Endif Endif i = i + 1 If i = 20000 Then Return Goto loop_mr Return 'timeout waiting: . Only character 'k' is checked modem_ready = False Hserout "AT".startmark = False Endif If startmark = True Then data(j) = serdata If j = 64 Then j = 0 Else j = j + 1 Endif Endif Endif i = i + 1 If i = 10000 Then Return Goto loop_nr Return 'timeout 'store data in buffer modem_ready: '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * 'sends AT command to modem and wait for OK to be received.

'returns 0 in variable "serdata" if no data read ASM:ser_in: btfsc rcsta.ferr goto frameerror clrw 'return 0 if no data btfss pir1.w bsf intcon.'************************************* WaitMs 350 Return hserget2: '******************************************* 'serial input routine with error handling.cren movf rcreg.oerr ASM: ASM: ASM: ASM: ASM: ASM: goto overerror btfsc rcsta.gie .rcif goto end_call 'clear gie before read ASM:uart_gotit: bcf intcon.gie ASM: btfsc intcon.gie goto ser_in 'turn gie off 'flush fifo 'turn cren on.gie goto end_call ASM:overerror: bcf intcon.gie ASM: ASM: ASM: ASM: ASM: ASM: ASM: ASM: ASM: btfsc INTCON.GIE goto overerror bcf rcsta.w movf rcreg.w movf rcreg.w bsf rcsta.gie ASM: ASM: ASM: ASM: ASM: btfsc intcon.cren bsf intcon. clear oerr flag ASM:frameerror: bcf intcon.gie goto uart_gotit movf rcreg.

gps_buff[30].7194.w bsf intcon. // temp_buff[3] = gps_buff[22]. temp_buff[0] = gps_buff[19].6.lat = atol(temp_buff). unsigned temp_buff[10].lon_deg = atol(temp_buff).8. current_loc.E.lat_deg = atol(temp_buff).6381. //temp_buff[2] = gps_buff[21]. temp_buff[4] = 0. temp_buff[2] = gps_buff[16].M. current_loc.06703.N. //get Longitude temp_buff[0] = temp_buff[1] = temp_buff[2] = temp_buff[3] = temp_buff[4] = temp_buff[5] = gps_buff[26]. 24). temp_buff[2] = 0. temp_buff[2] = 0.. gps_buff[28]. current_loc.' && gps_buff[14] != '.182948. gps_buf_index < GPS_BUFFER_SIZE. gps_dat_ready_flag = high.1. temp_buff[1] = gps_buff[33]. temp_buff[1] = gps_buff[15]. //temp_buff[3] = gps_buff[35].') { //get Latitude temp_buff[0] = gps_buff[14].0 0051. gps_dat_ready_flag = LOW. temp_buff[3] = gps_buff[17].gie goto ser_in ASM:end_call: movwf serdata Return GPS CODE ……………………………………………… unsigned int1 get_loc( void ) { unsigned int16 gps_buf_index. gps_buff + 14. temp_buff[0] = gps_buff[32].ASM: ASM: ASM: ASM: goto frameerror movf rcreg.04. current_loc.09. gps_buff[29]. temp_buff[1] = gps_buff[20]. strncpy (gps_smsdat.2456.-044. } //$GPGGA. gps_buff[27].M.*66 if(gps_buff[13] = '.lon = atol(temp_buff).0. //temp_buff[2] = gps_buff[34]. for ( gps_buf_index = 0. 0.gps_buf_index++) { gps_buff[ gps_buf_index ] = fgetc(GPS_COM). } } .

30 .

3 References 31 .5.

32 .