You are on page 1of 68

UNIVERSITY OF DAR ES SALAAM

COLLEGE OF ENGINEERING AND TECHNOLOGY


DEPARTMENT OF ELECTRICAL AND COMPUTER SYSTEMS ENGINEERING

PROJECT REPORT CS499 PROJECT TITLE: MICROCONTROLLER BASED TAXI BILLING SYSTEM

A Project Report in Partial Fulfilment for the Award of Bachelor of Science in Computer Engineering & Information Technology

Name of Candidate: Maira, Albert M. Registration Number: 2006-04-05608 Supervisor: Dr. M.M. Kissaka Submission Date: 9th July 2010

Table of Contents
Content Page
TABLE OF CONTENTS .............................................................................................................................. I DECLARATION ........................................................................................................................................ III ABSTRACT ................................................................................................................................................ IV ACKNOWLEDGEMENTS .........................................................................................................................V LIST OF FIGURES .................................................................................................................................... VI LIST OF TABLES ...................................................................................................................................... VI LIST OF ABBREVIATIONS AND ACRONYMS .................................................................................VII CHAPTER 1 ................................................................................................................................................. 1 INTRODUCTION ........................................................................................................................................ 1 1.1 WHAT IS A TAXIMETER? ....................................................................................................................... 1 1.2 CURRENT SITUATION ............................................................................................................................ 1 1.3 PROBLEM STATEMENTS ........................................................................................................................ 2 1.4 OBJECTIVES .......................................................................................................................................... 2 1.5 SIGNIFICANCE OF THE PROJECT ............................................................................................................. 3 1.6 SCOPE OF THE PROJECT ......................................................................................................................... 3 1.7 METHODOLOGY .................................................................................................................................... 3 CHAPTER 2 ................................................................................................................................................. 5 LITERATURE REVIEW ............................................................................................................................ 5 2.1 MICROCONTROLLER ............................................................................................................................. 5 2.2 LCD ..................................................................................................................................................... 7 2.3 TAXIMETERS ......................................................................................................................................... 7 2.3.1 Mechanical taximeters ................................................................................................................. 7 2.3.2 Microprocessor taximeters .......................................................................................................... 8 2.3.3 Microcontroller taximeters .......................................................................................................... 9 2.4 DIGITAL LOGIC ..................................................................................................................................... 9 2.5 ODOMETRY ..........................................................................................................................................10 2.6 INTERRUPTS .........................................................................................................................................10 CHAPTER3 .................................................................................................................................................12 INITIAL DESIGN .......................................................................................................................................12 3.1 SYSTEM MODELLING ...........................................................................................................................12 3.1.1 System Requirements...................................................................................................................12 3.1.2 Block Diagram of the System ......................................................................................................12 3.1.3 System flow chart ........................................................................................................................13 3.1.4 Resource management ................................................................................................................15 3.2 COMPONENTS SELECTION ....................................................................................................................15 3.2.1 PIC16F877A microcontroller .....................................................................................................15 3.2.2 JHD162A DISPLAY ....................................................................................................................18 3.2.3 Keypad ........................................................................................................................................19 3.2.4 Pushbutton switch .......................................................................................................................20 CHAPTER 4 ................................................................................................................................................21 DEVICE CONFIGURATION ....................................................................................................................21 4.1 POWER CONFIGURATION ......................................................................................................................21

4.1.1 Power-On Reset (POR) ...............................................................................................................22 4.1.2 MCLR Reset during normal operation ........................................................................................23 4.1.3 MCLR reset during sleep ............................................................................................................23 4.1.4 WDT reset (During normal operation) .......................................................................................24 4.1.5 WDT Wake-up (during SLEEP) ..................................................................................................24 4.1.6 Brown-out Reset (BOR) ..............................................................................................................24 Power Control/Status Register (PCON) ..............................................................................................25 Device Configuration Word Register ...................................................................................................26 4.2 OSCILLATOR CONFIGURATION .............................................................................................................27 4.3 INTERRUPT CONFIGURATION ...............................................................................................................29 4.3.1 INTCON register .........................................................................................................................30 4.3.2 OPTION_REG register ...............................................................................................................31 4.3.3 PIE1 register ...............................................................................................................................32 4.3.4 PIR1 register ...............................................................................................................................33 4.3.5 T1CON register ...........................................................................................................................34 4.4 I/O PORTS DIRECTION .........................................................................................................................36 4.4.1 Port A ..........................................................................................................................................36 4.4.2 Port B ..........................................................................................................................................37 4.4.3 Port C ..........................................................................................................................................38 4.4.4 Port D .........................................................................................................................................38 4.4.5 Port E ..........................................................................................................................................38 CHAPTER 5 ................................................................................................................................................40 SOFTWARE IMPLEMENTATION .........................................................................................................40 5.1 MAIN PROGRAM THREAD .....................................................................................................................41 5.1.1 Initialisation ................................................................................................................................41 5.1.2 Update LCD display....................................................................................................................42 5.2 DISTANCE COST ISR THREAD ..............................................................................................................42 5.3 TIME COST ISR THREAD.......................................................................................................................42 CHAPTER 6 ................................................................................................................................................43 HARDWARE IMPLEMENTATION ........................................................................................................43 6.1 POWER SUPPLY ....................................................................................................................................44 6.2 DEVICE INTERFACING ..........................................................................................................................46 6.2.1 Interfacing PIC16F877A and LCD screen..................................................................................46 6.2.2 Interfacing PIC16F877A and Keypad.........................................................................................47 6.2.3 Interfacing PIC16F877A with sensor .........................................................................................47 6.3 RESET CIRCUIT.....................................................................................................................................48 6.4 CIRCUIT SIMULATION ..........................................................................................................................50 CHAPTER 7 ................................................................................................................................................52 CONCLUSION ............................................................................................................................................52 7.1 CHALLENGES .......................................................................................................................................52 7.2 SUCCESSES ..........................................................................................................................................52 7.3 FAILURES .............................................................................................................................................53 7.4 RECOMMENDATIONS ...........................................................................................................................53 REFERENCES: ...........................................................................................................................................54 APPENDIX A: APPLICATION SOFTWARE CODE. ...........................................................................55 APPENDIX B: PROJECT ACTIVITIES .................................................................................................59 APPENDIX C: PROJECT COSTS ............................................................................................................60

ii

Declaration Statement of Authorship and Originality


I declare that this report and work described in it are my own work, with any contribution from others expressly acknowledge and/or cited.

I declare that the work in this report was carried out in accordance with the regulations of the University of Dar es Salaam and has not been presented to any other University for examination either in Tanzania or overseas. Any views expressed in the report are those of the author and in no way represent those of the University of Dar es Salaam.

Maira, Albert M.

SIGNED: .

DATE: .

iii

Abstract
Within our modern day towns and cities in Tanzania taxicabs are a common means of transportation, but the billing of the taxicabs is currently done through negotiation between the taxicab driver and a prospective customer. This situation can lead into several inconveniences to both the taxicab driver and the customer.

This design project proposes a prototype microcontroller circuit that will enable to implement a computerised billing mechanism to be used to automate the billing in taxicabs.

In this design an external wheel revolution sensor is used to generate an interrupt to the microcontroller each time the wheels make a single revolution; and from this interrupt, distance travelled is deduced by using wheel dimensions (circumference). Also time duration of the journey is obtained from an internal timer in the microcontroller which is set to overflow after every two seconds; and from this interrupt, hiring time of the journey is obtained for billing purposes.

Then finally, the microcontroller by using the predetermined billing rate which is based on parameters of cost per 100metres distance and cost per 1minute time of the journey, it calculates the cost (in T.Shs) incurred by the customer and displays it on the LCD screen.

iv

Acknowledgements
The first and the foremost to be thanked is the almighty God, who gave me strength, courage, and direction to perform this project. Secondly, I would like to acknowledge Dr. M.M. Kissaka my supervisor for providing me assistance, guidance and constructive criticism throughout the design of my project.

Also I would like to give my sincere thanks to all Electrical and Computer Systems engineering (ECSE) department staffs for their constructive suggestions and help toward my project.

List of figures
Figure 1: System block diagram ....................................................................................... 13 Figure 2: System flow chart .............................................................................................. 14 Figure 3: Reset circuit ....................................................................................................... 23 Figure 4: PIC power stabilisation supply.......................................................................... 45 Figure 5: LCD Power stabilisation circuit ........................................................................ 46 Figure 6: Microcontroller reset circuit .............................................................................. 49 Figure 7: Taxicab choices ................................................................................................. 50 Figure 8: Taxicab billing................................................................................................... 51 Figure 9: Display bill ........................................................................................................ 51

List of tables
Table 1:PIC16F877A features .......................................................................................... 17 Table 2: Oscillator frequency configuration choices ........................................................ 28 Table 3: Recommended capacitors for crystal oscillator .................................................. 28 Table 4: Prescaler rate select bits ...................................................................................... 32 Table 5: Bill of materials (BOM)...................................................................................... 49

vi

List of abbreviations and acronyms


ADC BOR BOM CMOS CPU EEPROM EPROM ECSE I/O ports ISR LCD LVP MCLR MCU MSSP OST OTP PIC POR PWRT RAM ROM ST TTL T.Shs WDT Analogue to digital converter Brown out reset Bill of materials Complementary metal oxide semiconductor Central processing unit Electrically erasable programmable read only memory Erasable programmable read only memory Electrical and computer systems engineering Input or output port Interrupt service routine Liquid crystal display Low voltage programming Master clear Microcontroller unit Master Synchronous Serial Port Oscillator start-up timer One time programmable Programmable intelligent computer Power on reset Power up timer Random access memory Read only memory Schmitt trigger Transistor-transistor logic Tanzanian shillings Watch dog timer

vii

Chapter 1 Introduction
Microcontroller based taxi billing system is a computerised electronic billing system for rented personal transportation services of a taxicab, which are commonly found within our modern day towns and cities as one of transportation means.

Microcontrollers are virtually everywhere in our modern society such that they can be found in practically every digital electronic device that furnishes an independent functionality to its user be it at home, industry or office. For example we can find microcontrollers in our televisions, fridges, microwave ovens, personal computers and printers.

1.1 What is a taximeter?


A taximeter is a device that indicates the amount to be charged for use of a taxi by using a predetermined rate or rates based on distance travelled, time elapsed or a combination of both.

Taximeters arose out of a need to automate the taxi fare since in our present day society we tend to seek efficiency and quality in our lives, with minimum resources in terms of cost and time through the use automatic or semi-automatic mechanisation.

1.2 Current situation


The current situation found in our Tanzanian towns and cities is that; billing for rented transportation services is conducted through negotiation by word of mouth between the taxicab driver and the customer. So only until the cost has been agreed between the two parties the journey can begin.

There is no clear billing structure used to arrive at the cost rather billing is assumed depending on the case by case basis and bargain power of the parties, this design project 1

will address this shortage by proposing a microcontroller based billing system which uses billing structure based on the measured distance and time to determine the cost.

1.3 Problem statements


Due to the use of negotiation caused by a lack of clear billing structure the present situation has several problems which lead into inconveniences to both the taxicab driver and the customer as well; Lack of clear billing structure for taxicabs which causes price bargains between taxicab driver and customer causes wastage of time. Difficulties might arise to people who are new into town since they can be caught at a disadvantage in bargains, since they cannot estimate the destination distance and thus reasonable cost. Difficulties to foreigners who cannot speak the local language Swahili during price negotiation.

1.4 Objectives
Due to the aforementioned problems of the present situation this design project will address the situation by proposing a microcontroller billing system whose main objective is to computerise and thus automate the billing system of rented transportation services of the taxicab by achieving the following specific objectives. To design a microcontroller circuit that is capable of measuring time and distance. To design a microcontroller circuit that calculates the cost by using time and distance as the billing parameters. To design a microcontroller circuit that displays the measured distance, time and cost on the alphanumeric LCD screen.

1.5 Significance of the project


Upon its completion, the project will come up with the circuit that will be able to measure the distance travelled and hiring time of the journey then system will automatically calculate the fare. The circuit will provide a means of standardising the taxicab billing so that it can be justly to both the taxicab driver and to the customer.

1.6 Scope of the project


This project is undergraduate final year project performed in partial fulfilment for the award of Bachelor of Science in Computer Engineering and Information Technology. The project is a design-implement based project that will use microcontroller, revolution sensor, and LCD display to build a circuit that will automatically measure distance covered and hiring time to calculate cost. Only a prototype will be accomplished, mainly for proof of concept purposes and its industrial application may not be feasible at this stage.

1.7 Methodology
Since the system to be designed is an embedded electronics application then both principles of hardware and software design methodologies are adopted in order to accomplish the intended designed system then the following development approach will be used. Literature review in design, interfacing and practical limitations and challenges of microcontroller systems. Functional requirements elicitation from the users of the proposed system. System requirements identification. System plan design and circuit simulation. Implementation of system plan and circuit on to a breadboard prototype circuit. Testing of prototype to ascertain that the requirements have been met and to account for the subtle practical challenges.

The current situation has been outlined in this chapter together with its associated problems and a design methodology has been identified as an approach to achieve the design goals and solve the present problems. So the next chapter is about literature review on the different implementation of taximeters together with associated technologies so as to achieve an efficient and useful design in this project.

Chapter 2 Literature review


This is the chapter that gives some information on various technologies to be used in the construction of this design project

2.1 Microcontroller
A microcontroller is a single chip, self contained computer which incorporates all the basic components of a much familiar personal computer but on a much smaller scale. Thats why microcontrollers are often referred to as single chip devices or single chip computers. The main consequence of the microcontrollers small size is that its resources are far more limited than those of a personal computer microprocessor.

In functional terms, a microcontroller is a programmable single chip which controls a process or system. Microcontrollers are typically used as embedded controllers where they control part of a larger system such as an appliance, automobile device, scientific instrument or a computer peripheral to name a few. In this design a microcontroller will be used to control a process that is the billing process.

Physically, a microcontroller is an integrated circuit with pins. The pins present on a microcontroller are used for power, ground, oscillator clock signals, I/O ports, interrupt request signals, reset and control pins. In contrast the pins present on a microprocessor are most often memory bus signals (rather than I/O ports). A typical microcontroller has the following building parts CPU: this is a part that does all the computing and supervisory functions within a microcontroller as it; fetches, decodes and executes program instructions and directs the flow of data to and from memory. The CPU performs the calculations as required by program instructions and places the results of these calculations into memory space.

ROM: this is a non-volatile memory used for storage of program codes and data in the microcontroller. The microcontroller uses ROM memory space to store program instructions so that they can not be affected by loss of power.

RAM: this is the data memory used to store all of the program variables, thus it is used to read and write data values as a program runs. RAM uses volatile memory (hence when the power is off its contents are lost) type of technology whose access time does not depend on the spatial locality of the given memory address.

I/O PORTS: these are the pins used to provide communication access to/from the microcontroller and other electronic peripheral devices and systems.

Just as any other computer architecture microcontrollers are of two basic types; Harvard architecture microcontroller: in this architecture the microcontroller uses separate memory space for program instructions and data. This allows two or more internal data buses which allow simultaneous access to both instructions and data. for example the CPU fetches instruction on the program memory bus if fetched instruction requires an operation on data memory the CPU can fetch the next program instruction while it uses the data bus for its data operation this gives high throughput and speeds up execution time, but at the cost of more hardware complexity as this architecture requires much more internal buses for data and program instruction. In this design a microcontroller with Harvard architecture will be used due to good performance. Von Neumann architecture microcontroller: in this microcontroller architecture there is a single common memory space where both program instructions and data are stored, thus there is a single data bus which fetches both instructions and data. Each time the PU fetches a program instruction it may have to perform one or more read/write operations to data memory space. It must wait until these subsequent operations are complete before it can fetch and decode the next program instruction. The advantage of this architecture lies in its simplicity and economy.

2.2 LCD
LCDs are alphanumeric displays which are commonly used in microcontroller circuit applications due to their advantages of low cost and low power consumption. And thus are ideal in low power battery operated portable devices. There are basically two types of LCDs as far as the interface technique is concerned namely parallel and serial LCDs.

Parallel LCDs are connected to the microcontroller I/O pins using four or eight data wires and data is transferred from the microcontroller to the LCD in parallel form either one nibble at a time if four data wire mode or one byte if eight data wire mode is used. This has the advantage of being economical and with better performance.

Serial LCDs are connected to the microcontroller using only one data line and data is transferred to the LCD using the standard RS232 asynchronous data communication protocols. Serial LCDs are easier to use but they usually cost more than the parallel ones due to presence of serial controller chip such as RS232.however they have an advantage that only one wire is used to interface them to a microcontroller, thus saving the number of I/O pins required.

In this design a parallel LCD with eight data wires will be used due to better performance and relatively smaller cost as compared to serial LCD.

2.3 Taximeters
Apart from the microcontroller approach chosen in this design there are other two more methods which can be used to provide a billing mechanism of taxicabs.

2.3.1 Mechanical taximeters


These were the early means of constructing taximeters by using the mechanical computing gears to transduce the distance covered into billing cost. The mechanical taximeters have the following advantages

They have good temperature performance. They are immune from electrical and electromagnetic interference.

The mechanical taximeters have the following disadvantages They are heavy and bulky. They are difficulty to calibrate accurately on a timely basis. They suffer from poor accuracy. They lack adequate resolution. They have limitations on the number of optional rates. They have limited feature capability. They do not take advantage of available electronic technology. The process of calibrating mechanical taximeters to new fare rates is awkward and expensive as it usually requires change in computing gears. Mechanical computing gears with time are subject to corrosion and wear and this introduces errors in fare calculations. In general the use of mechanical taximeters does not provide much room for flexibility in the billing requirements and it does not fit well with present day ubiquitous electronics technologies which are much more efficient and cheap.

2.3.2 Microprocessor taximeters


These are taximeters which use the general purpose microprocessor as the computing engine of the billing system of taximeter. The advantages of microprocessor taximeters are They have high performance. They are easy to interface to other intelligent peripherals and systems.

However the microprocessor taximeters have the following disadvantages They have poor temperature performance. They have high cost. They are susceptible from electrical and electromagnetic interference.

They have high power requirements.

In general the use of general purpose microprocessor in taximeters is uneconomical as the microprocessors have so many capabilities (which must be paid for at a high cost), but which are not normally needed in the operation of taximeters.

2.3.3 Microcontroller taximeters


These are taximeters which use a dedicated processor of the microcontroller to provide a computing mechanism for billing system of taximeter. This is the preferred choice in this design due to the following advantages They are cheap in cost. They are flexible in providing the billing options. They have adequate performance for taximeter application. They have good resolution.

2.4 Digital logic


When a pin on a microcontroller port is configured as the input line, the microcontroller can read the electrical voltage present on that input pin to determine its logical binary value (0 or 1). Similarly when the pin is configured as the output pin, the microcontroller can raise the voltage on that pin to +5 V by placing logical binary 1 at the bit location on the port. Placing a binary 0 at the bit location will output a zero voltage. In the TTL logic electronic family; electrically a binary 1 is equal to a positive voltage level between 2V and 5V. A binary 0 is equal to a voltage of 0 to 0.8V. The voltage value between 0.8 and 2V are undefined. While in CMOS logic family, the input voltage within 1.5V (0 to 1.5V) of ground are considered as the binary 0 while the input voltage within 1.5V to +5V supply are considered as the binary 1. The main advantage of CMOS logic devices is their low power requirements as compared to TTL based devices or other logic families. This is the

main reason CMOS logic has become the dominant form of logic used for large complex ICs.

Thus for this design CMOS based electronic devices will be used.

2.5 Odometry
Odometry is the technique of measuring distance travelled by a vehicle, generally by measuring wheel revolutions. A pushbutton switch in this design will be used to measure angular displacement of a wheel. By knowing the wheel dimensions (i.e. circumference) it is not difficult to calculate the actual distance moved this is a simple technique but, it can take no account of wheel slippage, or inaccuracies in wheel dimensions due to change in tyre pressure or other parts of the measurement chain.

2.6 Interrupts
Interrupts are a mechanism of a microcontroller which enables it to respond to some events at the moment when they occur, regardless of what microcontroller is doing at the time. This is a very important part in this design, because it provides connection between a microcontroller and environment which surrounds it. Generally, each interrupt changes the program flow, interrupts it and after executing an interrupt subprogram (interrupt routine) it continues from that same point onwards.

There are basically two types of interrupts namely; Hardware interrupts these are interrupts that are initiated by a peripheral hardware module event for example the timer module could issue an interrupt on overflow to the central processing unit. Software interrupts are software instructions that make calls to interrupt-handler routines. Software interrupts are not often used in smaller microcontrollers, but they are very common in microprocessor architectures as trap handlers.

In typical microcontroller architecture there are multiple hardware interrupt sources and when an interrupt request is acknowledged the execution jumps to the handler, the address the program jumps to is known as the interrupt vector.

10

Depending on the architecture of the microcontroller the interrupts can be either be vectored or non vectored interrupts. For vectored interrupts architectures this address is specified by the application while for non-vectored architectures a specific address is used by the processor.

The midrange PIC16FXXX MCU architecture (to be used in this project) uses nonvectored approach; whereby whenever an interrupt occurs the program goes to constant ISR address constant at 0004h. Thus it is the duty of the programmer to test which specific interrupt indeed occurred (i.e. by testing specific interrupt flag bits) and take appropriate action accordingly. Some processors with vectored interrupt approach (e.g. high end architecture devices PIC24FXXX) have multiple interrupt vectors for handling multiple interrupt sources with different interrupt handlers at programmer specified memory location.

11

Chapter3 Initial Design


This chapter will give information about the modelled building blocks required the system it will also explain how different system parts and components are chosen as building components of the design depending on their features and characteristics.

3.1 System Modelling


This section will elaborate on the model of the design, to implement a microcontroller circuit that acts as a taximeter by taking into consideration the user requirements and the needed hardware

3.1.1 System Requirements


The following user general requirements have been identified The user interface must be simple. The contact area of push buttons should be at least 50 mm 2 . The energy source must be provided by a car. It must be able to show distance travelled, hiring time and cost. The cost of production should be low. The software architecture must be modular. The design should include the possibility of being used as a development board for new modules. User needs to be able to reset the system to give a new billing instance.

3.1.2 Block Diagram of the System


The designed system will include the following building blocks Keypad: this is used to capture user settings.

12

Wheel revolution sensor: this is a digital switch that triggers a wheel revolution interrupt to a microcontroller each time it is triggered by a wheel revolution. LCD screen: this is the display used to show the measured distance, time and calculated cost. Microcontroller: this is the workhorse of the system and performs all the decision making and computations.

Display

Keypad

Microcontroller

Revolution sensor

Figure 1: System block diagram

3.1.3 System flow chart


The system flow chart in this design utilises three asynchronous program threads; namely, the main program, wheel revolution sensor ISR and the timer1 overflow ISR.

13

Start Disable time interrupt Initialisation Save main program registers to be affected No Wait for START key Increment seconds time counter Is the start key pressed? Yes Is 100 metres reached? Yes Increment distance metres counter Save main program registers to be affected Disable sensor interrupt

Yes Is 60 seconds reached? Yes Increment cost due to minute time

Increment cost due to 100 metres distance Update display No No No Reset hundred metres counter

Reset seconds counter

Check keypad status for pressed key

Is the stop key pressed? Restore main program registers Restore main program registers

Enable time counter interrupt

Enable sensor interrupt

Return

Return

Figure 2: System flow chart

14

3.1.4 Resource management


In the restricted environment of a microcontroller the memory requirements needs to be taken into consideration early from the design stage so that a microcontroller with sufficient resources for the design can be selected. Variable or Module Real time clock User settings Stack Local variables Total RAM estimate Constants Interrupt service routines Initialisation Display Keypad decode Total ROM estimate Resources (bytes) 10 20 100 200 330 10 300 100 400 100 910

3.2 Components selection


This section give information about the components selected to provide building blocks from the functional and system requirements identified.

3.2.1 PIC16F877A microcontroller


This is the preferred microcontroller choice in this design due to the following advantages of Microchips PIC microcontroller family products: The availability of excellent low-cost and free development tools. The largest and strongest user Internet based community of probably any silicon chip family. An outstanding distributor network with a wide variety of parts available in very short notice. A wide range of devices with various features that just about guarantees that there is a microcontroller suitable for any application.

15

Microchip's efforts at continually improving and enhancing the PIC MCU family based on customer's needs. High-Performance RISC CPU which means all instructions are single-cycle except for program branches which needs two instruction cycles. It has enhanced flash program memory (EEPROM) package with typical 100,000 erase/write cycle. It has Data EEPROM memory with a typical 1,000,000 erase/write cycle. Data EEPROM Retention time of at least 40 years. It has a Low-power CMOS Technology with a fully static design and a wide operating voltage range (2.0V to 5.5V). Internal Watchdog Timer (WDT) with its own on-chip RC oscillator for reliable operation Programmable code protection capability. Power saving Sleep mode ability. Selectable oscillator options.

These strengths have contributed to the Microchip PIC8-bit MCU being the second most popular microcontroller product in the world today (1as of 2010). This is up from the twentieth position in 1995.

www.microchip.com

16

The PIC16F877A microcontroller belongs in a midrange family of microchips microcontroller products. It is a 40 pins flash based 8-bit CMOS microcontroller with the following main features

Table 1:PIC16F877A features Key Features Operating Frequency Resets (and Delays) Flash Program Memory (14-bit words) Data Memory (bytes) EEPROM Data Memory (bytes) Interrupts I/O Ports Timers Capture/Compare/PWM modules Serial Communications Parallel Communications 10-bit Analogue-to-Digital Module Analogue Comparators Instruction Set Packages PIC16F877A DC 20 MHz POR, BOR (PWRT, OST) 8K 368 256 15 Ports A, B, C, D, E 3 2 MSSP, USART PSP 8 input channels 2 35 Instructions 40-pin PDIP 44-pin PLCC 44-pin TQFP 44pin QFN

The other important features of PIC16F877A which are important in this design include It contains internal 16bit TIMER1 which can be used to monitor the elapsed time for billing purposes. This timer will cause an interrupt each moment it overflows and its interrupt on overflow can be monitored for elapsed time for billing. It has PORTB 0 external interrupt which can be used to monitor the wheel revolution sensor interrupt, such that each moment the PORTB 0 changes from low to high by an external sensor; an interrupt for a wheel revolution will be generated. The PORTB 0 has internal pull capability which means the pins on this port can be configured to be internally tied to logic HIGH by being internally connected to V dd , and thus when they change to logic LOW via a grounding switch caused by

17

an external event such as key press an appropriate action can be taken due to this external interrupt by a microcontroller. Brown-out detection circuitry for Brown-out Reset (BOR) which has the ability of detecting the unsafe operation voltage and will reset the MCU should it detect anomalous power state.

3.2.2 JHD162A DISPLAY


This is a liquid crystal display with two rows (lines) and sixteen columns (characters) alphanumeric characters display capability which will be used to provide the graphical user interface to the users, by displaying visual information about available choices, time, distance and cost of the journey.

JHD162A contains HD44780U internal display controller which is capable of accepting data sent in either 4bit two operations or 8bit one operation ,so that it is capable of interfacing with both 4bit or 8bit microprocessor cores. Since in this design an 8bit mode will be used because the PIC16F877A microcontroller has an 8bit data processing core, in addition to that so as to achieve better performance an 8bit mode is preferred as few operations will be needed which consequently give short execution time as compared to 4bit mode which needs twice as much operations and thus time to display the same number of characters.

When the JHD162A display is not enabled, data lines are in tri-state mode which means they are in a state of high impedance (i.e. they appear as if they are disconnected) and this means they do not interfere with the operation of the microcontroller when the display is not being addressed.

JHD162A display has 16pin connector for interfacing the display to a microcontroller V ss this is the 0V grounding pin.

18

V dd this is the pin which is connected to the positive power supply, the manufacturers recommended supply is 5V,however the module can be operated as low as 3V or as high as 6V.

V ee this is the pin used to control the contrast of the display and thus should be connected to a variable voltage supply or it can be connected to ground if contrast adjustment is not needed.

RS this is the register select pin when it is low data transferred to the display is treated as commands on the other hand when RS is high a character can be transferred to or from the module.

R / W Pin this is the pin which is pulled low in order to write commands or
character data to the LCD module, also when this pin is high character data or status information can be read from the module. This pin is usually connected to ground because we normally write to the LCD module rather than read from it.

EN pin this is an enable pin which is used to initiate the transfer of commands or data between LCD module and microcontroller. when writing to the display data is transferred only on the high to low transition of this pin .when reading from the display data becomes available after the low to high transition of the enable pin and this data remains valid so long as the enable pin is high.

Pins 7 to 14 are eight data bus lines (D 0 to D 7 ) and will be used to transfer display characters to the LCD module.

Pin 15 provides an anode connection pin for LED backlight. Pin 16 provides a cathode for LED backlight.

3.2.3 Keypad
This is the twelve button 43 switch matrix keypad which allows the microcontroller to capture user settings and supervisory commands from the user. Functionally the keypad is simply a set of switches connected in a row and column arrangement and accessed by a scanning routine.

19

If the row inputs (A, B, C, D) are all set high initially and no button is pressed all the column outputs (1, 2, 3) will be high (i.e. pulled up to 5V). However if a logical LOW is output on each row in turn and a button pressed that LOW will appear at the column output and thus can be read into the PIC, the combination of active row and column identifies the pressed key by the microcontroller.

3.2.4 Pushbutton switch


This is a device which enables the wheel revolution to be sensed by a microcontroller, the main interest here is not to switch directly a voltage or current but rather to convert the switch position in to a logic level that can be read by a microcontroller port.

This is achieved in this design by internally puling up the PORTB 0 to V dd such that when this push button is pressed due to wheel revolution the PORTB 0 will go LOW and this will generate an external interrupt on the microcontroller. The pushbutton switch is chosen in this design due its following features It is simple to interface with the microcontroller since it is a passive sensor which means it does not require any signal conditioning mechanism. It is very economical as compared to other active sensors such as optoelectronic sensors which contain transduction mechanism to transform optical signal in to electrical signal. It does not require any analogue to digital conversion.

20

Chapter 4 Device configuration


This is the section which describes the design of the system by first describing the various configuration registers together with the justification of the configured choice. Because within any electronic device the configuration registers are the most important registers since they determine the overall behaviour of the electronic device which in this case is the PIC16F877A microcontroller unit.

The device configuration relevant to this design has four main distinct categories namely Power configuration Oscillator configuration Interrupts configuration I/O ports configuration

4.1 Power configuration


This is an important configuration with in a microcontroller as it determines the power status and behaviour of the microcontroller during initialisation and operation. It achieves this by controlling the PWRT and OST modules. PWRT module is the timer that provides a fixed 72 ms nominal time-out during power-up (that is from the POR). Because Power-up Timer operates on an internal RC oscillator the chip is kept in RESET as long as the PWRT is active (i.e. first 72msec after power up). This power up timer delay allows V dd to rise to an acceptable safe level. A configuration bit with in CONFIGURATION WORD REGISTER<3> provides the option of enabling or disabling the PWRT.

OST module is the module that is intended to keep the chip in Reset until the crystal oscillator is stable The Oscillator Start-up Timer (OST) provides a delay of 1024 oscillator cycles (from OSC1 input) after the PWRT delay is over (i.e. if PWRT is

21

enabled). This helps to ensure that the crystal oscillator or resonator has started and has stabilised. The OST time-out is invoked only for XT, LP and HS modes and only on Power-on Reset or wake-up from Sleep.

The PIC16F877A differentiates between various kinds of RESET conditions Power-on Reset (POR) MCLR Reset during normal operation MCLR Reset during SLEEP WDT Reset (during normal operation) WDT Wake-up (during SLEEP) Brown-out Reset (BOR)

4.1.1 Power-On Reset (POR)


A Power-on Reset pulse is generated on-chip when V dd rise is detected (in the range of 1.2V - 1.7V). To take advantage of the POR, I tie the MCLR pin through a resistor (so as to protect the MCU from spurious voltage spikes) to V dd . This will eliminate external RC components usually needed to create a Power-on Reset. From the device datasheet a maximum rise time for PIC16F877A V dd is 10seconds. Now when the device starts normal operation (i.e. exits the RESET condition), device operating parameters (voltage, frequency, current and temperature) must be met with in 10seconds to ensure smooth operation. If these conditions are not met, the device must be held in RESET until the operating conditions are met. Brown-out Reset is be used to meet the start-up conditions since it is the one which controls the power-up start timer (PWRT).

22

4.1.2 MCLR Reset during normal operation


This is the master clear of the device which can be triggered by setting the MCLR low and it will reset the device into an initial known safe state by clearing the entire RAM and starting program execution all over again. PIC16F877A devices have an internal noise filter in the MCLR reset path the filter which will detect and ignore small pulses. From the datasheet PIC16F877A requires the low pulse width to be at least 2seconds to have a valid reset signal.

Figure 3: Reset circuit

4.1.3 MCLR reset during sleep


This is the reset condition which wakes up the microcontroller from sleep by driving the MCLR low. The external MCLR Reset will cause a device Reset. And all other events will be considered a continuation of program execution before entering the initial sleep state and thus cause a wake-up.

Microcontroller compiled tips n tricks pp24- Microchip cooperation

23

The TO and PD bits in the Status register can be used to determine the cause of device Reset. The PD bit, which is set on power-up, is cleared when Sleep is invoked. The TO bit is cleared if a WDT time-out occurred and caused wake-up.

4.1.4 WDT reset (During normal operation)


The Watchdog Timer is a free running, on-chip RC oscillator which does not require any external components. This RC oscillator is separate from the RC oscillator of the OSC1/CLKI pin. If this timer is enabled and it has not been reset within a specific amount of time it will timeout cause a reset situation on the microcontroller. But in this design this timer is disabled because its reset functionality is not needed.

4.1.5 WDT Wake-up (during SLEEP)


During normal operation, a WDT time-out generates a device Reset (Watchdog Timer Reset). Also if the device is in Sleep mode, a WDT time-out causes the device to wakeup and continue with normal operation (Watchdog Timer Wake-up). Because the WDT clock is independent from the external or internal system clock, then this means that the WDT will run even if the external clock on the OSC1/CLKI and OSC2/CLKO pins of the device has been stopped, for example, by execution of a SLEEP instruction. The TO bit in the Status register will be cleared upon a Watchdog Timer time-out.

4.1.6 Brown-out Reset (BOR)


The configuration bit, BODEN, can enable or disable the Brown-out Reset circuit. If V dd falls below V BOR (about 4V) for longer than T BOR (about 100sec) the brown-out situation will reset the device. On the other hand if V dd falls below V BOR for less than

24

T BOR , a RESET may not occur. This feature will be implemented so as to have a reliable microcontroller system which is intelligent enough to shut down when supplied power falls below optimal operating values.

Once the brown-out occurs, the device will remain in Brown-out Reset until V dd rises above V BOR . The Power-up Timer then keeps the device in RESET for T PWRT (about 72msec). If V dd should fall below V BOR during power-up timer (T PWRT ), the Brown-out Reset process will restart when V dd rises above V BOR with the Power-up Timer Reset. The Power-up Timer is always enabled when the Brown-out Reset circuit is enabled, regardless of the state of the PWRT configuration bit.

The above configurations choices are controlled and/or monitored by the microcontroller by using the following two registers; Power control/status registers (PCON) Configuration word register

Power Control/Status Register (PCON)


The Power Control/Status Register, this is an important register with in the microcontroller used to indicate the power status during transitioning from powering up or reset condition. The power status indicated enables the programmer to take appropriate action. PCON Register Bit# 7 6 5 4 3 2 1 0 0 0 0 0 0 0 POR BOR . 7-2: Unimplemented bits (read as 0) 1: POR : Power-on Reset Status bit 1 = No Power-on Reset occurred 0 = A Power-on Reset occurred (must be set in software after a Power-on Reset occurs)

25

0:

BOR : Brown-out Reset Status bit 1 = No Brown-out Reset occurred 0 = A Brown-out Reset occurred (must be set in software after a Brown-out Reset or Power-on Reset occurs)

Bit 0 is Brown-out Reset Status bit this bit is unknown on a Power-on Reset. It is recommended to the user to set it and check its status on subsequent RESETS to see if bit BOR cleared, indicating a BOR occurred. However when the Brown-out Reset is disabled, the state of the BOR bit is unpredictable and is, therefore, not valid at any time. Bit 1 is POR (Power-on Reset Status bit). It is cleared on a Power-on Reset and unaffected otherwise. The user must set this bit following a Power-on Reset.

Device Configuration Word Register


The device configuration register bits allow each user to customize certain aspects of the device to the needs of the application. When the device powers up, the state of these bits determines the modes that the device uses. These bits are mapped in program memory location 2007h. This location is not accessible during normal device operation (can be accessed only during programming mode).

The configuration bits can be programmed (read as '0') or left un-programmed (read as '1') to select various device configurations. The ability to change these settings once they have been programmed depends on the memory technology and the package type. For Read Only Memory (ROM) devices, these bits are specified at time of ROM code submittal and once the device is masked may not be changed for those devices (would require a new mask code).For One Time Programmable (OTP) devices, once these bits are programmed (0), they may not be changed. For windowed EPROM devices, once these bits are programmed (0), the device must be UV erased to return the configuration word to the erased state. UV erasing the device also erases the program memory. For Flash devices, these bits may be erased and reprogrammed.

26

In this design due to advantage of flexibility in prototyping the flash memory device is used. The program word register is then programmed as; Bit# 13 12 1 1 Bit# 13: 12: Flash memory code protection is DISABLED Unimplemented bit (recommended to read as 1)

11 1

10 1

9 1

8 1

7 0

6 1

5 1

4 1 0

3 0

2 0

0 1

10-9: WRT flash program memory write is DISABLED as the result the unprotected memory location can be written by EECON control 8: 7: CPD data EE memory code protection is DISABLED LVP: low voltage in circuit serial programming is DISABLED as the result RB3 is digital I/O and high voltage programming must be used on MCLR pin for downloading application code to the chip. 6: 5-4: 3: 2: 1-0: BOREN brown-out reset control bit is ENABLED Unimplemented manufacturer recommends to read as 1

PWRTEN power up timer control bit is ENABLED


WDTE watch dog timer control bit is DISABLED FOSC1:FOSC0 oscillator selection bits crystal (resonator) oscillator XT mode selected

4.2 Oscillator configuration


PIC16F877A device can have up to four different oscillator modes. The user can program up to two device configuration bits (FOSC1 and FOSC0) in order to select one of these FOUR oscillator modes by either selecting

27

Table 2: Oscillator frequency configuration choices Configuration bits OSC OSC Comment FOSC1:FOSC0 Mode Feedback Inverter Gain 11 RC Least expensive solution for device oscillation (only an external resistor and capacitor is required). Most variation in time-base. Devices default mode. 10 HS High Gain High frequency application. Oscillator circuits mode consumes the most current of the three crystal modes. 01 XT Medium Standard crystal/resonator frequency. Gain Oscillator circuits mode consumes the middle current of the three crystal modes. 00 LP Low Gain Low power/frequency applications. Oscillator circuits mode consumes the least current of the three crystal modes. In XT, LP or HS modes, a crystal or ceramic resonator is connected to the OSC1/CLKIN and OSC2/CLKOUT pins to establish oscillation. The PIC16F876 oscillator design requires the use of a parallel cut crystal. Use of a series cut crystal may give a frequency out of the crystal manufacturers specifications. When in XT, LP or HS modes, the device can have an external clock source to drive the OSC1/CLKIN pin.

In this design a XT mode is preferred since it requires the optimum current out of the three possible crystal oscillator modes which is crucial since the source of power will come from dry cell batteries. In addition to that, also due to small frequency of XT mode the effects of the electromagnetic interference are minimal, this is important so as to minimize the interference to the electronics systems of the taxicab. Table 3: Recommended capacitors for crystal oscillator Oscillator type Crystal Freq. Cap. Range C1 Cap. Range C2 LP 32 kHz 33pF 33 pF 200 kHz 15 pF 15 pF XT 200 kHz 47-68 pF 47-68 pF 1MHz 15 pF 15 pF 4 MHz 15 pF 15 pF HS 4 MHz 15 pF 15 pF 8 MHz 18-33 pF 15-33 pF 20 MHz 15-33 pF 15-33pF

28

In this design a clock rate of 1MHz ( 10 6 Hz) is chosen because a 2second interval interrupt is desired from an internal 16bit TIMER1 which has the maximum pre-scale value of 1:8 Then 1 instruction takes 4 10 6 sec = 4sec Selecting the prescale value of 1:8 then the counter increments every: 84sec= 32sec For the 16bit TIMER1 counter to overflow it will have to reach 65536 in 6553632 = 2.097seconds 2seconds Then after every 2 seconds an interrupt will be received by the microcontroller with a 1MHz clock, this interrupt will be used to monitor the time of the journey for billing purposes.

4.3 Interrupt Configuration


PIC16F877A microcontroller can have many sources of interrupt. These sources generally include one interrupt source for each peripheral module, though some modules may generate multiple interrupts (such as the USART module). The interrupts supported by PIC16F877A microcontroller are: INT Pin Interrupt (external interrupt) TMR0 Overflow Interrupt PORTB Change Interrupt (pins RB7:RB4) Comparator Change Interrupt Parallel Slave Port Interrupt USART Interrupts Receive Interrupt Transmit Interrupt A/D Conversion Complete Interrupt Data EEPROM Write Complete Interrupt Timer1 Overflow Interrupt

29

Timer2 Overflow Interrupt CCP Interrupt SSP Interrupt

In this design I will use only two interrupt sources namely; TIMER1 OVERFLOW INTERRUPT for managing the billing time and PORTB0/INT EXTERNAL INTERRUPT from the pushbutton switch which is used to monitor the distance covered. There are five registers used in the control and status of the two interrupts required in this design. The registers needed to be configured for the interrupts are INTCON register OPTION_REG register PIE1 register PIR1 register T1CON register

4.3.1 INTCON register


The INTCON Register is a readable and writable register, which contains various enable and flag bits for the TMR0 register overflow, RB Port change and External RB0/INT pin interrupts. Bit# 7 1 Bit# 7: GIE: Global Interrupt Enable bit is ENABLED; this implies all unmasked interrupts are enabled. 6: PEIE: Peripheral Interrupt control bit is ENABLED; this implies all unmasked peripheral interrupts are enabled 5: 4: 3: T0IE: TMR0 Overflow Interrupt Control bit is DISABLED INTE: RB0/INT External Interrupt Control bit is ENABLED RBIE: RB Port Change Interrupt Control bit is DISABLED 30

6 1 0

5 1

4 0

2 T0IF

1 INTF

0 RBIF

2:

T0IF: TMR0 Overflow Interrupt Flag bit 1 = TMR0 register has overflowed (must be cleared in software) 0 = TMR0 register did not overflow

1:

INTF: RB0/INT External Interrupt Flag bit 1 = The RB0/INT external interrupt occurred (must be cleared in software) 0 = The RB0/INT external interrupt did not occur

0:

RBIF: RB Port Change Interrupt Flag bit 1 = At least one of the RB7:RB4 pins changed state; a mismatch condition will continue to set the bit. Reading PORTB will end the mismatch condition and allow the bit to be cleared (must be cleared in software). 0 = none of the RB7:RB4 pins have changed state

4.3.2 OPTION_REG register


The OPTION_REG Register is a readable and writable register, which contains various control bits to configure the TMR0 prescaler/WDT postscaler (single assignable register known also as the prescaler), the External INT Interrupt, TMR0 and the weak pull-ups on PORTB. Bit# 7 0 Bit# 7: 6: 6 1 0 5 0 4 1 3 1 2 1 1 1 0

RBPU : PORTB Pull-up control bit is ENABLED.


INTEDG: Interrupt Edge Select bit Interrupt ON RISING EDGE ) of RB0/INT ( pin is selected T0CS: TMR0 Clock Source Select bit unimplemented (read as 0) T0SE: TMR0 Source Edge Select bit unimplemented (read as 0) PSA: Prescaler Assignment bit is reserved for WDT instead of TMR0 PS2:PS0: Prescaler Rate Select bits 1:128

5: 4: 3: 2-0:

31

Bit Value 000 001 010 011 100 101 110 111

Table 4: Prescaler rate select bits TMR0 Rate WDT Rate 1:2 1:1 1:4 1:2 1:8 1:4 1:16 1:8 1:32 1:16 1:64 1:32 1:128 1:64 1:256 1:128

4.3.3 PIE1 register


The PIE1 register contains the individual control bits for the peripheral interrupts Bit# 7 0 Bit# 7: 6: 5: 4: 3: 2: 1: 0: PSPIE: Parallel Slave Port Read/Write Interrupt Control bit is DISABLED. ADIE: A/D Converter Interrupt Control bit is DISABLED RCIE: USART Receive Interrupt Control bit is DISABLED TXIE: USART Transmit Interrupt Control bit is DISABLED SSPIE: Synchronous Serial Port Interrupt Control bit is DISABLED CCP1IE: CCP1 Interrupt Control bit is DISABLED TMR2IE: TMR2 to PR2 Match Interrupt Control bit is DISABLED TMR1IE: TMR1 Overflow Interrupt Control bit is ENABLED 6 0 0 5 0 4 0 3 0 2 0 1 1 0

32

4.3.4 PIR1 register


The PIR1 register contains the individual flag bits for the peripheral interrupts. Bit# 7 6 5 4 3 2 1 0 PSPIF PSPIF RCIF TXIF SSPIF CCP1IF TMR2IF TMR1IF Bit# 7: PSPIF: Parallel Slave Port Read/Write Interrupt Flag bit 1 = A read or a write operation has taken place (must be cleared in software) 0 = No read or write has occurred. 6: ADIF: A/D Converter Interrupt Flag bit 1 = An A/D conversion completed 0 = The A/D conversion is not complete 5: RCIF: USART Receive Interrupt Flag bit 1 = The USART receive buffer is full 0 = The USART receive buffer is empty 4: TXIF: USART Transmit Interrupt Flag bit 1 = The USART transmit buffer is empty 0 = The USART transmit buffer is full 3: SSPIF: Synchronous Serial Port (SSP) Interrupt Flag 1 = The SSP interrupt condition has occurred, and must be cleared in software before returning from the Interrupt Service Routine. The conditions that will set this bit are: SPI - A transmission/reception has taken place. I2C Slave - A transmission/reception has taken place. I2C Master - A transmission/reception has taken place. - The initiated START condition was completed by the SSP module. - The initiated STOP condition was completed by the SSP module. - The initiated Restart condition was completed by the SSP module. 33

- The initiated Acknowledge condition was completed by the SSP module. - A START condition occurred while the SSP module was idle (Multi-Master system). - A STOP condition occurred while the SSP module was idle (Multi-Master system). 0 = No SSP interrupt condition has occurred 2: CCP1IF: CCP1 Interrupt Flag bit Capture mode: 1 = A TMR1 register capture occurred (must be cleared in software) 0 = No TMR1 register capture occurred Compare mode: 1 = A TMR1 register compare match occurred (must be cleared in software) 0 = No TMR1 register compare match occurred PWM mode: Unused in this mode 1: TMR2IF: TMR2 to PR2 Match Interrupt Flag bit 1 = TMR2 to PR2 match occurred (must be cleared in software) 0 = No TMR2 to PR2 match occurred 0: TMR1IF: TMR1 Overflow Interrupt Flag bit 1 = TMR1 register overflowed (must be cleared in software) 0 = TMR1 register did not overflow

4.3.5 T1CON register


This is the register which is used to configure the Timer1 peripheral. Timer1 module is a 16-bit timer/counter consisting of two 8-bit registers (TMR1H and TMR1L) which are readable and writable. The TMR1 Register pair (TMR1H:TMR1L) increments from 0000h to FFFFh and rolls over to 0000h. The TIMER1 Interrupt, if enabled, is generated on overflow which is latched in the TMR1IF interrupt flag bit. This interrupt can be enabled/disabled by setting/clearing the TMR1IE interrupt enable bit. 34

TIMER1 can operate in one of three modes, the operating mode is determined by clock select bit, TMR1CS (T1CON<1>), and the synchronization bit, T1SYNC.the three possible operation modes are As a synchronous timer As a synchronous counter As an asynchronous counter

In timer mode, TIMER1 increments every instruction cycle while in counter mode, it increments on every rising edge of the external clock input on pin T1CKI.

TIMER1 can be turned on and off using theTMR1ON control bit (T1CON<0>). TIMER1 also has an internal reset input, which can be generated by a CCP module.Timer1 has the capability to operate off an external crystal. When the Timer1 oscillator is enabled (T1OSCEN is set), the T1OSI and T1OSO pins become inputs. That is, their corresponding TRIS values are ignored.

In this design the TIMER1 will be used as a synchronous timer to provide an interrupt after every 2 seconds. Bit# 7 0 Bit# 7-6: 5-4: 6 0 1 5 1 4 0 3 1 2 0 1 1 0

Unimplemented (read as 0) T1CKPS1:T1CKPS0: Timer1 Input Clock Prescale Select bits 1:8 ENABLED 11 = 1:8 Prescale value 10 = 1:4 Prescale value 01 = 1:2 Prescale value 00 = 1:1 Prescale value

3:

T1OSCEN: Timer1 Oscillator Control bit is DISABLED this implies then the counter increment on every prescaled instruction cycle

35

2:

T1SYNC : Timer1 External Clock Input Synchronization Control bit is


DISABLED; then synchronization is ignored since an internal oscillator is used which needs no synchronization

1: 0:

TMR1CS: Timer1 Clock Source Select bit internal clock is used TMR1ON: Timer1 On CONTROL bit is ENABLED

4.4 I/O Ports Direction


The PIC16F877A has three input/output ports namely A, B and C which allows the microcontroller to monitor and control other devices, each port has a corresponding PORT register and TRIS data direction register. PORT register is the latch for the data to be output. When the PORT is read, the device reads the levels present on the I/O pins (not the latch). This means that care should be taken with read-modify-write commands on the ports and changing the direction of a pin from an input to an output. TRIS register is used to control the data direction, for most ports, the I/O pins direction (input or output) is controlled by this data direction register, that is the TRIS<x> bit controls the direction of PORT<x> pin. A 1 in the TRIS bit corresponds to that pin being an input, while a 0 corresponds to that pin being an output. However this configuration can be overridden when peripheral is enabled at multiplexed general I/O port the functionality of the I/O pins may change to accommodate the requirements of the peripheral module

4.4.1 Port A
PORTA is a 6-bit wide, bi-directional port, only PORTA<4> pin is a Schmitt Trigger input and an open drain output. All other PORTA port pins have TTL input levels and full CMOS output drivers. All pins have data direction bits (TRIS registers) which can configure these pins as either output or input.

36

Setting a TRISA register bit puts the corresponding output driver in a hi-impedance mode. Clearing a bit in the TRISA register puts the contents of the output latch on the selected pin(s). In this design the PORTA is unused, left for further improvement of the design hence the TRIS register is left programmed as Bit# 7 0 6 0 0 5 0 4 0 3 0 2 0 1 0 0

4.4.2 Port B
PORTB is an 8-bit wide, bi-directional port the appropriate register for direction of data is TRISB at address 86h; each of the PORTB pins has a weak internal pull-up resistor (i.e. resistor that defines the line to logic HIGH). A single control bit in OPTION_REG can turn on all the pull-ups this is performed by clearing bit RBPU (OPTION<7>). The weak pull-up is automatically turned off when the port pin is configured as an output and the pull-ups are disabled on a Power-on Reset so we need to enable it at initialisation routine just after the device powers up.

Four of the PORTB pins, RB7:RB4, have an interrupt on change feature. Only pins configured as inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is excluded from the interrupt on change comparison). The input pins (of RB7:RB4) are compared with the old value latched on the last read of PORTB. The mismatch outputs of RB7:RB4 are ORed together to generate the RB Port Change Interrupt with flag bit RBIF (INTCON<0>). RB0/INT is an external interrupt input pin and is configured using the INTEDG bit (OPTION_REG<6>) in this design this will be used to monitor an interrupt from wheel revolution sensor, then the TRIS register for port B becomes. Bit# 7 0 6 0 0 5 0 4 0 3 0 2 0 1 1 0

37

4.4.3 Port C
PORTC is an 8-bit bi-directional port. Each pin is individually configurable as an input or output through the TRISC register. PORTC pins have Schmitt Trigger input buffers and it will be used to provide interface to the 43 keypad, then the TRIS register for port C is programmed as. Bit# 7 1 6 1 1 5 1 4 1 3 0 2 0 1 0 0

4.4.4 Port D
PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configurable as an input or output. PORTD can also be configured as an 8-bit wide microprocessor port (Parallel Slave Port) by setting control bit, PSPMODE (TRISE<4>). In such a mode, the input buffers are TTL, however this design will use this port as a normal I/O port with 8bit parallel data bus to the LCD screen Bit# 7 0

6 0 0

5 0

4 0

3 0

2 0

1 0

4.4.5 Port E
PORTE has three pins (RE0/RD/AN5, RE1/WR/AN6 and RE2/CS/AN7) which are individually configurable as inputs or outputs. These pins have Schmitt Trigger input buffers. The PORTE pins become the I/O control inputs for the microprocessor port when bit PSPMODE (TRISE<4>) is set.

In this mode, the user must make certain that the TRISE<2:0> bits are set and that the pins are configured as digital inputs. Also, ensure that ADCON1 is configured for digital I/O. In this mode, the input buffers are TTL. The TRISE register also controls the Parallel Slave Port operation.

38

PORTE pins are multiplexed with analogue inputs. When selected for analogue input, these pins will read as 0s. TRISE controls the direction of the RE pins, even when they are being used as analogue inputs. The user must make sure to keep the pins configured as inputs when using them as analogue inputs.

In this design this port is left unused for further improvement of the design, and thus the TRISE register is programmed as; Bit# 7 0 6 0 0 5 0 4 0 3 0 2 0 1 0 0

39

Chapter 5 Software implementation


Although microcontrollers have been traditionally been programmed using the assembly language of the target device in this implementation a high level language will be used because high-level languages offer several desirable advantages for this design project as compared to the assembly language: It is easier to develop programs using a high-level language. Program maintenance is much easier if the program is developed using a highlevel language. Testing a program developed in a high-level language is much easier. High-level languages are more user-friendly and less prone to making errors. It is easier to document a program developed using a high-level language.

In addition to the above advantages, high-level languages also have some disadvantages. For example, the length of the code in memory is usually larger when a high-level language is used, and the programs developed using the assembly language usually run faster than those developed using a high-level language. The application software code was implemented by using MikroC MikroElektronika cooperation C compiler for Microchip PIC microcontrollers version: 8.0.0.0. This high level language C compiler was chosen for software implementation due to its following advantages The C compiler (MikroC) is well documented in a downloadable user manual. Includes a good range of peripheral driver libraries, including CAN, Ethernet, and graphical LCD drivers as part of a comprehensive I/O library. The packages are oriented toward the educational and hobby market, offering additional features designed to assist the beginner in developing C applications.

The pseudo code derived from the modelled system flow chart in chapter2 has the following sequence of activities.

40

1. Program initialises. 2. User prompted for choice from available options. 3. IF start key chosen continue to step4 ELSE go back to step2. 4. Update the display screen. 5. Check for keypad status. 6. IF stop key is pressed from keypad stop and wait for start key press ELSE go back to step4.

In this design the modelled system flow chart of the application program has three parallel threads that implements the above pseudo code namely Main program thread block. TIMER1 overflow interrupt time cost ISR thread. PORTB 0 external interrupt distance cost ISR thread.

5.1 Main program thread


The main program block has three functionalities It initialises the microcontroller to an initial state by clearing executing the initialisation routine. It updates the display screen by executing the update display routine. It checks the keypad for pressed key options and takes appropriate action according to the captured user choice.

5.1.1 Initialisation
In this stage the main program sets the configuration registers with appropriate values and ensures that the microcontroller is within a desirable initial state for safe and reliable operation of the microcontroller. In this routine the configuration registers are programmed with the desired values and the program global variables are initialised to their default values.

41

5.1.2 Update LCD display


In this stage the main program updates the alphanumeric display with the values of time, distance and cost. To not interfere with the display controller (HD44780) operation interrupts are temporarily disabled during this procedure and the numeric values are first converted into string character buffer before being sent to the display, since the display controller is character based.

5.2 Distance cost ISR thread


This is the interrupt service routine for handling the PORTB 0 external interrupt; it achieves this by adding the metres counter to itself and then checks to see this running sum if it has reached 100metres (0.1km), so that the cost can be calculated (i.e. billing in this design is by each 0.1km covered distance). Then the 100metres counter is checked if it has reached 1000metres (1km) so that the kilometres distance counter can be updated and 100metres counter reset. Then the function is implemented as.

5.3 Time cost ISR thread


This is the interrupt service routine for handling the TIMER1 overflow interrupt which occurs after every 2 seconds. In this routine the seconds counter is monitored if it has reached one minute so that the billing cost can be calculated. (i.e. billing is by each elapsed minute).

42

Chapter 6 Hardware implementation


This is the section which describes the hardware modules interconnection implementation scheme so as to achieve a working system by using the Proteus professional version 7.2 Labcenter electronics.

Proteus VSM is an interactive electronics design package from Labcenter Electronics that allows analogue, digital, and microprocessor circuits to be subjected to virtual testing before the creation of a PCB layout for the construction of real hardware. ISIS is the schematic capture package, and ARES is the layout package.

The circuit is entered directly onto the schematic by selecting components from a library of parts, which have associated mathematical models (e.g., V= IR for a resistor). When completed, the wiring schematic is converted to a set of nodes connected by components, represented by a set of simultaneous equations derived from the model for each component. The network is solved for any given set of inputs and the outputs are displayed via active on-screen components, virtual instruments, or charts.

The microcontroller is simulated on the basis of its internal architecture and the specific program being executed, which must be attached to complete the model. In our case, the program is written in C and the HEX byte file produced by the compiler is attached to the MCU. This file contains the program machine code and some additional information to help with debugging the program. ISIS allows the source code and variables to be displayed so that the program operation can be studied step by step and any functional errors corrected.

43

6.1 Power supply


In this design since the electronics components used all use 5v supply voltage hence the V dd is tied to the voltage supply with a decoupling capacitor. The decoupling capacitor is used to minimize the effects of rapid changes in power demands by devices in the circuit (including the PIC16F877A). A decoupling capacitor can be thought of as a filter that smoothes out the rough spots of the power supply and provides additional current for high load situations on the circuit. For this design tantalum decoupling capacitors at 5 volts, I use parts that are rated at 16 volts (which is a de-rated value less than one third of the rated value). When tantalum capacitors are first powered up in an application, voltage spikes (which are caused by power supply start up and current transients with in chips) can cause them to develop "pin-hole" breakthroughs in the dielectric, which can cause the plates to touch.
3

When the plates touch, heat is generated by the short circuit, which boils away more

dielectric. This process snowballs until the part explodes or catches fire. By derating the capacitor values, the dielectric layer is thicker, minimizing the opportunity for pinholes to develop. Decoupling capacitors are to be placed across V dd and V ss of LCD and MCU, because these are the components in this design which can develop significant current transients. This does complicate the wiring somewhat, but does make a more reliable microcontroller circuit. From PIC16F877A datasheet the maximum current into V dd pin 250 mA and maximum current out of V ss pin 300 mA. To be on the safe side current in to V dd is de-rated by 40%, then I dd = 150mA. Now to protect the microcontroller from voltage spikes I allow 0.5V to drop across the protection resistance such that i have V dd =4.5V. Then from Ohms law the protection resistance is obtained as:
3

PIC microcontrollers, programming and customising pp70 by Myke Predko

44

r=

v 0.5v = = 3.3333 3.3 i 250mA

Then by using the standard resistor value i have R PIC = 3.3 with I dd at 150mA

5V DC SUPPLY

3.3

Vdd

PIC16 F 877 A
0.1F

V ss

Figure 4: PIC power stabilisation supply

Similarly from LCD screen datasheet the maximum supply current is 3mA then derating this by 40% i have 1.8mA, and by allowing 0.5V to drop across the protection resistor the value of protective resistor for display is obtained as; By ohms law
r= 0.5v v = 277.78 270 i 1.8mA

45

Then using the standard value I have R LCD =270 with the I dd at 1.8mA
5V DC SUPPLY

270

Vdd

JHD162 A
0.1F

V ss

Figure 5: LCD Power stabilisation circuit

6.2 Device interfacing


6.2.1 Interfacing PIC16F877A and LCD screen
From the system modelling the PIC16F877A will be interfaced with 8-data wires using a PORTD (i.e. data port) and the control from PORTB (i.e. control port) of microcontroller. And from PIC16F877A device data sheet the maximum supply voltage for logic (i.e. control and data port signals) is given by V OH = V dd - 0.7V with I OH (max) =3mA

46

Since in this design chosen V dd is 4.5V this means the PORTB and PORTD output logical high voltage will be 3.8V at a maximum operational current of 3mA.

Now from the LCD display datasheet the maximum input current value for the each data pin of LCD module is 3mA and logical high voltage ranges from 2.2V to V dd (i.e. 2.2V to 4.5V) and then this means the LCD module can be safely directly connected to the microcontroller without any protection resistors.

6.2.2 Interfacing PIC16F877A and Keypad


The PIC16F877A will be connected to the 43 keypad by using the first seven pins of PORTC, since the keypad is just a set of matrix switches with the column configured as outputs and rows configured as inputs. Such that the keypad scanning routine pulls up one column at a time and reads the corresponding rows.

From the PIC16F877A datasheet the maximum output high voltage is obtained as above to be 3.8V at a maximum current of 3mA, this will be the output high voltage for the keypad columns that is PORTC pin 4 to 6.

Now since the keypad will be scanned within the same PORTC at pins 0 to 3 and PORTC has Schmitt triggered I/O buffers then the input high voltage needs to be from 0.8 V dd to V dd that is from 3.8V to 4.5V (with V dd =4.5V). From the above paragraph i have deduced that the output from the keypad column will be 3.8V, and then this means this will be enough to trigger a Schmitt buffer input of rows at the maximum input current of 25mA. This implies the keypad can be directly connected to the microcontroller since their logical levels are compatible.

6.2.3 Interfacing PIC16F877A with sensor


The wheel revolution sensor (pushbutton switch) will be connected at PORTB 0 , since the internal pull up on PORTB has been enabled in this design, this means the input ports

47

of PORTB have been internally tied to V dd .which makes the job of this pushbutton is just to bring logical low voltage to the PORTB 0 and this shall cause an external interrupt on the rising edge of PORTB 0 .

Since the PORTB 0 has a Schmitt trigger buffer this implies the logical low is from V ss to 0.2 V dd that is from 0V to 0.9V (with V dd =4.5V), this is achieved by directly tying the PORTB 0 via a pushbutton switch.

6.3 Reset circuit


This is the circuit which is used to restart program execution of the microcontroller that is when a reset occurs the program counter is loaded with instruction at 0000h.this could be useful in case the system is stuck. In this reset circuit the reset occurs when a reset pushbutton is pressed.

To prevent the device from resetting several times during power up transitioning the coupling capacitor is provided in this circuit so as to eliminate the effect of harmful power transients that could set and reset the microcontroller several times when the power is initially applied.

From the RC charging equation Vc = Vdd (1 e t / RC ) For V c to reach 99% of V dd five time constants are essential this time will be enough to allow the power to stabilise i.e. t=5=5RC= 539k0.1 =19.5msec Then 19.5msec after power up the system will be stable and ready for operation.

48

5V

39k

1.8k

MCLR

RESET

PIC16 F 877 A
0.1F

Figure 6: Microcontroller reset circuit From the above identified hardware requirements the following is a summary of required materials for prototype implementation Table 5: Bill of materials (BOM) Quantity: 1 1 2 1 1 1 1 1 1 1 1 1 References RESISTOR1 RESISTOR2 CAPACITOR1, CAPACITOR2 CAPACITOR3 CAPACITOR4 LCD DISPLAY KEYPAD MICROCONTROLLER PARALLEL CUT CRYSTAL OSCILLATOR LCD PROTECTION RESISTOR PIC PROTECTION RESISTOR MINI-PUSH BUTTON SWITCH Value 39k 1.8k 15pF 0.85nF 0.1F JHD162A 43 PIC16F877A 1MHz 270 3.3 SENSOR

49

6.4 Circuit Simulation


The design schematic was developed in ISIS professional release 7.1 and the application is simulated here for a typical routine of steps that occurs in the system;

Step1: User prompted for choice

PROTECTION RESISTOR
VDD 280

LCD1
LM016L

VSS VDD VEE

RS RW E 4 5 6

SENSOR OSCILLATOR
1MHz

100n

1 2 3

15p 13 14 2 3 4 5 6 7

MICROCONTROLLER
OSC1/CLKIN OSC2/CLKOUT RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30

C2
15p

R1
39k

8 9 10

R2
2k

RA0/AN0 RA1/AN1 RA2/AN2/VREF-/CVREF RA3/AN3/VREF+ RA4/T0CKI/C1OUT RA5/AN4/SS/C2OUT RC0/T1OSO/T1CKI RE0/AN5/RD RC1/T1OSI/CCP2 RE1/AN6/WR RC2/CCP1 RE2/AN7/CS RC3/SCK/SCL RC4/SDI/SDA MCLR/Vpp/THV RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 PIC16F877A

C3
0.85n

KEYPAD
1 2 3

4 BY 3

1 4 7

2 5 8 0

3 6 9 #

Figure 7: Taxicab choices

50

7 8 9 10 11 12 13 14

D0 D1 D2 D3 D4 D5 D6 D7

C1

C4

Step2: System goes in to continuous billing loop when start key is pressed to update display and while checking for stop key.
PROTECTION RESISTOR
VDD 280

LCD1
LM016L

VSS VDD VEE

RS RW E 4 5 6
4 BY 3

SENSOR OSCILLATOR
1MHz

100n

1 2 3

15p 13 14 2 3 4 5 6 7

MICROCONTROLLER
RB0/INT RB1 RB2 RB3/PGM RA0/AN0 RB4 RA1/AN1 RB5 RA2/AN2/VREF-/CVREF RA3/AN3/VREF+ RB6/PGC RB7/PGD RA4/T0CKI/C1OUT RA5/AN4/SS/C2OUT RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RE0/AN5/RD RC2/CCP1 RE1/AN6/WR RC3/SCK/SCL RE2/AN7/CS RC4/SDI/SDA MCLR/Vpp/THV RC5/SDO RC6/TX/CK RC7/RX/DT OSC1/CLKIN OSC2/CLKOUT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 PIC16F877A 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30

C2
15p

R1
39k

8 9 10

R2
2k

C3
0.85n

KEYPAD
1 2
A

1 4 7

2 5 8 0

3 6 9 #

Figure 8: Taxicab billing Step3: When destination is reached and the user presses STOP button (#key) to stop billing here the cost is displayed and the system waits for start key for new billing.
PROTECTION RESISTOR
VDD 280

VSS VDD VEE

RS RW E 4 5 6
4 BY 3

SENSOR OSCILLATOR
1MHz

100n

1 2 3

15p 13 14 2 3 4 5 6 7

MICROCONTROLLER
OSC1/CLKIN OSC2/CLKOUT RB0/INT RB1 RB2 RB3/PGM RB4 RB5 RB6/PGC RB7/PGD 33 34 35 36 37 38 39 40 15 16 17 18 23 24 25 26 19 20 21 22 27 28 29 30

C2
15p

R1
39k

8 9 10

R2
2k

RA0/AN0 RA1/AN1 RA2/AN2/VREF-/CVREF RA3/AN3/VREF+ RA4/T0CKI/C1OUT RA5/AN4/SS/C2OUT RC0/T1OSO/T1CKI RC1/T1OSI/CCP2 RE0/AN5/RD RC2/CCP1 RE1/AN6/WR RC3/SCK/SCL RE2/AN7/CS RC4/SDI/SDA MCLR/Vpp/THV RC5/SDO RC6/TX/CK RC7/RX/DT RD0/PSP0 RD1/PSP1 RD2/PSP2 RD3/PSP3 RD4/PSP4 RD5/PSP5 RD6/PSP6 RD7/PSP7 PIC16F877A

C3
0.85n

KEYPAD
1 2
A

1 4 7

2 5 8 0

3 6 9 #

Figure 9: Display bill 51

7 8 9 10 11 12 13 14

D0 D1 D2 D3 D4 D5 D6 D7

C1

C4

LCD1
LM016L

7 8 9 10 11 12 13 14

D0 D1 D2 D3 D4 D5 D6 D7

C1

C4

Chapter 7 Conclusion
In the course of working on this project many things came up, both positive and negative, however to a good extent things have been under control and the system was successful designed. The design worked fine under the emulation environment. However during implementation several challenges were encountered.

7.1 Challenges
Numerous challenges were encountered during the project work implementation firstly was parts availability because initially I had planned to use a four line display screen but had to settle with two line display.

Secondly, parts cost affordability; the real world commercial taxi meters use optical sensors or Hall Effect sensors for rotation detection, due to design budget constraint, I had to use the pushbutton switch which is not durable, since it will wear out in a very short time when implemented on the real world situation.

Thirdly, was the difficulty of obtaining the microcode programmer since there was none within our department then I had to borrow the one from electronics science department this caused many unnecessary hustles and wasted much valuable time during design testing.

7.2 Successes
The system plan was successfully designed, simulated and then tested on the breadboard hardware prototyping circuit, so I could claim that my project objectives have been duly met.

52

7.3 Failures
Although I have been able to model and finally design the prototype; I have failed to come up with quantifiable data and/or mathematical model that justifies by how much my proposed system will reduce the inconveniences suffered by the customers and taxicab drivers due to the present situation.

7.4 Recommendations
The following are my recommendations for the improvement of the proposed microcontroller based TAXI billing system for future works. 1. Sensor improvement: The design could be improved by replacing the pushbutton switch with the optocoupler as a wheel revolution sensor. Because an Optocoupler is a device that combines a LED and photo-transistor in the same case so when a light beam is interrupted (e.g. by a spoke on the wheel) a revolution will be sensed each time the light is interrupted, and the transistor will produce a pulse. In this design this implementation was not used due to prohibitive cost of optocoupler sensors. 2. Statistical records: Keeping statistical records by the microcontroller could improve the financial management usefulness of the system to the users; this could be achieved by attaching to the microcontroller retrievable special flash memory to be used to store a billing log file so that it can be used for later auditing and printing. 3. The government revenue authority (i.e. TRA) can use taximeters to increase the source of revenues from taxi businesses by charging value added tax (VAT) on taxicab business transactions.

53

References:
Ball, S.R (2006),Embedded Microprocessor systems - real world design, Newnes press, New York, 2nd edition. Di Jasio et al (2008); PIC Microcontrollers (know it all), Newnes press, Burlington, M.A, Gardner Nigel (1998); An introduction to programming the microchip PIC in C, Character Press Ltd, U.K. Hitachi cooperation (2000);LMO41L display datasheet Ibrahim, Dogan (2006); Microcontroller Based Digital Control. John Wiley and Sons. Iovine, John (2000); PIC Microcontroller Project Book. McGraw Hill, Inc. Sanchez, Julio, and Maria P Canton (2007); Microcontroller Programming. CRC press Nagy, C. (2003);Embedded Systems Design using the TI MSP 430 series,Newnes press, Burlington M.A. MikroElektronika cooperation (2006); mikroC Users Manual Microchip technology (2001); PIC16F87XA datasheet Microchip technology (2001);PIC Microcontrollers midrange MCU Family Reference Manual Microchip technology incorporated (2009);Microchip Compiled Tips N Tricks Guide Steiner Jack (1980); Taximeter US Patent 4205388 Wilmshurst, T. (2001). An Introduction to the Design of Small-Scale Embedded Systems. Palgrave.

World Wide Web resources http:// www.microchip.com/forums http:// www.edaboard.com/forums

54

Appendix A: Application software code.

55

56

57

58

Appendix B: PROJECT ACTIVITIES

59

Appendix C: project costs


S/N DESCRIPTION 1 Stationery: Plain papers (A4) Marker pen Blue pen Pencil Office file Transport cost Internet access Printing expenses Binding costs Device and components: Resistors/Capacitors pack Micro-controller Prototype board LCD Connecting wires Miscellaneous expenses QUANTITY UNIT COST (TSHS) 7,000/= 500/= 300/= 100/= 2,500/= TOTAL COST (TSHS) 7,000/= 1,000/= 3600/= 500/= 2,500/= 30,000/= 30,000/= 10,000/= 6,000/= 15,000/= 30,000/= 6,000/= 30,000/= 5,000/= 30,000/= 206,600/=

1 rim 2 1 dozen 5 1

2 3 4 5 6

100 pages 2 reports 1 1 1 1

100/= 3,000/= 15,000/= 30,000/= 6,000/= 30,000/= 5,000/= TOTAL

60