+ All Categories
Home > Documents > Prepaid Energy Meter Final Year Project Report

Prepaid Energy Meter Final Year Project Report

Date post: 27-Oct-2014
Category:
Upload: aarcoelectronics
View: 1,195 times
Download: 46 times
Share this document with a friend
Popular Tags:
124
COMSATS Institute of Information Technology Lahore Automated Remote Metering System (ARMS) Project Advisor Mr. Muhammad Nadeem (Assistant Professor) Project Members: Muhammad Shahbaz [email protected] Muhammad Iyaz Khan [email protected] Muhammad Asad Rafique [email protected] Muhammad Fahad Malik [email protected] [email protected] SESSION Spring 2003- 2007 Department of Electrical Engineering COMSATS Institute of Information Technology Defence Road, Off Raiwind Road, Lahore.
Transcript
Page 1: Prepaid Energy Meter Final Year Project Report

COMSATS Institute of Information Technology

Lahore

Automated Remote Metering System

(ARMS)

PPrroojjeecctt AAddvviissoorr

MMrr.. MMuuhhaammmmaadd NNaaddeeeemm

((AAssssiissttaanntt PPrrooffeessssoorr))

PPrroojjeecctt MMeemmbbeerrss::

MMuuhhaammmmaadd SShhaahhbbaazz mmsshhaahhbbaazzaannssaarrii@@hhoottmmaaiill..ccoomm

MMuuhhaammmmaadd IIyyaazz KKhhaann mmiiyyaazzkkhhaann@@hhoottmmaaiill..ccoomm

MMuuhhaammmmaadd AAssaadd RRaaffiiqquuee ttooaassaadd@@hhoottmmaaiill..ccoomm

MMuuhhaammmmaadd FFaahhaadd MMaalliikk ffaahhaaddmmaalliikk1188@@hhoottmmaaiill..ccoomm

aarrmmss..tteeaamm@@ggmmaaiill..ccoomm

SSEESSSSIIOONN SSpprriinngg 22000033-- 22000077

Department of Electrical Engineering

COMSATS Institute of Information Technology

Defence Road, Off Raiwind Road, Lahore.

Page 2: Prepaid Energy Meter Final Year Project Report

Automated Remote Metering System

(ARMS)

A project thesis submitted in the partial fulfillment of the requirements for the degree of

Bachelor of Science in Computer Engineering

by

Muhammad Shahbaz BCE/L-S03-32

Muhammad Iyaz Khan BCE/L-S03-26

Muhammad Asad Rafique BCE/L-S03-21

Muhammad Fahad Malik BCE/L-S03-24

Year Spring 2003- 2007 Supervisor External Examiner Head of Department Dated Dated

Department of Electrical Engineering

COMSATS Institute of Information Technology

Defence Road, Off Raiwind Road, Lahore.

Page 3: Prepaid Energy Meter Final Year Project Report

Department of Electrical Engineering

COMSATS Institute of Information Technology

Defence Road, Off Raiwind Road, Lahore.

Page 4: Prepaid Energy Meter Final Year Project Report

Dedicated To

Our Loving Parents, Teachers, Class fellows and Friends who

encouraged and motivated us in completing the project and

also dedicated to all junior Students of Electrical Engineering

Department of COMSATS Institute of Information Technology,

Lahore.

Page 5: Prepaid Energy Meter Final Year Project Report

Acknowledgements

Thanks to Almighty Allah, the most merciful and beneficial for showing us the right

path and giving us the strength to accomplish this task.

We are grateful to Mr. Muhammad Nadeem (Assistant Professor)

COMSATS Institute of Information Technology, Lahore for providing full support

and guidance in the completion of our project. We also grateful to Mr. Mohsin Ali

(Deputy General Manager) and Mr. Salman Aizad (Deputy Manager)

SIEMENS Pakistan Engineering Co.Ltd. for the encouragement and help towards

our project. We thank them whole-heartedly for their sincere instructions, advices

and motivation from the beginning to the accomplishment of our project.

We are thankful to our families and beloved parents whose hands always rose in the

prayers for our success.

Muhammad Shahbaz

Muhammad Iyaz Khan

Muhammad Asad Rafique

Muhammad Fahad Malik

Page 6: Prepaid Energy Meter Final Year Project Report

To Almighty Allah Who created the universe

and gives meaning to our lives Through His love

Page 7: Prepaid Energy Meter Final Year Project Report

Abstract:

Today the world is facing the environment that offers challenges. Ideas are polishing the minds of the Engineers, Scientists and Analysts who are involved in the development of industry as well as providing feasible products to the users. Demand actually requires accessing the devices characteristics remotely in a reliable way. In the 21st century everyone is talking about modernization and development but without electricity it seems to be unaccomplished. The users are growing exponentially and load on power providing divisions (e.g. WAPDA) is increasing, so organizations as well as customers must be facilitated by giving them an innovative solution; i-e, concept of Automated Remote Metering System

(ARMS).As energy meter gets older they may become less accurate due to its mechanical design (based on Ferrari Wheel Principle) and are the main source of dissipating the power so it makes good prospective sense to move to this new technology. Collecting data from power meters is a laborious task. Conventionally the meter is read by human being and written onto a notepad. The data then has to be typed into a computer before it can be processed. Collecting data electronically has many advantages over the traditional method such as: the digital data can be read and understood by computers and stored in database and also other devices can be stored in media such as disks or CDs and multiple copies can be easily made for reliable data storage. By keeping all these things in the mind, the idea of Automated Remote Metering System

(ARMS) has been flourished comprising of four modules: Digital Field Unit (Power Meter), Data Concentrator (Brick), Wireless Communication Link and Database System Unit (developed at area’s sub-station). The system developed automates the whole process that is, measuring the power from digital electric meter, send the consumed units (Postpaid electric meter) and card number (Prepaid electric meter) to area sub-station and the process of bill generation. It also eliminates human error in reading meters, improves meter reading accuracy, an accurate usage based bill resulting in better customer satisfaction, protection against electricity theft and meter tampering. This metering system is feasible for residential, commercial and industrial applications because of the versatility and low-cost afforded by system design. It also can measure and record energy usage at different times of the day, so utilities can bill customers for energy based on time of usage. As system is automated so data is transmitted to the utility via a wireless communication link. Improved accuracy and lower power consumption are other benefits of ARMS. This system is charging system whereby customers will be charged more for power used at peak time and less for power used at off-hours. The system design also changes the economics of manufacturing energy meters. Another consideration is the demand for mechanical-meter replacements that are as inexpensive as possible. In parts of the developing world where many new customers are being connected to the grid, the low cost of the project is its main attraction as well. In the first part Digital Field Unit (Power Meter) had been developed which is of two types Postpaid and Prepaid, that has no mechanical part (elimination of old Ferrari wheel) and it measures the current and voltage, convert it into a digital form and then compute the instantaneous power. In prepaid meter case we interfaced the keypad to enter the card number whereas in postpaid consumer will have the monthly bill. Secondly, Data Concentrator (Brick) which is master module of the Field unit had also been developed that acquisite the data from the power meter at selected intervals and send this data via Wireless Communication Link for this we interface the mobile phone and send the data in SMS text format to area sub-station. Lastly, Database System Unit is developed at area’s sub-station that stores the customer information (meter no, customer name and address) consumed units and computes the electricity bill automatically. The data is received in the database through the serially interfaced mobile phone by reading the mobile phone through AT commands. Database is developed using Visual Basic 6 and a graphical user interface is provided for entering the customer’s information and for generation of electricity bill.

Page 8: Prepaid Energy Meter Final Year Project Report

1

Table of Contents

CHAPTER # 1....................................................................................................... 6

Introduction .......................................................................................................... 6

1.1 Electricity (History) ....................................................................................................6

1.1.1 What is Electricity? ..........................................................................................................7

1.2 Power Generation........................................................................................................7 1.2.1 Methods of Generation.....................................................................................................8

1.3 Electricity Demand .....................................................................................................9

1.4 Electricity Retailing ....................................................................................................9 1.4.1 Creating a Market...........................................................................................................10

CHAPTER # 2..................................................................................................... 11

Automated Remote Metering System ................................................................ 11

2.1 Problem Statement....................................................................................................11

2.2 Scope of the Project ..................................................................................................12

2.3 Advantages................................................................................................................12

2.4 ARMS Topology.......................................................................................................13

2.4.1 Digital Field Unit (Power Meter)...................................................................................14 2.4.2 Data Concentrator (Brick)..............................................................................................14 2.4.3 Wireless Communication Link ......................................................................................14 2.4.4 Database System (Developed at area sub-station) .........................................................14

CHAPTER # 3..................................................................................................... 15

Digital Field Unit (Power Meter) ....................................................................... 15

3.1 Introduction...............................................................................................................15 3.1.1 Types of Digital Field Unit ............................................................................................15 3.1.2 Block Diagram of Digital Field Unit .............................................................................16

3.2 Energy Measurement Module...................................................................................16 3.2.1 Description of Energy Measurement Module ................................................................16 3.2.2 Features (IEC Specification) ..........................................................................................17 3.2.3 Function of Energy Measurement Module.....................................................................19 3.2.4 SPI - Interface ................................................................................................................21 3.2.5 Register Access ..............................................................................................................22 3.2.6 Power Calculation ..........................................................................................................24 3.2.7 Shunt Resistance (RSH) Calcualtion .............................................................................24 3.2.8 Application Circuit.........................................................................................................27

3.3 Controlling Module...................................................................................................28

3.3.1 Microcontroller ..............................................................................................................28 3.3.2 PIC Microcontroller .......................................................................................................32 3.3.3 Computation of Consumed Units...................................................................................35 3.3.4 Evaluation of a Delta Value ----- Software Dependant..................................................36

3.4 Display System .........................................................................................................37 3.4.1 User Guide to Operate the System (Visual Aids) ..........................................................37 3.4.2 Application Flow Chart..................................................................................................39 3.4.3 Pin Assignment ..............................................................................................................39 3.4.3 Pin Assignment ..............................................................................................................40 3.4.4 Instruction Description...................................................................................................40

Page 9: Prepaid Energy Meter Final Year Project Report

2

CHAPTER # 4..................................................................................................... 44

Data Concentrator (Brick) ................................................................................. 44

4.1 Introduction...............................................................................................................44

4.2 Block Diagram of Data Concentrator .......................................................................44

4.3 Communication Module ...........................................................................................45

4.3.1Addressable Universal Synchronous Asynchronous Receiver Transmitter (USART) ...45 4.3.2 USART Baud Rate Generator (BRG) ............................................................................45 4.3.3 DB-9 Connector .............................................................................................................46

4.4 Storage Media ...........................................................................................................48

CHAPTER # 5..................................................................................................... 50

Wireless Communication Link........................................................................... 50

5.1 Introduction...............................................................................................................50

5.2 AT Commands..........................................................................................................50

5.2.1 Syntax Rules ..................................................................................................................50

5.3 At Commands For SMS............................................................................................52

5.4 AT Commands To Read SMS ..................................................................................56

5.5 AT Commands To Send SMS ..................................................................................56

CHAPTER # 6..................................................................................................... 57

Database System ................................................................................................. 57

6.1 Introduction...............................................................................................................57

6.2 ARMS Application Software Developed at Area Sub-Station .................................57

6.3 Database..............................................................................................................57

6.3.1 DBMS ............................................................................................................................57 6.3.2 Block Diagram of DataBase System..............................................................................58

6.4 Database Selection....................................................................................................58

6.5 ARMS Database Designing ......................................................................................60

6.6 ARMS Visual Basic 6 Guideline User Interface Development................................61

6.6.1 DataLogger.EXE............................................................................................................62 6.6.2 ARMS Application.EXE................................................................................................65

CHAPTER # 7..................................................................................................... 68

ARMS Implementation....................................................................................... 68

7.1 Tools Used ................................................................................................................68 7.1.1 OrCAD...........................................................................................................................68 7.1.2 PROTEUS---ISIS...........................................................................................................71 7.1.3 Controller Programming Tool.......................................................................................73 7.1.4 DataBase Development Tool ........................................................................................76 7.1.5 Microsoft Visual Basic 6................................................................................................78

7.2 Implementation of Digital Field Unit (Power Meter) ...............................................84

7.2.1 Digital Field Unit (Postpaid Meter) ...............................................................................84 7.2.2 Digital Field Unit (Prepaid Meter) .................................................................................85 7.2.3 PCB Layout of Postpaid Meter ......................................................................................86 7.2.4 PCB Layout of Prepaid Meter.......................................................................................86

7.3 Implementation of Data Concentrator (Brick)..........................................................87

7.3.1 Schematic of Data Concentrator ....................................................................................87 7.3.2 PCB Layout of Data Concentrator .................................................................................88

REFERENCES ................................................................................................... 89

Page 10: Prepaid Energy Meter Final Year Project Report

3

APPENDIX A...................................................................................................... 90

Source Codes (Field Unit)................................................................................... 90

A.1 Field Unit Code for Energy Measurement,Control and dispaly of Data(Postpaid) .90

A.2 Field Unit Code for Energy Measurement,Control and dispaly of Data (Prepaid)..95

APPENDIX B.................................................................................................... 103

Source Codes (Data Concentrator) .................................................................. 103

B.1 DataConcentrator Code For Acquisating and Sending of Data .............................103

APPENDIX C.................................................................................................... 106

Source Codes (Database Unit).......................................................................... 106

C.1 DataBase Code For Storage of Data,ConsumerPersonal Info and Computation of Electricity Bill...............................................................................................................106 C.2 Data Logger........................................................................................................11063

Page 11: Prepaid Energy Meter Final Year Project Report

4

LIST OF FIGURES

Fig 2.1 : Overview of ARMS................................................................................................163 Fig 3.1 : Block Diagram (Field Unit)......................................................................................16 Fig 3.2 : Block Diagram of SA9903B.....................................................................................17 Fig 3.3.1 : Analog Input (Current Sensor) Internal Configuration..........................................19 Fig 3.3.2 : Analog Input (Voltage Sensor) Internal Configuration .........................................19 Fig 3.4 : Current & Voltage Sense Inputs (IIP, IIN and IVP).................................................20 Fig 3.5 : Current Level Resistors ............................................................................................20 Fig 3.6 : SPI-Interface............................................................................................................20 Fig 3.7 : SPI-Waveforms ........................................................................................................22 Fig 3.8 : Active & Reactive Register ......................................................................................23 Fig 3.9 : Wrapping of Active & Reactive Register .................................................................23 Fig3.10 :Shunt Resistance.......................................................................................................25 Fig 3.11 : Application Circuit .................................................................................................27 Fig 3.12 : Block Diagram of Microcontroller .........................................................................28 Fig 3.13 :Block Diagram of Microcontroller with ports .........................................................29 Fig 3.14 : Block Diagram of Microcontroller with ROM & RAM.........................................30 Fig 3.15 : Block Diagram of Microcontroller highlighted PORTS.........................................31 Fig 3.16 : PIC16F877A Pin Diagram......................................................................................33 Fig 3.17 : PIC16F877A Block Diagram .................................................................................34 Fig 3.18 :Flow Chart to Compute Delta Value .......................................................................36 Fig 3.19 :Main Display Menu .................................................................................................37 Fig 3.20 : Initial Display for Prepaid Meter ............................................................................37 Fig 3.21 : Timer Expires .........................................................................................................38 Fig 3.22 : Keypad ‘#’ Button ..................................................................................................38 Fig 3.23 : Enter Card Menu.....................................................................................................38 Fig 3.24 : Code Entry Menu....................................................................................................39 Fig 3.25 : Confirmation of Code.............................................................................................39 Fig 3.26 : Application Flow Chart of LCD.............................................................................39 Fig 4.1 : Block Diagram of Data Concentrator .......................................................................44 Fig 4.2 : Transmitt Status and Control Register......................................................................45 Fig 4.3 : Receive Status and Control Register ........................................................................45 Fig 4.4 :Baud Rate ..................................................................................................................46 Fig 4.5 :DB-9 Male &Female Connectors ..............................................................................47 Fig 4.6 : M95040.....................................................................................................................49 Fig 5.1 : AT + CSMS..............................................................................................................52 Fig 5.2 : AT + CMGF .............................................................................................................53 Fig 5.3 : AT + CSCA ..............................................................................................................53 Fig 5.4 : AT + CNMI ..............................................................................................................54 Fig 5.5 : AT + CMGS .............................................................................................................55 Fig 5.6 : AT + CMGR.............................................................................................................55 Fig 5.7 : AT + CMGL .............................................................................................................56 Fig 6.1 : Block Diagram of DataBase System ........................................................................58 Fig 6.2 : ARMS Database Tables' Diagram............................................................................61 Fig 6.3 : Depicts the MSComm Component in VB6 Enviroment...........................................63 Fig 6.4 : Depicts the Timer Component in VB6 Enviroment .................................................64 Fig 6.6 : ARMS Meter Information Form...............................................................................65 Fig 6.7 : ARMS Customer Information Form.........................................................................66 Fig 6.8 : ARMS Prepaid Electricity Bill Form........................................................................67 Fig 6.9 : ARMS Postpaid Electricity Bill................................................................................67 Fig 7.1 : Schematic of Postpaid Meter ....................................................................................84 Fig 7.2 : Schematic of Prepaid Meter......................................................................................85 Fig 7.3 :PCB Layout of Postpaid Meter..................................................................................86 Fig 7.4 : PCB Layout of Prepaid Meter ..................................................................................86 Fig 7.5 : Schematic of Data Concentrator ...............................................................................87 Fig 7.6 :PCB Layout of Data Concentrator.............................................................................88

Page 12: Prepaid Energy Meter Final Year Project Report

5

LIST OF TABLES

Table 3.1 : IEC Standards .......................................................................................................18 Table 3.2 : Register Addresses................................................................................................23 Table 3.3 : Copper Wire Specifications ..................................................................................26 Table 3.4.1 : Clear Display Data Field....................................................................................40 Table 3.4.2 : Return Home Data .............................................................................................40 Table 3.4.3 : Entry Mode Set ..................................................................................................41 Table 3.4.4 : Display ON/OFF Control...................................................................................41 Table 3.4.5.1 : Cursor Or Display Shift ..................................................................................42 Table 3.4.5.2 : Cursor Or Display Shift ..................................................................................42 Table 3.4.6 : Function Set .......................................................................................................42 Table 3.4.7 : Set CGRAM Address.........................................................................................43 Table 3.4.8 : Set DDRAM Address ........................................................................................43 Table 4.1 : Baud Rate Formula ...............................................................................................46 Table 5.1 : AT + CSMS ..........................................................................................................52 Table 5.2 : AT + CMGF..........................................................................................................53 Table 5.3 : AT + CSCA ..........................................................................................................53 Table 5.4 : AT + CNMI ..........................................................................................................54 Table 5.5 : AT + CMGS..........................................................................................................54 Table 5.6 : AT + CMGR .........................................................................................................55 Table 5.7 : AT + CMGL .........................................................................................................56 Table 6.1 : Attributes of Entities in DB ..................................................................................60

Page 13: Prepaid Energy Meter Final Year Project Report

6

CHAPTER # 1

Introduction

1.1 Electricity (History)

History of Electricity is fascinating. Benjamin Franklin did not "invent" power. In fact, the story of

power did not begin when he flew his kite during a thunderstorm or when light bulbs were installed

in houses all around the world.

The truth is that power has always been around because it naturally exists in the world. Lightning,

for instance, is simply a flow of electrons between the ground and the clouds. When you touch

something and get a shock that is really static moving toward you.

Hence, electrical equipment like motors, light bulbs, and batteries aren't needed for electric power

to exist. They are just creative inventions designed to harness and use electric power.

In the rich story of electric power, the first discoveries were made back in ancient Greece. Greek

philosophers discovered that when amber is rubbed against cloth, lightweight objects will stick to

it. This is the basis of static shock.

Basic electricity is described in many ways. When an electrical current flows through a conductor,

a magnetic field (or "flux") develops around the conductor. The highest flux density occurs when

the conductor is formed into a coil having many turns. In electronics and basic electricity, a coil is

usually known as an inductor. If a steady DC current is run through the coil, you would have an

electromagnet - a device with the properties of a conventional magnet, except you can turn it on or

off by placing a switch in the circuit. There's reciprocity in the interaction between electron flow

and magnetism. If you sweep one pole of a magnet quickly past an electrical conductor (at a right

angle to it), a voltage will be momentarily "induced" in the conductor. The polarity of the voltage

will depend upon which pole of the magnet you're using, and in which direction it sweeps past the

conductor. This phenomenon becomes more apparent when the conductor is formed into a coil of

many turns. The relationship in basic electricity is the fundamental operating principle of a

generator. The output, known as alternating current, is the type of power that electric utility

companies supply to businesses and homes. A practical generator would likely have two coils

mounted on opposite sides of the spinning magnet and wired together in a series connection.

Because the coils are in a series, the voltages combine, and the voltage output of the generator will

be twice that of each coil. [1]

Page 14: Prepaid Energy Meter Final Year Project Report

7

1.1.1 What is Electricity?

Power is a form of energy. It is the flow of electrons. All matter is made up of atoms, and an atom

has a center, called a nucleus. The nucleus contains positively charged particles called protons and

uncharged particles called neutrons. The nucleus of an atom is surrounded by negatively charged

particles called electrons. The negative charge of an electron is equal to the positive charge of a

proton, and the number of electrons in an atom is usually equal to the number of protons. When the

balancing force between protons and electrons is upset by an outside force, an atom may gain or

lose an electron. When electrons are "lost" from an atom, the free movement of these electrons

constitutes an electric current.

Power is a basic part of nature and it is one of our most widely used forms of energy. We get

power, which is a secondary energy source, from the conversion of other sources of energy, like

coal, natural gas, oil, nuclear power and other natural sources, which are called primary sources.

Many cities and towns were built alongside waterfalls (a primary source of mechanical energy)

that turned water wheels to perform work. Before power generation began slightly over 100 years

ago, houses were lit with kerosene lamps, food was cooled in iceboxes, and rooms were warmed

by wood-burning or coal-burning stoves. Beginning with Benjamin Franklin's experiment with a

kite one stormy night in Philadelphia, the principles of power gradually became understood. In the

mid-1800s, Thomas Edison changed everyone's life -- he perfected his invention -- the electric

light bulb. Prior to 1879, power had been used in arc lights for outdoor lighting. Edison's invention

used power to bring indoor lighting to our homes. [2]

1.2 Power Generation

HOW IS POWER GENERATED?

An electric generator is a device for converting mechanical energy into electrical energy. The

process is based on the relationship between magnetism and power. When a wire or any other

electrically conductive material moves across a magnetic field, an electric current occurs in the

wire. The large generators used by the electric utility industry have a stationary conductor. A

magnet attached to the end of a rotating shaft is positioned inside a stationary conducting ring that

is wrapped with a long, continuous piece of wire. When the magnet rotates, it induces a small

electric current in each section of wire as it passes. Each section of wire constitutes a small,

separate electric conductor. All the small currents of individual sections add up to one current of

considerable size. This current is used for electric power.

The importance of dependable electricity generation, transmission and distribution was revealed

when it became apparent that electricity was useful for providing heat, light and power for human

needs. Centralized power generation became possible when it was recognized that alternating

Page 15: Prepaid Energy Meter Final Year Project Report

8

current electric power lines can transport electricity at low costs across great distances by taking

advantage of the ability to transform the voltage using power transformers.

Electricity has been generated for the purpose of powering human technologies for at least 120

years from various sources of energy. The first power plants were run on wood, while today we

rely mainly on petroleum, natural gas, coal, hydroelectric and nuclear power and a small amount

from hydrogen, solar energy, tidal harnesses, wind generators, and geothermal sources.[3]

1.2.1 Methods of Generation

Turbines

Rotating turbines attached to electrical generators produce most commercially available electricity.

Turbines are driven by a fluid which acts as an intermediate energy carrier. The fluids typically

used are:

� Steam - Water is boiled by nuclear fission or the burning of fossil fuels (coal, natural gas,

or petroleum). Some newer plants use the sun as the heat source: solar parabolic troughs

and solar power towers concentrate sunlight to heat a heat transfer fluid, which is then used

to produce steam.

� Hydal - Turbine blades are acted upon by flowing water, produced by hydroelectric dams

or tidal forces.

� Wind - Most wind turbines generate electricity from naturally occurring wind. Solar

updraft towers use wind that is artificially produced inside the chimney by heating it with

sunlight.

� Hot gases - Turbines are driven directly by gases produced by the combustion of natural

gas or oil.

Combined cycle gas turbine plants are driven by both steam and gas. They generate power by

burning natural gas in a gas turbine and use residual heat to generate additional electricity from

steam. These plants offer efficiencies of up to 60%.

Reciprocating Engines

Small electricity generators are often powered by reciprocating engines burning diesel, biogas or

natural gas. Diesel engines are often used for back up generation, usually at low voltages. Biogas is

often combusted where it is produced, such as a landfill or wastewater treatment plant, with a

reciprocating engine or a microturbine, which is a small gas turbine.[4]

Page 16: Prepaid Energy Meter Final Year Project Report

9

Photovoltaic Panels

Unlike the solar heat concentrators mentioned above, photovoltaic panels convert sunlight directly

to electricity. Although sunlight is free and abundant, solar panels are expensive to produce and

have only a 10-20% conversion efficiency. Until recently, photovoltaics were most commonly

used in remote sites where there is no access to a commercial power grid, or as a supplemental

electricity source for individual homes and businesses. Recent advances in manufacturing

efficiency and photovoltaic technology, combined with subsidies driven by environmental

concerns, have dramatically accelerated the deployment of solar panels. Installed solar capacity is

growing by 30% per year in several regions including Germany, Japan, California and New Jersey.

1.3 Electricity Demand

The demand for electricity can be met in two different ways. The primary method thus far has been

for public or private utilities to construct large scale centralized projects to generate and transmit

the electricity required to fuel economies. Many of these projects have caused unpleasant

environmental effects such as air or radiation pollution and the flooding of large areas of land.

Distributed generation creates power on a smaller scale at locations throughout the electricity

network. Often these sites generate electricity as a byproduct of other industrial processes such as

using gas from landfills to drive turbines.

1.4 Electricity Retailing

Electricity retailing began at the end of the 19th century when the bodies who generated electricity

for their own use made supply available to third parties. In the beginning, electricity was primarily

used for street lighting and trams. The general public were allowed to purchase electricity only

after large scale electric companies were started.

The provision of these services was generally the responsibility of electric compaines or municipal

authorities who either set up their own departments or contracted the services from private

entrepreneurs. Residential, commercial and industrial use of electricity was confined, initially, to

lighting but this changed dramatically with the development of electric motors, heaters and

communication devices.

The basic principle of supply has not changed much over time. The amount of energy used by the

domestic consumer, and thus the amount charged for, is measured through an electricity meter that

is usually placed near the input of a home to provide easy access to the meter reader.

Page 17: Prepaid Energy Meter Final Year Project Report

10

Customers are usually charged a monthly service fee and additional charges based on the electrical

energy (in kWh) consumed by the household or business during the month. Commercial and

industrial consumers normally have more complex pricing schemes. These require meters that

measure the energy usage in time intervals (such as a half hour) to impose charges based on both

the amount of energy consumed and the maximum rate of consumption, i.e. the maximum demand,

which is measured in kW.

1.4.1 Creating a Market

In 1990 there was a significant development in the way electricity was bought and sold. In many

countries, the electricity market was deregulated to open up the supply of electricity to

competition. In the United Kingdom the Electricity Supply Industry was radically reformed to

establish competition. This trend continued in other countries (see New Zealand Electricity

Market) and the role of electricity retailing changed from what was essentially an administrative

function within an integrated utility to a become a risk management function within a competitive

electricity market.

Electricity retailers now provide fixed prices for electricity to their customers and manage the risk

involved in purchasing electricity from spot markets or electricity pools. This development has not

been without casualties. The most notable example of poor risk management (coupled with poor

market regulation) occurred in California in the summer of 2001, when Pacific Gas and Electric

and Southern California Edison were driven into bankruptcy by having to purchase electricity at

high spot prices and sell at low fixed rates.

Customers may choose from a number of competing suppliers. They may also opt to pay more for

"green" power, i.e. electricity sourced from renewable energy generation such as wind power or

solar power. An electricity provider is often known as "the electric company" or "the power

company". [5]

Page 18: Prepaid Energy Meter Final Year Project Report

11

CHAPTER # 2

Automated Remote Metering System

Automated Remote Metering System (ARMS) is an innovative solution to the problems faced by

power providing divisions like WAPDA that automates the whole process of measuring the energy

from the meter, sending the consumed units and computation of electricity bill. This system

provides facilitation to the organizations as well as to the customers by its improved accuracy,

lower power consumption and its low cost. The system also provides the best possible customer

service, high reliability, enhanced customer convenience, controls meter reading costs, easy access

in remote areas, time saving, ease to resolve complaints, theft prevention, more convenient and

effective, stable and flexible architecture, providing effective maintenance and development

possibilities, less expensive for support and maintenance.

2.1 Problem Statement

On average, utilities find theft and current diversion to cost up to 10 percent of revenues, and have

various programs in place to address this issue. Ratepayers use a variety of ingenious and devious

techniques to steal power from utilities. For instance, one method of tampering is to use a magnet

around the meter, attempting to distort the recording of data. Another method of tampering is to

pull a meter out and turn it upside down – but the ARMS defeat this ploy. Another issue is the

collection of data from power meters as this is a laborious task. Conventionally the meter is read

by human being and written onto a notepad. The data then has to be typed into a computer before it

can be processed. Collecting data electronically has many advantages over the traditional method

such as: the digital data can be read and understood by computers and stored in database and also

other devices can be stored in media such as disks or CDs and multiple copies can be easily made

for reliable data storage. Transmission loss is the main issue of the time but the efficiency of the

system can be measured by comparing the amount put into the system with the cumulative total of

amounts withdrawn from the system, with the difference being assessed as transmission loss. By

keeping all these things in the mind, the idea of Automated Remote Metering System (ARMS) has

been flourished comprising of four modules: Digital Field Unit (Power Meter), Data Concentrator

(Brick), Wireless Communication Link and Database System Unit (developed at area’s sub-

station). The system developed automates the whole process of measuring the power from electric

meter, send the consumed units and card number (prepaid electric meter) to area sub-station and

the process of bill generation.

Page 19: Prepaid Energy Meter Final Year Project Report

12

2.2 Scope of the Project

The installation of accurate and secure metering system at delivery points is the fundamental

requirement, the best solution is through state-of-art changes being proposed by customized

development for micro-processor based energy metering and to thereafter retrieve maximum

possible data regarding customer behavior and characteristics of power supply from the utility.

Through the reduced need for on-site manual meter readings and other efficiencies, the system is

expected to pay for itself within few years of installation.

Another factor which needs to be considered, is the fact that starting from power houses right to

consumer mains, more than 95 per cent of the installed meters are working on the old principle. As

these meters have a tendency to slow down with passage of time, the utilities as a consequence get

incorrect information for calculation of return on their investments. This misleading information

shall make all assessments about the system untrue and definitely on the lower side.

The system proposed would be a real time system that can translate from the metering to the billing

process. As and when required, the system can be integrated with a new application such as energy

pooling system, customer relationship management system, geographical interface system and so

forth. Hence, the focus is on a system that not only retrieves the data but can also perform

following tasks:

� Manage the meters

� Conducts energy audit, outage

� Supports event alarming, detect system device status

� Remote meter configuration

� Supports billing and auto estimate and adjustments

� Supports future expansions/replacements of the meters at a minimal cost to the utility

ARMS is a significant improvement over the current visual/manual meter reading method which is

prone to errors at various stages of reading and recording meter data.

2.3 Advantages

There are several advantages to be enjoyed by a utility implementing an ARMS System as well as

its customers. A few of these advantages are listed here

• Eliminates human error in reading meters

• Improves meter reading accuracy

• Lowers estimate based meter reading

• Automatic process of measuring the power, sending the data and generating the bill

Page 20: Prepaid Energy Meter Final Year Project Report

13

• An accurate usage based bill results in better customer satisfaction

• Theft and meter tampering detection

• Difficult to access meters can be read easily

• Shortened time interval between reading a meter and generating a bill

2.4 ARMS Topology

By keeping all these things in the mind, the idea of Automated Remote Metering System (ARMS)

has been flourished comprising of four modules: Digital Field Unit (Power Meter), Data

Concentrator (Brick), Wireless Communication Link and Database System Unit (developed at

area’s sub-station). The system developed automates the whole process of measuring the power

from electric meter, send the consumed units and card number (prepaid electric meter) to area sub-

station and the process of bill generation.

Fig 2.1 : Overview of ARMS

Page 21: Prepaid Energy Meter Final Year Project Report

14

2.4.1 Digital Field Unit (Power Meter)

Digital field unit is basically a power meter that has no mechanical part(elimination of old Ferrari

wheel) and measure the current and voltage, convert it into a digital form and then compute the

instantaneous power which is the power at a certain instant. The basic component in the field unit

is the energy measuring IC with SPI interface that perform the measurement of Active Power. The

heart of this unit is the microprocessor, which is providing the interface with LCD and energy

measuring IC and is also responsible for acquisition of the data and perform computation of power.

2.4.2 Data Concentrator (Brick)

A data concentrator called brick is the master module of the Field Unit, usually 4-5 Field Units are

linked with this module via SPI interface. Data Concentrator extracts the data that is the consumed

units(prepaid & post-paid meter) and the scratch card code(prepaid meter) from the field units on

the selected intervals and store them on to the on board non-volatile memory and transfer this data

to the area sub-station’s database through terminal equipment via wireless communication link.

2.4.3 Wireless Communication Link

The wireless communication between Data Concentrator and the Database system is done by using

GSM network. For this AT Commands are used and cell phone is interfaced with microcontroller

serially that sends the data to the area sub-station.

2.4.4 Database System (Developed at area sub-station)

Finally, a database system is developed on the host side where the data from all the field units is

stored and computed for the billing process, which is at the area sub-station. This unit provides a

permanent storage for the data (consumed units), customer information which is taken initially

along with its complete record. Also there is an automatic system for the computation of electricity

bill.

Page 22: Prepaid Energy Meter Final Year Project Report

15

CHAPTER # 3

Digital Field Unit (Power Meter)

3.1 Introduction

Digital field unit is basically a power (remote) meter, which consists of three parts:

• Energy Measurement Module

• Controlling Module

• Display System

3.1.1 Types of Digital Field Unit

There are two types of Digital Field Unit:

1) Postpaid Meter 2) Prepaid Meter

1) Postpaid Meter

Postpaid Meter is type of Field unit in which there is a monthly billing system and user paid at the

end of the month. In this case the consumed units are sent to the area sub-station at selected

interval. Details are in the next section.

2) Prepaid Meter

The construction and the power measuring mechanism of Prepaid Meter is just like the postpaid

meter but the only difference is in the working and its functionality in which user has the facility to

enter a card code just like the mobile phone cards and have its balance in form of units. For this a

keypad is interfaced with the unit as shown in the block diagram. In this case the scratch card code

along with the consumed units is sent to the area sub-station at selected interval.

In the first part Digital Field Unit (Power Meter) had been developed which is of two types

Postpaid and Prepaid, that has no mechanical part (elimination of old Ferrari wheel) and it

measures the current and voltage, convert it into a digital form and then compute the instantaneous

power. In prepaid meter case we interfaced the keypad to enter the card number whereas in

postpaid consumer will have the monthly bill.

Page 23: Prepaid Energy Meter Final Year Project Report

16

3.1.2 Block Diagram of Digital Field Unit

Fig 3.1 : Block Diagram (Field Unit)

3.2 Energy Measurement Module

Energy is measured by measuring the voltage and current, convert it into a digital form and then

compute the instantaneous power which is the power at a certain instant. The active energy register

is read after every 1 sec and its value will be sent to the Microcontroller via SPI interface in the

controlling module, for this we are using SA9903B as a metering IC. The instantaneous active

power values are continuously integrated to an active energy register, the value of which is

periodically accessed by the Microcontroller via an SPI (Serial Peripheral Interface). The

Microcontroller uses the retrieved active register value to calculate the active power consumed.

3.2.1 Description of Energy Measurement Module

The heart of the energy measurement module is the SAMES’s SA9903B IC which is a single phase

bi-directional energy/power metering integrated circuit that performs measurement of active and

reactive power, mains voltage and mains frequency. Measured values for active and reactive

energy, the mains voltage and frequency are accessible through a SPI bus from 24 bit registers. But

we are measuring only the Active Energy. The integrated circuit includes all the required functions

for single-phase power and energy measurement such as two over sampling A/D converters for the

voltage and current sense inputs, power calculation and energy integration. The SPI interface of the

SA9903B has a tri-state output that allows connection of more than one metering device on a

single SPI bus. This innovative universal single-phase power/energy metering integrated circuit is

* Prepaid Power Meter

Page 24: Prepaid Energy Meter Final Year Project Report

17

ideally suited for energy calculations in applications such as electricity dispensing systems (ED's),

residential municipal metering and factory energy metering and control.

Fig 3.2 : Block Diagram of SA9903B[6]

3.2.2 Features (IEC Specification)

� Bi-directional active and reactive power/energy measurement

� RMS Voltage and frequency measurement

� SPI communication bus

� Meets the IEC 61036 Specification requirements for Class 1 AC Watt hour meters

� Less than 1% error over a dynamic range of 1:1000 for active measurement

� Meets the IEC 61268 Specification requirements hour meters

� Protected against ESD

� Total power consumption rating below25mW

� Adaptable to different current sensor technologies

� Operates over a wide temperature range

� Precision on-chip voltage reference [6]

IEC 61036 Specification requirements for Class 1 Accuracy

The primary international standard to which all electric meters must conform is IEC 61036. This

document specifies electrical, mechanical, and environmental requirements, and calls out two

accuracy classes: Class 1, with a 1% nominal accuracy over most of the usable current range, and

Class 2, with a 2% nominal accuracy. See Table 3.1 for a summary of the more important

requirements for compliant electric meters. The IEC Microelectronics Collection contains more

than 700 documents concerning bare aluminum conductors; cables, wires, waveguides, R.F.

Page 25: Prepaid Energy Meter Final Year Project Report

18

connectors, and accessories for communication and signalling such as coaxial cable, wire and

symmetric cables, connectors for R.F. cables, waveguides and their accessories; capacitors and

resistors for electronic equipment; degrees of protection by enclosures; electric cables and their

characteristics; electrical installations for outdoor sites under heavy conditions, including open-cast

mines and quarries; electrical and electronic test and measuring instruments, systems and

accessories; electrical relays; electromechanical components for electronic equipment such as

connectors, switches, and mechanical structures for electronic equipment; electronic tubes; fibre

optics for interconnecting devices and passive components, fibre optic systems specifications, and

fibres and cables; high-voltage, low-voltage, and miniature fuses; high-voltage testing techniques;

instrument transformers; interference from overhead power lines, high voltage equipment, and

electric traction systems; magnetic alloys and steels; magnetic components and ferrite materials;

piezo electric devices for frequency control and selection; power capacitors; printed circuits;

recommendations for overhead lines; secondary cells and batteries including those with alkaline;

semiconductor devices and integrated circuits; and switchgear and control gear.[7]

ELECTRICAL REQUIREMENTS

ELEMENT LIMIT, CLASS 1 LIMIT, CLASS 2

Power dissipation, other than current circuit 2W, 10VA

Power dissipation, current circuit 4.0VA 2.5VA

Operating voltage range 90% to 110% nominal

Absolute maximum voltage range 0% to 115% nominal

Absolute maximum overcurrent, one-half cycle 30 IMAX

EMC REQUIREMENTS

ELEMENT LIMIT

Electrostatic discharge, contact 8kV

Electrostatic discharge, air 15kV

Immunity to electromagnetic fields 10V/m, 80MHz to 1GHz

Electrical fast transient, load = IB 2kV, all leads

Electrical fast transient, no load 4kV, all leads

Immunity to conducted disturbances 10V, 150kHz to 80MHz

ACCURACY REQUIREMENTS

ELEMENT LIMIT, CLASS 1 LIMIT, CLASS 2

Nominal accuracy, 10% IB—IMAX 1.0% 2.0%

Low current accuracy, 5% IB—10% IB 1.5% 2.5%

Nominal accuracy, 20% IB—IMAX, with reactive 1.0% 2.0%

Low current accuracy, 10% IB—20% IB, with reactive 1.5% 2.5%

Accuracy derating due to 10% voltage variation 0.7% 1.0%

Accuracy derating due to voltage variation, pF = 0.5 inductive 1.0% 1.5%

Accuracy derating due to 2% frequency variation 0.5% 0.8%

Accuracy derating due to frequency variation, pF = 0.5 inductive 0.7% 1.0%

Accuracy derating due to temperature variation 0.05%/°K 0.10%/°K

Accuracy derating due to temperature variation, pF = 0.5 inductive

0.07%/°K 0.15%/°K

Accuracy derating due to self-heating at IMAX, pF = 1 0.7% 1.0%

Accuracy derating due to self-heating at IMAX, pF = 0.5 inductive 1.0% 1.5%

Table 3.1 : IEC Standards[7]

Page 26: Prepaid Energy Meter Final Year Project Report

19

VDD

VDD

IV

P

Voltage

Sensor Inputs Av

GND

While IEC 61036 (or a minor variant) is recognized as the standard for electric meters, the

requirements for multifunctional meters are not nearly so universal.

3.2.3 Function of Energy Measurement Module

Analog Input Configuration

The input circuitry of the current and voltage sensor inputs is illustrated in figure 3.3.1 and 3.3.2.

These inputs are protected against electrostatic discharge through clamping diodes. The feedback

loops from the outputs of the amplifiers Ai and Av generate virtual shorts on the signal inputs.

Exact duplications of the input currents are generated for the analog signal processing circuitry.

The current and voltage sense inputs are identical. Both inputs are differential current driven up to

±25µA peak. One of the voltage sense amplifier input terminals is internally connected to GND.

This is possible because the voltage sense input is much less sensitive to externally induced

parasitic signals compared to the current sense inputs.[6]

Fig 3.3.1 : Analog Input (Current Sensor) Internal Configuration[6]

Fig 3.3.2 : Analog Input (Voltage Sensor) Internal Configuration[6]

VDD

VDD

VDD

IIP

II

N

Current

Sensor Inputs Ai

Page 27: Prepaid Energy Meter Final Year Project Report

20

IIP

IIN

IVP

Current

ADC

Current

ADC

Voltage

ADC

Voltage Sense Input (IVP)

The mains voltage is divided to 14V at nominal mains voltage by means of resistors R1, R2, R3

and R4 as shown in the application circuit (fig 2.11). The current into the voltage sense input is set

at 14µA with resistor R5 from the voltage divider. The voltage sense input of the AD converter

saturates at an input current of ±25µA peak.

Fig 3.4 : Current & Voltage Sense Inputs (IIP, IIN and IVP)[6]

Current Sense Input (IIP and IIN)

Application circuit (fig 2.11) shows the typical connections for the current sensor input. The

resistor R6 and R7 define the current level into the current sense inputs of the SA9903B as shown

in the fig 2.2.3.3. At rated current the resistor values should be selected for input currents of 16µA .

Values for resistors R6 and R7 may be calculated as follows:

R6 = R7 = (I / 16µA ) x RSH / 2

Where:

I = Max line current or if a CT is used

I = line current / CT ratio

RSH = Shunt resistor or termination resistor

Fig 3.5 : Current Level Resistors[6]

Page 28: Prepaid Energy Meter Final Year Project Report

21

The voltage drop across RSH should not be less than 20mV at rated currents, but not higher than

200mV. The ideal value should be approximately 100mV. In case a current transformer is used for

current sensing the value of RSH should be less than the resistance of the CT's secondary winding.

The mains voltage is divided to 14V at nominal mains voltage by means of resistors R1, R2, R3

and R4. The current into the voltage sense input is set at 14µA with resistor R5 from the voltage

divider. The voltage sense input of the AD converter saturates at an input current of ±25µA peak.

Reference Voltage (VREF)

The VREF pin is the reference for the bias resistor. With a bias resistor of 24k optimum conditions

are set.

Serial Clock (SCK)

The SCK pin is used to synchronize data interchange between the micro controller and the

SA9903B. The clock signal on this pin is generated by the micro controller and determines the data

transfer rate of the DO and DI pins.

Serial Data in (DI)

The DI pin is the serial data input pin for the SA9903B. Data will be input at a rate determined by

the Serial Clock (SCK). Data will be accepted only during an active chip select (CS).

Chip Select (CS)

The CS input is used to address the SA9903B. An active high on this pin enables the SA9903B to

initiate data exchange.

Serial Data out (DO)

The DO pin is the serial data output pin for the SA9903B. The Serial Clock (SCK) determines the

data output rate. Data is only transferred during on active chip select (CS). This output is tri-state

when CS is low.[6]

3.2.4 SPI - Interface

Description

A serial peripheral interface bus (SPI) is a synchronous bus used for data transfers between a micro

controller and the SA9903B. The pins DO (Serial Data Out), DI (Serial Data In), CS (Chip Select),

Page 29: Prepaid Energy Meter Final Year Project Report

22

SCK

DI

CS

DO

1 1 0 A5 A4 A3 A2 A1 A0

0 D23 D22 D21 D1 D0 D23 D22 D1 D0 High Impedance

Read Command Register Address

Register Data

and SCK (Serial Clock) are used in the bus implementation. The SA9903B is the slave device with

the micro controller the bus master. The CS input initiates and terminates data transfers. A SCK

signal (generated by the micro controller) strobes data between the micro-controller and the SCK

pin of the SA9903B device. The DI and DO pins are the serial data input and output pins for the

SA9903B, respectively.

Fig 3.7 : SPI-Waveforms[6]

3.2.5 Register Access

The SA9903B contains four 24 bit registers. The content represents active energy, reactive energy,

and mains voltage and mains frequency. The register addresses are shown in the following table

(Table 3.2):

SDO

SPI-Slave

CS

SCLK

SDI

Fig 3.6 : SPI-Interface[6]

Page 30: Prepaid Energy Meter Final Year Project Report

23

ID Register Header Bits A5 A4 A3 A2 A1 A0

1 Active 1 1 0 X X 0 0 0 0

2 Reactive 1 1 0 X X 0 0 0 1

3 Voltage 1 1 0 X X 0 0 1 0

4 Frequency 1 1 0 X X 0 0 1 1

Table 3.2 : Register Addresses[6]

Registers may be read individually and in any order. After a register has been read, the contents of

the next register value will be shifted out on the DO pin with every SCK clock cycle. Data output

on DO will continue until CS is inactive.

Active and Reactive Register Values

The active and reactive registers are 24 bit up/down counters, that increment or decrement at a rate

of 320k samples per second at rated conditions.

23 22 21 20 10 9 8 7 6 5 4 3 2 1 0

Active or Reactive Energy Register Fig 3.8 : Active & Reactive Register[6]

The register values will increment for positive energy flow and decrement for negative energy flow

as indicated in figure below. The active and reactive registers are not reset after access, so in order

to determine the correct register value; the previous value read must be subtracted from the current

reading. The data read from the registers represents the active or reactive power integrated over

time. The increase or decrease between readings represents the measured energy consumption. [6]

Fig 3.9 : Wrapping of Active & Reactive Register[6]

Page 31: Prepaid Energy Meter Final Year Project Report

24

At rated conditions, the active and reactive registers will wrap around every 52 seconds. The micro

controller program needs to take this condition into account when calculating the difference

between register values.

3.2.6 Power Calculation

Instantaneous power signals are generated by multiplying the current and voltage signals, for

active power = V x I x Cos(ø) and for reactive power = V x I x Sin(ø). The power signals are

continuously added to the respective energy registers. Positive power will be added to the energy

register contents and negative energy will be subtracted.[9]

Using the Register Values

Active and Reactive energy register

The active and reactive energy measured per count can be calculated by applying the following

formulae:

Energy per Count = Vrated * Irated / 320k

Where

Vrated = Rated mains voltage of meter

Irated = Rated mains current of meter

The active and reactive power measured by the SA9903B is calculated as follows:

P=Vrated * Irated * N / INTtime / 320k

Where

Vrated = Rated mains voltage of meter

Irated = Rated mains current of meter

N = Difference in register values between successive reads (delta value)

INTtime = Time difference between successive register reads (in seconds)[9]

3.2.7 Shunt Resistance (RSH) Calcualtion

A shunt is simply a resistor of very low value (frequently less than one ohm) that is used to help

measure current. As shown in fig 2.10 the shunt resistor Rsh is placed in parallel with a meter to

decrease its sensitivity by a known amount. The shunt does that by bypassing or "shunting" most

of the current around the meter. The shunt resistor there fore lets your take a standard meter, such

as a 0-1miliammeter, and turns it into, say, a 0-20-amp meter.

Page 32: Prepaid Energy Meter Final Year Project Report

25

Fig3.10 :Shunt Resistance

Making the Shunt

The shunt is made from a short length of copper wire. All wire has resistance, so we can use that

property to make a shunt resistor. To make a shunt, you first need to determine how much current

will flow through it. For example, if your meter is going to measure 20 amps full scale, then the

shunt wire must be safely able to carry that amount of current.

Let's say you are going to make a 20-amp shunt using a surplus analog 0-1 millimeter (mA) whose

face plate is graduated from 0-1. Go to a copper-wire table and select an appropriate gauge wire.

Remember that the smaller the wire gauge, the more current it can safely carry. For most hobby

applications, 250 circular mils per amp are more than adequate. To find the circular mils per amp

for the shunt wire, divide the circular mils for the selected wire (found in the copper wire table) by

the current you intend to pass through the wire:

Circular Mils per amp = (circular mils for wire) / (current through the wire)

By using the copper wire table, you will find that 12-gauge wire has a cross-sectional area of 6530

circular mils. By dividing that by 20 amps, we get 326 circular mils/amp, which should work fine.

12 gauge wire is very common, and can be purchased in most hardware stores. To find the

resistance of the shunt, use this equation:

Rsh=Rm / (n-1)

Where Rsh is the resistance of the shunt, Rm is the resistance of the surplus meter, and n is the

shunt's multiplication factor. In our example, since we are using a 0-1mA meter and 1

mA=0.001amps, n=20amps / 0.001amps, or 20,000.Next, let's suppose that the resistance of your

meter was 81 ohms. Plugging that resistance and n=20,000 into above equation, we get

Rsh = 81 / 20,000 - 1) = 0.00405 Ohms

That's not very much resistance, is it! A shunt having that resistance will pass 19.999 amps through

Rsh

RL

R

m

Page 33: Prepaid Energy Meter Final Year Project Report

26

it, and 0.001A (1 mA) will pass through the meter for a full scale reading. Next, we need to

calculate the length of our copper wire shunt. Note that as stated in the copper-wire table, 12 gauge

wire has a resistance of 1.619 ohms/1000ft. Therefore, the length of the shunt wire (Ls) can

therefore be determined using:

Ls=Rsh / (XV/1000ft.) = 0.00405 / (1.619/1000ft.) = 2.5 ft.

So the 12-gauge wire shunt should be 2 feet 6 inches long when using a 0-1mA meter having an

internal resistance of 81 ohms to measure 20 amps full-scale.[12]

Following is the table which gives the Copper Wire Specifications

AWG Diam. Mills

Circular Mills

Ohms/1000ft at 25 C

mm Closest

British SWG

18 40.3 1624.09 6.38 1.024 20

20 32.0 1024.00 10.13 0.813 22

21 28.5 812.25 12.77 0.724 23

22 25.3 640.09 16.20 0.643 24

24 20.1 404.01 25.67 0.511 26

26 15.9 252.81 41.02 0.404 29

28 12.6 158.76 65.31 0.32 31

30 10.0 100.00 103.71 0.254 34

32 8.0 64.00 162.00 0.203 37

34 6.3 39.69 261.30 0.142 38.39

36 5.0 25.00 414.80 0.127 41

38 4.0 16.00 648.20 0.102 43

Table 3.3 : Copper Wire Specifications[12]

Page 34: Prepaid Energy Meter Final Year Project Report

27

3.2.8 Application Circuit

Fig 3.11 : Application Circuit[6]

Page 35: Prepaid Energy Meter Final Year Project Report

28

3.3 Controlling Module

3.3.1 Microcontroller

It is a highly integrated chip that contains all the components comprising a controller. Typically

this includes a CPU, RAM, some form of ROM, I/O ports, and timers. Unlike a general-purpose

computer; which also includes all of these components, a Microcontroller is designed for a very

specific task, to control a particular system. As a result, the parts can be simplified and reduced,

which cuts down production costs. Microcontroller is sometimes called an embedded

Microcontroller, which just means that they are part of an embedded system, i.e. one part of a

larger device or system.

So a Microcontroller combines these components onto the same microchip.

o The CPU core

o Memory (both ROM and RAM)

o Some parallel digital I/O

Fig 3.12 : Block Diagram of Microcontroller

CPU

The CPU is the integration of a number of useful functions into a single IC package. These

functions are:

• The ability to execute a stored set of instructions to carry out user defined tasks.

• The ability to be able to access external memory chips to both read and write data from

and to the memory.

Page 36: Prepaid Energy Meter Final Year Project Report

29

Fig 3.13 :Block Diagram of Microcontroller with ports

The above figure (fig 312) illustrates a typical Microcontroller device and the different sub units

integrated onto the Microcontroller microchip. The heart of the Microcontroller is the CPU

core. In the past this has traditionally been based on an 8-bit microprocessor unit. For example,

Motorola uses a basic 6800 Microprocessor core in their 6805/6808-microcontroller devices. In

recent years, Microcontrollers have been developed around specifically designed CPU cores for

example, the Microchip PIC range of Microcontrollers.[13]

Memory

Memory can be obtained as either:

• Read Only Memory (ROM). This is memory that can only be read, the data being

stored in the memory device during its manufacture.

• Erasable Programmable Read Only Memory (EPROM). This is similar to ROM

type memory but the user can program it. The contents of the memory can be

erased from the memory by exposing the memory chip to ultraviolet radiation for a

short period of time. It can therefore be used many times over.

• Electrically Erasable Programmable Read Only Memory (EEPROM). Similar to

EPROM but has part or all of the memory contents erased by the microprocessor.

ROM

Typically, the amount of ROM type memory will vary between around 512 bytes and 4096 bytes,

although some 16-bit Microcontrollers such as the Hitachi H8/3048 can have as much as 128

Kbytes of ROM type memory.

ROM type memory is used to store the program code. ROM memory can be ROM (as in One Time

Programmable memory), EPROM, or EEPROM.

Page 37: Prepaid Energy Meter Final Year Project Report

30

RAM

The amount of RAM memory is usually somewhat smaller, typically ranging between 25 bytes to

4 Kbytes. RAM is used for data storage and stack management tasks. It is also used for register

stacks (as in the microchip PIC range of Microcontrollers).

I/O

I/O is Input or Output (Input/Output). It can be:

• A number of digital bits formed into a number of digital inputs or outputs called a

port. These are usually eight bits wide and thus referred to as a BYTE wide port.

i.e. byte wide input port, byte wide output port.

• A serial line from the microprocessor (Transmit or TX) and a serial line to the

microprocessor (Receive or RX) allowing serial data in the form of a bit stream to

be transmitted or received via a two wire interface.

• Other I/O devices such as Analogue to Digital Converters (ADC) and Digital to

Analogue Converters (DAC), Timer modules, Interrupt controllers etc.

Fig 3.14 : Block Diagram of Microcontroller with ROM & RAM

RAM Area

CPU ADC

PORT

A

SERIAL PORT

Rx ROM Area

PORT B PORT C

8

8

5 8

PORT

D 8

PORT E 3

Tx

Page 38: Prepaid Energy Meter Final Year Project Report

31

Fig 3.15 : Block Diagram of Microcontroller highlighted PORTS

The digital I/O ports are the means by which the Microcontroller interfaces to the environment.

Digital I/O tends to be grouped into byte wide ports (8 digital bits) that can be configured as either

input bits or output bits. There are some exceptions, such as the microchip PIC 16C54 with one 6-

bit RA port and a byte wide RB port. The number of I/O port bits varies, depending upon the size

of the Microcontroller. Some very simple 8-bit Microcontroller have as few as 4 bits of I/O, whilst

those at the high-end range can have as many as 33 bits of I/O (some 16 bit Microcontrollers could

have around 78 bits of I/O). Most Microcontrollers will also combine other devices such as:

• A Timer module to allow the Microcontroller to perform tasks for certain time

periods.

• A serial I/O port to allow data to flow between the Microcontroller and other

devices such as a PC or another Microcontroller.

• An ADC to allow the Microcontroller to accept analogue input data for processing.

Applications

The Microcontroller is a very common component in modern electronic systems. Its use despread

that it is almost impossible to work in electronics without coming across it. Microcontrollers are

used in a wide number of electronic systems such as:

• Engine management systems in automobiles.

Tx

RAM Area

CPU ADC

TIMER

16-BIT

PORT

A

SERIAL PORT

8

Rx ROM Area

PORT B PORT C

8

8

5 8

PORT

D 8

PORT E 3

Page 39: Prepaid Energy Meter Final Year Project Report

32

• Keyboard of a PC.

• Electronic measurement instruments (such as digital millimeters, frequency

synthesizers, and oscilloscopes)

• Printers.

• Mobile phones.

• Televisions, radios, CD players, tape recording equipment.

• Hearing aids.

• Security alarm systems, fire alarm systems, and building services systems.

3.3.2 PIC Microcontroller

PIC is a family of RISC microcontrollers made by Microchip Technology, derived from the

PIC1650 originally developed by General Instrument's Microelectronics Division.

Microchip Technology does not use PIC as an acronym; in fact the brand name is PICmicro. It is

generally regarded that PIC stands for Peripheral Interface Controller, although General

Instruments' original acronym for the PIC1650 was "Programmable Intelligent Computer". The

original PIC was built to be used with GI's new 16-bit CPU, the CP1600. While generally a good

CPU, the CP1600 had poor I/O performance, and the 8-bit PIC was developed in 1975 to improve

performance of the overall system by offloading I/O tasks from the CPU. The PIC used simple

microcode stored in ROM to perform its tasks, and although the term wasn't used at the time, it is a

RISC design that runs one instruction per cycle (4 oscillator cycles). In 1985 General Instruments

spun off their microelectronics division, and the new ownership cancelled almost everything —

which by this time was mostly out-of-date. The PIC, however, was upgraded with EPROM to

produce a programmable channel controller, and today a huge variety of PICs are available with

various on-board peripherals (serial communication modules, UARTs, motor control kernels, etc.)

and program memory from 512 words to 32k words and more (a "word" is one assembly language

instruction, varying from 12, 14 or 16 bits depending on the specific PICmicro family).[13]

PIC Architecture

Some highlights of the PIC Microcontroller architecture

• Harvard architecture with a separate program memory bus (14 bits wide) for instructions

and a data memory bus (8 bits wide).

• RISC architecture with 35 instructions, each occupying a single 14 bit program memory

word and a two-stage pipeline allowing most instructions to be executed in a single cycle

(the 16F8X models have 1K program flash memory words on the chip; other models have

up to 8K words).

Page 40: Prepaid Energy Meter Final Year Project Report

33

• internal ram memory implemented in two switch able file register banks with 80 bytes

each (they are switched by bit 5 of the Status register; other PIC models may have up to 4

banks); the first 12 file registers are special purpose (and named Special File Registers or

SFR), including the Status register word, Program Counter (PC), interrupt control and

timer.

• 64 bytes of EEPROM memory for storing constant data.

• Hardware controlled stack, 8 levels deep (up to 8 nested subroutine calls)

• 5 types of internal and external interrupts, programmable timer and Watchdog timer.

PIC16F877A is one of the most commonly used Microcontrollers especially in automotive,

industrial, appliances and consumer applications. The main features of this Microcontroller are as

follows.

It is commonly said that Microcontroller is an “entire computer on a single chip”, which implies

that it has more to offer than a single CPU (microprocessor). This additional functionality is

actually located in micro controller’s subsystems, also called the “integrated peripherals”.

Every Microcontroller is supplied with at least a couple of integrated peripherals – commonly;

these include timers, interrupt mechanisms and AD converters. More powerful Microcontrollers

can command a larger number of more diverse peripherals. In this chapter, we will cover some

common systems and the ways to utilize them from BASIC programming language.[13]

Pin Diagram

Fig 3.16 : PIC16F877A Pin Diagram[13]

Page 41: Prepaid Energy Meter Final Year Project Report

34

Block Diagram

Fig 3.17 : PIC16F877A Block Diagram[13]

Interrupt Mechanism

Interrupts are mechanisms, which enable instant response to events such as counter, overflow, pin

change, data received, etc. In normal mode, Microcontroller executes the main program as long as

there are no occurrences that would cause an interrupt. Upon interrupt, Microcontroller stops the

execution of main program and commences the special part of the program that will analyze and

handle the interrupt. This part of program is known as the interrupt (service) routine.[13]

Page 42: Prepaid Energy Meter Final Year Project Report

35

3.3.3 Computation of Consumed Units

In the controlling module the Microcontroller was programmed to read data from the metering IC

every second. The active register of the metering IC is not reset after it has been accessed, thus

when the Microcontroller reads the data from the active register, this value is stored and then

subtracted from the next reading to determine the actual instantaneous power value. The difference

between the current value and previous value is called a delta value. The active register of the

metering IC also wraps around every 52 seconds and this is rectified in software.[6] For each

reading the new delta value is added to the previous delta values and the accumulated value is

compared to a threshold value. The threshold value is the amount of energy measured by thes

meter before a pulse is generated. The threshold value is calculated by dividing the energy

represented by a light emitting diode (LED) pulse by the energy per register count i.e.

Threshold = Epp/Epc,

Epc (Energy per count) = Imax* Vnom /32000,

Where Epp is the energy per pulse, Epc is the energy per count, Imax is the maximum load current

and Vnom is the nominal voltage.

The active register increments at 320000 samples per second, therefore a single count of the energy

corresponds to an amount of energy expressed in Ws (Watt seconds). The pulse rate required for

the meter is usually expressed in pulses/kWh.A single pulse on an LED is a fraction of a kWh and

is converted to energy in Ws/pulse[9] i.e.

Epp (Energy per LED pulse) = 1000*3600/Mpr

Where Mpr is the pulse rate of the meter in pulses/kWh.

Pulse

A single unit (kWh) is divided into 100 fractions where each fraction represents 0.01 kWh and is

also called a Pulse. In this implementation, every second a reading is taken and compared with the

threshold value. When the threshold value is reached, a pulse is generated on an LED, denoting

0.01kWh power consumption, thus a 100 pulses result in 1kWh power consumption. Every time a

pulse is generated, the power consumption value is integrated with the previous value and

stored.[10]

Page 43: Prepaid Energy Meter Final Year Project Report

36

3.3.4 Evaluation of a Delta Value ----- Software Dependant

Delta value is the difference between the current value and the previous value that lies in the

register which is been accessed. There are three cases from which we measured the Delta value.

Also it is not always the case that Delta Value is a multiple of Threshold Value to find the Pulse so

in order to have accuracy in the computations Delta Value is divided by the Threshold and integer

value (quotient) is stored in a variable called ‘check’. There is also a variable called ‘remain’

which stores the remainder of the Delta Value and the Threshold Value.[14] The operation is

shown in the flow chart given below. Three cases for the evaluation of Delta value are:

Oldresult > presentresult (previous value is greater than the current value)

Oldresult < presentresult (previous value is smaller than the current value)

Oldresult == presentresult (previous value is equal to the current value)

Flow Charts to Evaluate Delta Value

When previous value is greater than the current value then delta value is computed as:

deltavalue = remains + ((16777215 - oldresult) + presentresult)

Where 16777215 = Max value in decimal in 24 bit register (224 =16777215)

When previous value is smaller than the current value then delta value is computed as:

deltavalue=presentresult - oldresult + remains

Fig 3.18 :Flow Chart to Compute Delta Value

Page 44: Prepaid Energy Meter Final Year Project Report

37

3.4 Display System

This acquisated data in the Microcontroller is displayed on the LCD that is in the display module

via parallel interfacing with Microcontroller, the control signals of the LCD are also been send by

Microcontroller. Character LCD is used for this.

3.4.1 User Guide to Operate the System (Visual Aids)

� Normal Display for Both Postpaid and Prepaid Field Units, units represents the Kilowatt

hour (power consumed) factor and pulses are the fraction of units (100 pulses=1Unit):

Fig 3.19 :Main Display Menu

� In Prepaid Field Unit initially there are 10 units and user having the option to enter the

card for this ,To enter card press 1 and to go to the main menu press 2 that is fig 3.19,if the

user do not enter any option timer will expire (fig 3.21) and user returns to main display

menu (fig 3.19)

Fig 3.20 : Initial Display for Prepaid Meter

Page 45: Prepaid Energy Meter Final Year Project Report

38

Fig 3.21 : Timer Expires

� To go to the entry card menu there is a ‘#’ button on the keypad for this purpose (fig 3.22)

and the menu appears as shown in fig 3.23

Fig 3.22 : Keypad ‘#’ Button

Fig 3.23 : Enter Card Menu

� By pressing ‘2’ user go to the main display menu (fig 3.19) and by pressing ‘1’ following

is the display (fig 3.24), after entering the card number there is confirmation asking from

the user that is this is a correct code for this press ‘1’ to right entry and back to main

display menu (fig 3.19) and press ‘2’ for reentry for the card code or number(fig 3.24)

Page 46: Prepaid Energy Meter Final Year Project Report

39

Fig 3.24 : Code Entry Menu

3.4.2 Application Flow Chart

IC Initialization

Set Display ON

Set Display Line

Write Data to

Write data to Line 1

Write data to Line 2

End

Fig 3.25 : Confirmation of Code

Fig 3.26 : Application Flow Chart of LCD

Page 47: Prepaid Energy Meter Final Year Project Report

40

3.4.3 Pin Assignment

Table 3.4 : LCD Specification[15]

3.4.4 Instruction Description

� Clear Display

Table 3.4.1 : Clear Display Data Field[15]

Clear all the display data by writing “20H”(space code) to all DDRAM address, and set DDRAM

address to “00H” into AC (address counter). Return cursor to the original status; namely, bring the

cursor to the left edge on the first line of the display. Make the entry mode increment

(I/D=”High”). [15]

� Return Home

Table 3.4.2 : Return Home Data[15]

Page 48: Prepaid Energy Meter Final Year Project Report

41

Set DDRAM address to “00H” into the address counter. Return cursor to its original site and return

display to its original status, if shifted. Contents of DDRAM do not change. [15]

� Entry Mode Set

Table 3.4.3 : Entry Mode Set[15]

Set the moving direction of cursor and display.

I/D:Increment /decrement of DDRAM address(cursor or blink)

I/D=High,cursor/blink moves to right and DDRAM address is increased by 1.

I/D=low,cursor/blink moves to left and DDRAM address is decreased by 1.

*CGRAM operates the same way as DDRAM, when reading from or writing to CGRAM.

SH:Shift of entire display

When DDRAM read (CGRAM read/write) operation or SH=Low, shifting of entire display is not

performed. if SH=High, and DDRAM write operation, shift of entire display is performed

according to I/D value(I/D=High,shift left,I/D=Low, shift right).

� Display ON/OFF Control

Table 3.4.4 : Display ON/OFF Control[15]

D:Display ON/OFF control bit

When D=High, entire display is turned on.

When D=Low, display is turned off,but display data remains in DDRAM.

C:Cursor ON/OFF control bit

When C=High, cursor is turned on.

When C=Low, cursor is disappeared in current display, but I/D register preserves its data.

B:Cursor Blink ON/OFF control bit

When B=High, cursor blink is on, which performs alternately between all the “High” data and

display characters at the cursor position.

When B=Low, blink is off. [15]

Page 49: Prepaid Energy Meter Final Year Project Report

42

� Cursor or Display Shift

Table 3.4.5.1 : Cursor Or Display Shift[15]

Shifting of right/left cursor position or display without writing or reading of display data. This

instruction is used to correct or search display data. During 2-line mode display, cursor moves to

the 2nd line after the 40th digit of the 1st line.

Note that display shift is performed simultaneously in all the lines. When displayed data is shifted

repeatedly, each line is shifted individually. When display shift is performed, the contents of the

address counter are not changed.

Table 3.4.5.2 : Cursor Or Display Shift[15]

� Function set

Table 3.4.6 : Function Set[15]

DL:Interface data length control bit

When DL=High, it means 8-bit bus mode with MPU.

When DL=Low, it means 4-bit bus mode with MPU.

When 4-bit bus mode, it needs to transfer 4-bit data twice.

N:Display line number control bit

When N=Low, 1-line display mode is set.

When N=High, 2-line display mode is set.

F:Display font type control bit

When F=Low, 5x8 dots format display mode is set.

Page 50: Prepaid Energy Meter Final Year Project Report

43

When F=High, 5x11 dots format display mode.

� Set CGRAM Address

Table 3.4.7 : Set CGRAM Address[15]

Set CGRAM address to AC.

This instruction makes CGRAM data available from MPU.

� Set DDRAM Address

Table 3.4.8 : Set DDRAM Address[15]

Set DDRAM address to AC.

This instruction makes DDRAM data available from MPU. When 1-line display

mode(N=Low),DDRAM address is from “00H” to “4FH”.In 2-line display

mode(N=High),DDRAM address in the 1st line is from “00H” to“27H”,and DDRAM address in

the 2nd line is from “40H” to “67H”.[15]

Page 51: Prepaid Energy Meter Final Year Project Report

44

Communication

Module

Storage Media

Processing Of Data

Data from Field Unit

DATA CONCENTRATOR

CHAPTER # 4

Data Concentrator (Brick)

4.1 Introduction

A data concentrator usually called bricks will extract the data from the field units via SPI

interface at the selected intervals and store them on to the on board non-volatile memory,

the memory used for this is M95040, which is 4k * 8 (4Kbit). Data is send to the area’s

sub-station after every selected interval via wireless communication link for this a SMS is

send from mobile phone which is connected to the microcontroller through DB-9

connector.

4.2 Block Diagram of Data Concentrator

Fig 4.1 : Block Diagram of Data Concentrator

To Field Unit From Field Unit

Page 52: Prepaid Energy Meter Final Year Project Report

45

4.3 Communication Module

The communication module sends the acquisated data that is in the microcontroller (discussed in

ch: 3) to the area sub-station by using the mobile phone. The mobile phone used for this purpose is

Sony Ericson’s T290.

4.3.1Addressable Universal Synchronous Asynchronous Receiver Transmitter

(USART)

The Universal Synchronous Asynchronous Receiver Transmitter (USART) module is one of the

two serial I/O modules. (USART is also known as a Serial Communications Interface or SCI.) The

USART can be configured as a full-duplex asynchronous system that can communicate with

peripheral devices, such as CRT terminals and personal computers, or it can be configured as a

half-duplex synchronous system that can communicate with peripheral devices, such as A/D or

D/A integrated circuits, serial EEPROMs, etc[13]. For this the Transmit and Receive Status and

Control Register of microcontroller is used as shown in fig 4.2 and 4.3.

The USART can be configured in the following modes:

� Asynchronous (full-duplex)

� Synchronous – Master (half-duplex)

� Synchronous – Slave (half-duplex)

Fig 4.2 : Transmitt Status and Control Register[13]

Fig 4.3 : Receive Status and Control Register[13]

4.3.2 USART Baud Rate Generator (BRG)

Baud Rate

Baud rate is a measure of how fast data is moving between instruments that use serial

communication. RS-232 uses only two voltage states, called MARK and SPACE. In such a

two-state coding scheme, the baud rate is identical to the maximum number of bits of

Page 53: Prepaid Energy Meter Final Year Project Report

46

information, including "control" bits, that are transmitted per second. MARK is a negative

voltage and SPACE is positive; the figure 4.4 shows how the idealized signal looks on an

oscilloscope.

Fig 4.4 :Baud Rate

The BRG supports both the Asynchronous and Synchronous modes of the USART. It is a

dedicated 8-bit baud rate generator. The SPBRG register controls the period of a free running 8-bit

timer. In Asynchronous mode, bit BRGH (TXSTA<2>) also controls the baud rate. In

Synchronous mode, bit BRGH is ignored. Table 4.1 shows the formula for computation of the

baud rate for different USART modes which only apply in Master Mode (internal clock). Given

the desired baud rate and FOSC, the nearest integer value for the SPBRG register can be calculated

using the formula in Table 4.1[13]. From this, the error in baud rate can be determined.

SYNC

BRGH=0(Low Speed)

BRGH=1(High Speed)

0

1

(Asynchronous) Baud Rate = FOSC/(64 (X + 1))

(Synchronous) Baud Rate = FOSC/(4 (X + 1))

Baud Rate = FOSC/(16 (X + 1))

NA

Table 4.1 : Baud Rate Formula

4.3.3 DB-9 Connector

This connector is occasionally found on smaller RS-232 lab equipment. It is compact yet has

enough pins for the "core" set of serial pins (with one pin extra). The DB-9 pin numbers for

transmit and receive (3 and 2) are opposite of those of the DB-25 connector (2 and 3). Be careful

with this when you're determining if a device is DTE or DCE. The images show the male and

female versions of the DB-25 connector with pin numbers. The ideal serial interface has three

classes of connections: a signal common line, two data lines, and five handshake lines. Knowing

Page 54: Prepaid Energy Meter Final Year Project Report

47

how these eight lines work together will give you a reference against which to compare most actual

RS-232 interfaces.

RS232 DB9 Connector Pinout

Pin #1 Data Carrier Detect CD

Pin #2 Receive Data RD or RX or RXD

Pin #3 Transmitted Data TD or TX or TXD

Pin #4 Data Terminal Ready DTR

Pin #5 Signal Ground GND

Pin #6 Data Set Ready DSR

Pin #7 Request To Send RTS

Pin #8 Clear To Send CTS

Pin #9 Ring Indicator RI

Fig 4.5 :DB-9 Male &Female Connectors[16]

� A signal common line must be connected between the DTE and DCE to provide a

reference point for other signal voltages.

� The next step is to connect a pair of data lines between the DTE and the DCE. According

to RS-232, data on each of these lines flows in only one direction, so obviously a pair of

lines is needed for two-way communication. By convention, the name of each data line is

given with respect to the DTE. DB-25 pin 2 of the DTE is called TxD (Transmit Data), and

DB-25 pin 3 of the DTE is called RxD (Receive Data).

� The final step in the construction of a serial interface is to connect the handshake lines.

These lines provide information to each device about the status of the other device. In

particular, the questions "Is the device turned on?" and "Is the device ready to receive

data?" are answered by the state of the handshake lines. It's easy to see how these

handshake functions can be used to regulate and control the flow of information between

two serial devices [16].

Page 55: Prepaid Energy Meter Final Year Project Report

48

4.4 Storage Media

The M95040 is a 4 Kbit (512 x 8) electrically erasable programmable memory (EEPROM),

accessed by a high speed SPI-compatible bus, device is accessed by a simple serial interface that is

SPI-compatible. The device is selected when Chip Select (S) is taken Low. Communications with

the device can be interrupted using Hold (HOLD). WRITE instructions are disabled by Write

Protect (W). [17].

Signal Description

During all operations, VCC must be held stable and within the specified valid range: VCC(min) to

VCC(max). All of the input and output signals can be held High or Low (according to voltages of

VIH, VOH, VIL or VOL, These signals are described next.

Serial Data Output (Q)

This output signal is used to transfer data serially out of the device. Data is shifted out on the

falling edge of Serial Clock (C).

Serial Data Input (D)

This input signal is used to transfer data serially into the device. It receives instructions, addresses,

and the data to be written. Values are latched on the rising edge of Serial Clock (C).

Serial Clock (C)

This input signal provides the timing of the serial interface. Instructions, addresses, or data present

at Serial Data Input (D) are latched on the rising edge of Serial Clock (C). Data on Serial Data

Output (Q) changes after the falling edge of Serial Clock (C).

Chip Select (S)

When this input signal is High, the device is deselected and Serial Data Output (Q) is at high

impedance. Unless an internal Write cycle is in progress, the device will be in the Standby Power

mode. Driving Chip Select (S) Low selects the device, placing it in the Active Power mode. After

Power-up, a falling edge on Chip Select (S) is required prior to the start of any instruction [17].

Page 56: Prepaid Energy Meter Final Year Project Report

49

Hold (HOLD)

The Hold (HOLD) signal is used to pause any serial communications with the device without

deselecting the device. During the Hold condition, the Serial Data Output (Q) is high impedance,

and Serial Data Input (D) and Serial Clock (C) are Don’t Care. To start the Hold condition, the

device must be selected, with Chip Select (S) driven Low.

Write Protect (W)

This input signal is used to control whether the memory is write protected. When Write Protect (W)

is held Low, writes to the memory are disabled, but other operations remain enabled. Write Protect

(W) must either be driven High or Low, but must not be left floating [17].

S 1 8 VCC

Q 2 7 HOLD

W 3 6 C

VSS 4 5 D

Fig 4.6 : M95040[17]

Page 57: Prepaid Energy Meter Final Year Project Report

50

CHAPTER # 5

Wireless Communication Link

5.1 Introduction

The wireless communication between data concentrator and the host system can be done by using

GSM network. For this we use AT commands, are used by TE (Terminal Equipment) to connect to

the mobile phone.

5.2 AT Commands

AT commands are used by TE (Terminal Equipment) to connect to the mobile phone. The TE’s

can be micro controllers, computers etc. These are set of commands described by the RFCs

(request for comments) of the Hayes’s compatible modem. Some AT commands are not supported

by all Samsung GSM products or by all operators. Giving a command that is not supported by a

product causes an error response. All products do not support all command parameters and using

those parameters causes an error response.

Computers use AT commands to communicate with modems. Most communications applications,

however, have a user-friendly interface that hides these AT commands from users. We can issue

the AT commands through our communication application. “AT” or “at” must be included at the

beginning of each command line. These AT commands can be issued to a mobile phone using a

utility in Microsoft Windows, which is called Hyper Terminal. In AT commands jargon this is

called Terminal Adapter (TA). Hyper terminal is used to issue the AT commands to the mobile

which is connected to the serial port of the computer. Hyper terminal can be configured to send

data to the serial port at different baud rates e.g. 110, 300, 1200, 2400, 4800, 9600, 19200, 38400,

57600, 115200, 230400, 460800, 921600 Bits per second. Some AT commands are not supported

by our mobile phone. Giving a command, which is not supported by the mobile, gives error

response. Also, all by all the products may not support some command parameters, and using such

parameters causes an error response.

The “AT” prefix must be included at the beginning of each command line. Several AT command

can be typed on the same line, and in such cases the “AT” prefix is needed only at the beginning of

the command line. The marking <n> used in command syntax is the setting value typed in as a part

of the command. If the value is optional it is enclosed into square brackets. When a setting value is

selected with an AT command then it is valid until it is not changed [18].

5.2.1 Syntax Rules

• A command string should start with start with “AT” or “at”, except for the command “A/”

and “+++”. At or aT are invalid.

Page 58: Prepaid Energy Meter Final Year Project Report

51

• Several commands can be given in one command string.

• The commands can be given in upper or lower case.

• A command string should be less than 40 characters.

• When an error is made during typing of the command, it can be corrected using the

backspace key.

• Command and command string must be terminated with an <ENTER>, except +++ and A/

• A telephone number can exist of following characters:

1 2 3 4 5 6 7 8 9 * = , ; # + >. All other characters are ignored (space, underscore).

They help formatting the dial string.

• Commands that use a numerical parameter can be used without a numerical value. In this

case command will be issued with a value zero.

• If the command string contains two consecutive commands without parameters, as

discussed above, the modem will respond with an error.

• After the command ATZ has been issued, a pause of two seconds should be expected

before entering the next commands.

This command set supports two data formats to represent the messages. PDU (protocol data

unit) and text format. PDU format has all data associated with the message in one 8-bit binary

format parameter and text mode has separate parameters for different message parameters.

Service specific documentation must specify the exact format of these.

Hence it is to use mandatory command +CMGF to list available formats and select the one to

be used with send, list, read and write commands. Different kinds of messages received from

network can be not only stored to a memory, but also forwarded to the TE.

Some elements used in the following section:

<CR> carriage return character, which values is specified in register s3

<DLE> IA5 (international alphabet 5; ITU-T T.50) character 16

<ETX> IA5 character 3

<LF> linefeed character, which values is specified in register S4

ERROR if verbose result codes are enabled with command V1 and command’s parameter

are not accepted by the TA, result <CR> <LF>ERROR<CR> <LF> is sent to the TE, if

numeric result codes are enabled with command V0, result 4<CR> is sent instead

OK if verbose result codes are enabled with command V1 and all commands in

command numeric result codes are enabled with command V0, result 0 <CR> is sent instead.

< . . . > name enclosed in angle brackets is syntactical element; bracket themselves don’t

appear in the command line.

Page 59: Prepaid Energy Meter Final Year Project Report

52

[ . . . ] optional part of command or result code is enclosed in square brackets; brackets

don’t appear in the command line; if command parameter is left out, it equals to its previous

value.

Underline underlined defined parameter value is the recommended default setting of this

parameter (this value should be used when parameter isn’t given in command line)

5.3 At Commands For SMS

AT+CSMS

This command selects the messaging service <service>. Main difference between <service> 0 and

1 is that when <service> = 1 +CNMA acknowledgement is required to most MT short messages

routed directly to the TE.

Command Response Default

AT+CSMS=<service> +csms: 1,1,1 0

AT+CSMS? +csms: <service>,1,1,l

AT+CSMS=? +csms: 1,1,1

Table 5.1 : AT + CSMS[18]

Fig 5.1 : AT + CSMS

AT+CMGF

This command selects the message format. <mode> = 0 selects the SMS PDU mode. <mode>= 1

selects the SMS text mode.

Page 60: Prepaid Energy Meter Final Year Project Report

53

Command Response Default

AT+CMGF=<mode> 0

AT+CMGF? +csmf: <mode>

AT+CMGF=? +csms: (0,1)

Table 5.2 : AT + CMGF[18]

Fig 5.2 : AT + CMGF

AT+CSCA

This command selects the service center number.

Command Response Default

AT+CSCA=<service> 0

AT+CSCA?

AT+CSCA=?

Table 5.3 : AT + CSCA[18]

Fig 5.3 : AT + CSCA

Page 61: Prepaid Energy Meter Final Year Project Report

54

AT+CNMI

New Message Indication to TE. Selects the procedure, for how the receiving of new message from

the network is indicated to TE when TE is active.

Command Response Default

AT+CNMI=<service> +cnmi: 1,1,1 0,0,0,0,0

AT+ CNMI ? +cnmi: <mode>,<mt>,<bm>,<ds>, <bfr>

AT+ CNMI =? +cnmi: 1,1,1

Table 5.4 : AT + CNMI[18]

Fig 5.4 : AT + CNMI

AT+CMGS

Sends a message form the TE to the network (SMS-Submit). Message reference value is returned

to the TE on successful message delivery. Sending can be cancelled by using the <ESC> character.

<ctrl-Z>must be used to indicate the ending of message body. Text/PDU can be used.

Command Response Default

Text mode(+cmgf=1)

At+cmgs=<da>[,<toda>]<CR> text is

enterd <ctrl-Z/ESC

Text mode and sending OK

+cmgs: <mr>[,<scts>]

Text mode

[,129/145]

At+CMGS=? +CSQ: <rssi>, 99

Table 5.5 : AT + CMGS[18]

Page 62: Prepaid Energy Meter Final Year Project Report

55

Fig 5.5 : AT + CMGS

AT+CMGR

This command is used to read the messages that are already present in the inbox from the index

that is given in the command. This command returns the information either the message is read of

unread, number of sender, sending date, sending time and then displays the message.

Command Response

AT+CMGR<index> +CMGR: <read/unread>,<number.>,<date & time>,<msg>

Table 5.6 : AT + CMGR[18]

Fig 5.6 : AT + CMGR

AT+CMGL

This command displays the list of all messages in the preferred memory storage (either mobile or

sim memory) sorted by their indexes.

Page 63: Prepaid Energy Meter Final Year Project Report

56

Command Response

AT+CMGL +CMGL: <index>,<read/unread><number.>,<date & time>,<msg>

Table 5.7 : AT + CMGL[18]

Fig 5.7 : AT + CMGL

5.4 AT Commands To Read SMS

� AT+CMGF=1(for text mode)

� AT+CPMS=“ME”(selects mobile memory)

� AT+CMGR=1(reads memory location#1)

� AT+CMGD=1(delete SMS after reading it)

5.5 AT Commands To Send SMS

� AT+CMGF=1(for text mode)

� AT+CPMS=“ME”(selects mobile memory)

� AT+CMGS=“0300XXXXXXX”\n1 PRE 000010 ctrl^z

Page 64: Prepaid Energy Meter Final Year Project Report

57

CHAPTER # 6

Database System

6.1 Introduction

Finally, a database system is developed on the host side where the data from all the field units is

stored and computed for the billing process, which is at the area sub-station. Database is developed

in MS SQL Server 2000 by using Data Base Management System (DBMS) language. Whereas

using Microsoft Visual Basic 6, the connectivity and the front end user interface will be

established.

6.2 ARMS Application Software Developed at Area Sub-Station

ARMS Appliction Software has actually been designed to make records of all the elcetricity

consumers. ARMS software actually uses Microsoft SQL Server 2000 as its back end for the

record manipulation of the consumers. For a detailed information about Microsoft SQL Server

2000. The Guideline User Interface has been developd in Microsoft Visual Basic 6. For a detailed

information about Microsoft Visual Basic 6. Both Microsoft SQL Server 2000 and Microsoft

Visual Basic 6 have been bounded together using Microsoft Windows Open Database Connectivity

(ODBC) Integral Component.

6.3 Database

A database is a collection of information stored in a computer in a systematic way, such that a

computer program can consult it to answer questions. The software used to mangeand query a

database is known as Database Management System (DBMS).

Database data is usually stored on computer files or on CD-ROM. A database may contain

bibliographic, textual or numeric data. The data are usually structured so that they may be searched

in a number of ways.

6.3.1 DBMS

DBMS (Database Management System) provides you with the software tools you need to organize

that data in a flexible manner. Includes facilities to add, modify or delete data from the database,

ask questions (or queries) about the data stored in the database and produce reports summarizing

selected contents. There are number of DBMS available as follows:

� Microsoft Access

� My SQL

Page 65: Prepaid Energy Meter Final Year Project Report

58

� Oracle

� Microsoft SQL Server

� Foxpro

� Borland Paradox

6.3.2 Block Diagram of DataBase System

Fig 6.1 :Block Diagram of DataBase System

6.4 Database Selection

Choosing the right technology means finding a technology that fills the requirements of your

application. Without knowing the capabilities of the various database technologies. You can easily

choose the wrong one for your particular application. When choosing a database technology one

needs to use it according to the application. However, if one writes his application with a thought

in mind, he will end up creating an application that has a closed, proprietary database that no one

else can use or make sense of.

Even if one is certain that others will never want to access his data except through his application,

then there comes a thought that what about future implementation of his application? What if his

application is windows executable and when he needs to produce a new version of it that runs

behind the web server and provides information to users with Web browsers? Because of the

Computation

Of Electricity

Bills

Permanent Storage OF

All Consumers

Data in Database

Communication

With Data

Concentrator

From Data Concentrator To Data Concentrator

Page 66: Prepaid Energy Meter Final Year Project Report

59

nature of web development tools, an open, non-proprietary database can enable you to perform this

conversion in much less time than a closed, proprietary database.

Now you will go through the process of choosing a database technology for an imaginary

application. You will go and examine each database and technology and see what each one has to

offer. Through this process, you will learn the capabilities and limitations of each database

technology and how to choose the most appropriate technology for your applications.

The best way to learn to choose a database is by using an example and applying it to each

technology. Let’s say that your job is to write an application for a company that sells products

through television advertising. The company advertises products like vegetable slicing machine, a

bamboo steamer and so on, and offers them for the low, low price. Each time the TV commercial

airs the company’s 800 lines is flooded with calls from buyers. The salespeople who take these

calls have your application running on their computers. They use your application to enter each

order so that the products can be shipped and the buyer’s money can be collected. This sounds easy

enough. Your application needs to present a window into which the salesperson can enter the

order, and then your application must write the information for the order to a data file. This being

said, you might decide it would be easier to create your own database.

Now map this example on our own problem domain. We want to maintain a database for electricity

consumers in the Area Sub-Station of Electricity providing Company. We want that there should

be some Window in which the information about the Consumers Electricity Records should be

manipulated and their Electricity Rates and Bills will be computed and displayed. We therefore be,

need with the database:

� The reliability

� Scalability and Availability

� Internet Integration

� Ease of Installation, deployment and use

� Extracting and analyzing summary data for online analytical processing (Data Mining)

We also required such DBMS, which updates the changes occurred in the respective consumer

electricity records. Also provides integration support for Sub-Station to Sub-Station

communications. So according to our requirements we choose Microsoft SQL Server 2000 in the

above list due to the features described in the following section.

Page 67: Prepaid Energy Meter Final Year Project Report

60

6.5 ARMS Database Designing

Database designing is quite easy and simple after getting some basic knowledge. You just

decide the fields of your database and then there are two approaches to design the database

tables on the basis of these fields. One method is normalizing the fields and the second

method is the ERD (Entity Relationship Diagrams) mapping. First have a look at the

following definitions

� Entity: Any real world concept or object is an Entity. For example, a car is an

entity, a book is an entity. Usually, every entity corresponds to a database table.

� Attributes: Every entity has attributes, for example; car is an entity and its model

no and their colors are its attributes. Usually, every attribute corresponds to a field

in the table.

� Primary Key: Every entity has a unique (key) attribute that distinguishes it from

other same entities, for example; in case of car (entity), car no is the primary

attribute. So this primary attribute formulates the primary key of the corresponding

table.

Now according to the ARMS project, we have to maintain the records of electricity

consumers. So we have the following entities:

� Card Information

� Customer Information

� Meter Information

The corresponding attributes of each entity in our database are:

Card Information Customer Information Meter Information

Card ID

Card Number

Card Units

Registration Date

Expire Date

Customer ID

Customer Name

Customer Address

Meter ID

Meter Number

Units

Type

Table 6.1 : Attributes of entities in DB

We moulded all this information into an Entity Relationship Diagram (ERD) and then mapped this

ERD into the corresponding ARMS database tables. Following is the ARMS database diagram

depicting all the tables and their fields:

Page 68: Prepaid Energy Meter Final Year Project Report

61

Fig 6.2 : ARMS Database Tables' Diagram

Finally, we ran the appropriate queries to create the ARMS database and all the three tables for the

database. The queries that we ran are given in the ARMS Codes in the Codes Appendix

6.6 ARMS Visual Basic 6 Guideline User Interface Development

There are the numbers of tools that can be used to fulfill the above-mentioned requirements. So we

choose Microsoft Visual Basic 6 to build an interface for the user of the ARMS application due to

following features of the Visual Basic 6:

� Visual Basic is an enjoyable language due to its visual environment. Much of building a

Windows program in Visual Basic requires dragging and dropping graphic objects onto the

screen from a toolbox which houses those objects. Your Windows program appears before

your eyes as you add the objects.

� Visual Basic is one of the first programming languages to incorporate a true WYSIWYG

(What You See Is What You Get) environment. The program that you build looks like the

program your users sees when they run the program from Windows.

� Visual Basic is much more than just a programming language. The programming language

forms the background of all that takes place in a running Visual Basic program.

Nevertheless, the language is a secondary consideration to the user interface. A Windows

program offers a high degree of user interaction using the graphical elements that form the

objects on the window the user sees. If the user interface is not correct, users will not like

the program.

� In today’s fast-changing world, program maintenance is more critical than ever before.

Companies change, industries consolidate, spin-offs happen. The computer programs of

today must be fluid and maintainable so that programmers can quickly change the program

to meet the needs of a changing environment in which the programs are used. So VB6

provides this.

Page 69: Prepaid Energy Meter Final Year Project Report

62

� Visual Basic 6 includes many new features, especially in the database and Internet areas.

Among these are ADO, DHTML applications, and WebClasses, just to mention the

outstanding ones [19].

ARMS Visual Basic 6 Application Software actually has two components in the overall execution.

Both the components have been binded with the database by using ADO componenets support.

One component is named as ARMS.exe and the second component is named as DataLogger.exe.

They are described as follows:

6.6.1 DataLogger.EXE

We have created our DataLogger.exe application to read the SMS from the mobile phone that has

been attached to the computer on CMO1 port. Actually, ther is a mobile phone attached to the

COM1 port of the computer at Area Sub-Station side in order to complete the Wireless

Communication Link between the Area Sub-Station and the Data Concentrator Module.

Actually, our DataLogger.exe does Polling to the attached mobile phone at regular intervals to

check any new SMS arrival. If there is a new SMS from a Data Concentrator Module, our

DataLogger.exe reads that SMS unfolds it, updates the appropriate records in the database. For a

detailed information on the format of the SMS text.

DataLogger.exe has invisible form and uses various timers to feed AT-Commands to the mobile

Phone using Visual Basic MSComm component. When you drag the MSComm component to your

application form, there are different properties displayed in the properties window of Microsoft

Visual Basic 6 regarding it. Set settings field to 9600,n,8,1. You have to set different properties at

run time like:

MSComm1.CommPort = 1

MSComm1.PortOpen = TRUE

MSComm1.Output = "The data you want to transmit serially"

The first property is to select either COM1 port or COM2 port at run time. Assigning a '1' will

select COM1 port and assigning a '2' will select COM2 port. The second property is to open and

close the connection on COM1 port at run time. Assigning a '1' will open the connection and

assigning a '0' will close the connection. The third command actually sends your data serially to the

attached mobile phone through COM1 port.

Page 70: Prepaid Energy Meter Final Year Project Report

63

Following figure points the MSComm component and its properties window in Microsoft Visual

Basic 6:

Fig 6.3 : Depicts the MSComm Component in VB6 Enviroment

Similarly, you can drag the Timer component to your form. It has two properties that you can set.

First is Interval as displayed in its properties window. You can set it to any integer value where an

integer represents the time in milliseconds. The second property is to enable or disable it. It can be

used at run time as follows:

Timer1.Enabled = TRUE //to enable it

Timer1.Enabled = FALS //to disable it

Page 71: Prepaid Energy Meter Final Year Project Report

64

Following figure points the MSComm component and its properties window in Microsoft Visual

Basic6:

Fig 6.4 : Depicts the Timer Component in VB6 Enviroment

These are the two components upon which our DataLogger.exe appliction is totally based. First we

initialize a MSComm component on COM1 port, then we use Timer component to feed the AT-

Commands serially to the Mobile Phone. The same sets of AT-Commands are used to read and

write the SMS from or to the mobile phone. For the AT-Commands sets used for read and write of

SMS. Whole the code of the DataLiogger.exe has been provided with ARMS Codes section [Codes

Appendix]. The final DataLogger.exe form is as follows:

Fig 6.5 : DataLogger.exe

Page 72: Prepaid Energy Meter Final Year Project Report

65

But when you run DataLogger.exe, it will not be visible to you because its visible property has

been disabled but it will be communicating with the mobile phone and updating the corresponding

records in the database.

6.6.2 ARMS Application.EXE

ARMS Application.exe actually provides a Guideline User Interface (GUI) for WAPDA Employee

to manipulate the records of every electricity consumer and to make it very simple the computaton

and printing of electricity bills with a single mouse click. At the startup, a electricity consumer

makes a request by processing an appliction to have a digital electricity meter installed at his home,

so, ARMS application provides an Installment Form which takes various consumer information as

inputs and initiates a record of the new consumer. After the digital electricity meter has been

installed at his end, the meer will concentrate its data to the Data Concentrator Module. Thus,

Data Concentrator Module will generat an SMS of the consumer data to the Area Sub-Station

where our ARMS application will automatically detect the new SMS arrival on the Mobile Phone

attached to the Area Sub-Station's Computer, so, it will read the SMS and update the appropriate

consumer records. Thus every consumer's records will be updated various times a month at regular

intervals. So, in the end of the month, WAPDA Employee will only click the COMPUTE BILL

button and PRINT button to have the electricity bill out. Thus this ARMS application is the last

module of the project that completes the automation of electricty meter reading and bill generation.

Following are two forms for Meter Information and Customer Information to create a new

consumer record:

Fig 6.6 : ARMS Meter Information Form

Page 73: Prepaid Energy Meter Final Year Project Report

66

This form is to select the type of the meter being installed, i-e; either prepaid or postpaid and

provides add initial balance facility. Following is a second form to collect Personal Information of

the Consumer:

Fig 6.7 : ARMS Customer Information Form

This Second form actually takes consumer's Personal Information such as Name, Address. On the

basis of the Package type, it also allots the consumer a Meter ID. Meter ID is the actual identity of

the electricity consumer through which he is recognized in the whole database.

These forms has been creates by using various Microsoft Visual Basic 6 components like TextBox,

CommandButton, OptionButton, CheckBox, ComboBox, ListBox, HScrollBar and VScrollBar. All

these components (also called controls) have their own properties to get them active and bringing

into flow of the logic for the software. Describing all the controls actually will be opening another

book on Microsoft Visual Basic 6, so I am just providing the Interface of my ARMS

Application.exe and its codes.

The other two forms of the ARMS Application.exe are for ELECTRICITY BILL Generation, one

form for Postpaid Meter Bill and one for showing the Prepaid Meter's Cards History. These forms

are as follows:

Page 74: Prepaid Energy Meter Final Year Project Report

67

Fig 6.8 : ARMS Prepaid Electricity Bill Form

Fig 6.9 : ARMS Postpaid Electricity Bill

Page 75: Prepaid Energy Meter Final Year Project Report

68

CHAPTER # 7

ARMS Implementation

7.1 Tools Used

Following are the brief description of the tools that were used for implementing the system :

7.1.1 OrCAD

OrCAD offers a total solution for your core design tasks:schematic- and VHDL-based design

entry; FPGA and CPLD design synthesis; digital, analog, and mixed-signal simulation; and printed

circuit board layout. What’s more, OrCAD’s products are a suite of applications built around an

engineer's design flow—not just a collection of independently developed point tools.

Typical Board Design Tasks

Typical board design tasks include the following:

� Creating the board. Using Capture, you create a netlist from your schematic that may

include your design rules to guide logical placement and routing, then load the netlist into

Layout.

� Specifying board parameters. You specify global settings for the board, including units of

measurement, grids, and spacing. In addition, you create a board outline and define the

layer stack,padstacks, and vias.

� Placing components and checking the placement. You use the component tool to manually

place components on the board individually or in groups. You then check the placement

using placement information from a variety of sources.

� Routing the board and checking the routing. You route the board, and can take advantage

of push-and-shove (a routing technology), which moves tracks to make room for the track

you are currently routing. You then check the routing using routing information from a

variety of sources.

� Finishing the board. Layout supplies an ordered progression of commands on the Auto

menu for finishing your design. These commands include Design Rule Check, Cleanup

Design, Rename Components, Back Annotate, Run Post Processor, and Create Reports.

� Layout includes GerbTool, which is a full-featured CAM tool, including a Gerber editor,

that reads and writes all standard Gerber formats and IPC-356. GerbTool has features for

automatic teardropping, panelization, venting and thieving, and removal of unused pads

and silkscreen on pads. These processes are used to improve manufacturability. Layout

Page 76: Prepaid Energy Meter Final Year Project Report

69

also includes Visual CADD, which is a two-dimensional drafting tool you can use for your

mechanical design needs. Visual CADD facilitates design and drafting by providing tools

for creating board outlines, height keepins and keepouts, and similar objects, as well as

single or double lines, circles, regular and irregular polygons, and more. Visual CADD

imports and exports .DWG, .DXF, and .GCD files.

Creating a Board

Before you begin creating a board, read the following to become more familiar with the types of

files you may be working with. A netlist file (.MNL) describes the interconnections of a schematic

design using the names of the nets, components, and pins. A netlist contains the following:

� Footprint names

� Electrical packaging

� Component names

� Net names

� The component pin for each net

� Net, pin, and component property information

A technology template (.TCH) specifies the characteristics of a board, including manufacturing

complexity and component type. Technology templates can also include the layer structure, grid

settings, spacing instructions, and a variety of other board criteria. The technology templates

supplied with Layout are documented in

A board template (.TPL) combines a board outline and possible mounting holes, edge connectors,

and other physical board objects merged with Layout’s default technology template,

DEFAULT.TCH. The board templates supplied with Layout are illustrated in the OrCAD Layout

Footprint Libraries manual. A board file (.MAX) contains all of the board’s physical and electrical

information.

Auotrouting

Gridded Autorouter

Layout’s gridded autorouter has two key features: sweep technology, which allows you to specify

the directional emphasis for routing different boards, and shove technology, which minimizes vias

and allows extremely dense autorouting. In addition, you can use interactive routing tools (see

Interactive routing tools below) with the gridded autorouter to refine the process of autorouting.

Sweep Technology

The autorouter routes the board using sweeps, which are successive routing passes. Beginning at a

specified point, Layout routes the board continually according to the sweep direction you specify.

Page 77: Prepaid Energy Meter Final Year Project Report

70

For example, if you want the sweeps to progress up first and then to the left, the autorouter routes

vertically and then horizontally, working through the entire board.

Shove Technology

The autorouter finds the optimal space for a given track and then moves or “shoves” other tracks

out of the way before routing in that area. If a pad or via is blocking the routing path, then the

autorouter attempts to go around the blockage by routing to a different layer using a via. The

autorouter also checks to see if there are obstructing tracks that can be rerouted or moved to an

entirely different location on the board.

Interactive Routing Tools

Though not part of the autorouter itself, interactive routing tools complement the gridded

autorouter by allowing you to refine an autorouted board. Using auto path route mode and shove

track mode, you can route critical nets and dense boards with minimal effort.

After you have completed the above items, you are ready to begin the routing process. The steps in

the autorouting process are:

� Check the board outline, via definitions, and routing and via grids

� Load a routing strategy file

� On predominantly through-hole boards, verifyconnections to the planes

� On SMT boards, implement fanout for power and ground

� Pre-route critical nets

� Implement autorouting

� Optimize routing using the interactive routing tools

� Check for route spacing violations and check routing statistics

� Optimize routing using Layout’s routing commands

Capture

The Project Manager

You use the project manager to collect and organize all the resources you need for your project.

These resources include schematic folders, schematic pages, part libraries, parts, VHDL files, and

output reports such as bills ofmaterials and netlists. A project doesn’t actually contain all the

resources. It merely “points to” the various files that the project uses. For this reason, be sure you

don’t move or delete any files referenced by a project. If you do, the project won’t be able to find

them. The project file is saved with an .OPJ file extension. It is an ASCII file, and can be viewed in

any text editor. Project manager tabs—File and Hierarchy The project manager provides two ways

Page 78: Prepaid Energy Meter Final Year Project Report

71

to display a project’s resources, the project manager displays all the project’s folders, schematic

folders, and schematic pages. These are displayed in a tree-like fashion. You can expand or

collapse the tree by clicking the plus sign in front of the icon. When that branch of the tree is

expanded, the plus sign change to a minus sign., the project manager displays the hierarchical

relationship among the project’s schematic folders and schematic pages. The schematic page

editor In the schematic page editor, you can display and edit schematic pages. You can place parts,

wires, buses, and draw graphics. The schematic page editor has a tool palette that you can use to

draw and place everything you need to create a schematic page. You can print from within the

schematic page editor, or from the project manager window.

The Part Editor

Create and edit parts using the part editor. From the View menu of the part editor, you can choose

Part or Package. In Part view you can:

� Create and edit parts and symbols, then store them in new or existing libraries.

� Create and edit power and ground symbols, off-page connector symbols, and title blocks.

� Use the tool palette’s electrical tools to place pins on parts, and its drawing tools to draw

parts and symbols. Package view shows the entire package. A package is a physical part

that contains more than one logical part. You can edit the properties of the entire package,

such as part reference, prefix, part alias, and so on. You cannot edit individual parts in this

view, but you can select individual parts to edit by double-clicking on them. The part

editor is very similar to the symbol editor. The main difference between the two is the

symbol editor’s lack of Pin and Pin Array tool palette buttons.

7.1.2 PROTEUS---ISIS

Many CAD users dismiss schematic capture as a necessary evil in the process of creating PCB

layout but we have always disputed this point of view. With PCB layout now offering automation

of both component placement and track routing, getting the design into the computer can often be

the most time consuming element of the exercise. And if you use circuit simulation to develop your

ideas, you are going to spend even more time working on the schematic.

ISIS has been created with this in mind. It has evolved over twelve years research and development

and has been proven by thousands of users worldwide. The strength of its architecture has allowed

us to integrate first conventional graph based simulation and now - with PROTEUS VSM -

interactive circuit simulation into the design environment. For the first time ever it is possible to

draw a complete circuit for a micro-controller based system and then test it interactively, all from

within the same piece of software. Meanwhile, ISIS retains a host of features aimed at the PCB

designer, so that the same design can be exported for production with ARES or other PCB layout

software.

Page 79: Prepaid Energy Meter Final Year Project Report

72

For the educational user and engineering author, ISIS also excels at producing attractive

schematics like you see in the magazines. It provides total control of drawing appearance in terms

of line widths, fill styles, colours and fonts. In addition, a system of templates allows you to define

a ‘house style’ and to copy the appearance of one drawing to another.

Other general features include:

� Runs on Windows 98/Me/2k/XP and later.

� Automatic wire routing and dot placement/removal.

� Powerful tools for selecting objects and assigning their properties.

� Total support for buses including component pins, inter-sheet terminals, module ports and

wires.

� Bill of Materials and Electrical Rules Check reports.

� Netlist outputs to suit all popular PCB layout tools.

For the ‘power user’, ISIS incorporates a number of features which aid in the management of large

designs. Indeed, a number of our customers have used it to produce designs containing many

thousands of components.

� Hierarchical design with support for parameterized component values on sub-circuits.

� Design Global Annotation allowing multiple instances of a sub-circuit to have different

component references.

� Automatic Annotation - the ability to number the components automatically.

� ASCII Data Import - .this facility provides the means to automatically bring component

stock codes and costs into ISIS design or library files where they can then be incorporated

or even totaled up in the Bill of Materials report.

ISIS provides the development environment for PROTEUS VSM, our revolutionary interactive

system level simulator. This product combines mixed mode circuit simulation, micro-processor

models and interactive component models to allow the simulation of complete micro-controller

based designs.

ISIS provides the means to enter the design in the first place, the architecture for real time

interactive simulation and a system for managing the source and object code associated with each

project. In addition, a number of graph objects can be placed on the schematic to enable

conventional time, frequency and swept variable simulation to be performed.

Major features of PROTEUS VSM include:

Page 80: Prepaid Energy Meter Final Year Project Report

73

� True Mixed Mode simulation based on Berkeley SPICE3F5 with extensions for digital

simulation and true mixed mode operation.

� Support for both interactive and graph based simulation.

� CPU Models available for popular microcontrollers such as the PIC and 8051 series.

� Interactive peripheral models include LED and LCD displays, a universal matrix keypad,

an RS232 terminal and a whole library of switches, pots, lamps, LEDs etc.

� Virtual Instruments include voltmeters, ammeters, a dual beam oscilloscope and a 24

channel logic analyser.

� On-screen graphing - the graphs are placed directly on the schematic just like any other

object. Graphs can be maximised to a full screen mode for cursor based measurement and

so forth.

� Graph Based Analysis types include transient, frequency, noise, distortion, AC and DC

sweeps and fourier transform. An Audio graph allows playback of simulated waveforms.

� Direct support for analogue component models in SPICE format.

� Open architecture for ‘plug in’ component models coded in C++ or other languages. These

can be electrical., graphical or a combination of the two.

� Digital simulator includes a BASIC-like programming language for modelling and test

vector generation.

� A design created for simulation can also be used to generate a netlist for creating a PCB -

there is no need to enter the design a second time.

7.1.3 Controller Programming Tool

MPLAB Integrated Development Environment (IDE) is a comprehensive editor, project manager

and design desktop for application development of embedded designs using Microchip PICmicro

and dsPIC microcontrollers. MPLAB IDE is a software program that runs on a PC to develop

applications for Microchip microcontrollers. It is called an Integrated Development Environment,

or IDE, because it provides a single integrated "environment" to develop code for an embedded

microcontroller

The built-in components consist of:

Project Manager

The project manager provides integration and communication between the IDE and the language

tools.

Page 81: Prepaid Energy Meter Final Year Project Report

74

Programmer's Editor

The editor is a full-featured programmer's text editor that also serves as a window into the

debugger.

Assembler/Linker and Language Tools

The assembler can be used standalone to assemble a single file, or can be used with the linker to

build a project from separate source files, libraries, and recompiled objects. The linker is

responsible for positioning the compiled code into memory areas of the target microcontroller.

Debugger

The Microchip debugger allows breakpoints, single-stepping, watch windows, and all the features

of a modern debugger for the MPLAB IDE. It works in conjunction with the editor to reference

information from the target being debugged back to the source code.

Execution Engines

There are software simulators in MPLAB IDE for all PICmicro and dsPIC devices. These

simulators use the PC to simulate the instructions and some peripheral functions of the PICmicro

and dsPIC devices. Optional in-circuit emulators and in-circuit debuggers are also available to test

code as it runs in the applications hardware.

Optional components can be purchased and added to the MPLAB IDE:

Compiler Language Tools

MPLAB C17, MPLAB C18 and MPLAB C30 from Microchip provide fully integrated, optimized

code. Along with compilers from Hi-Tech, IAR, microEngineering Labs, CCS, and Byte Craft,

they are invoked by the MPLAB IDE project manager to compile code that is automatically loaded

into the target debugger for instant testing and verification.

Programmers

PICSTART Plus, PRO MATE II, MPLAB PM3 as well as MPLAB ICD 2 can program code into

target microcontrollers. MPLAB IDE offers full control over programming both code and data, as

well as the configuration bits to set the various operating modes of the target microcontrollers

In Circuit Emulators

MPLAB ICE 2000 and MPLAB ICE 4000 are full-featured emulators for the PICmicro and dsPIC

devices. They connect to the PC via I/O ports, and allow full control over the operation of

microcontroller in the target applications.

Page 82: Prepaid Energy Meter Final Year Project Report

75

In Circuit Debugger

MPLAB ICD 2 provides an economic alternative to an emulator. By using some of the on-chip

resources, MPLAB ICD 2 can download code into a target microcontroller inserted in the

application, set breakpoints, single step, and monitor registers and variables.

In order to create code that is executable by the target PICmicro MCU, source files need to be put

into a project and then the code is built into executable code using selected language tools

(assemblers, compilers, linkers, etc.). In MPLAB IDE, the project manager controls this process.

All projects will have these basic steps:

Select Device

The capabilities of MPLAB IDE vary according to which device is selected. Device selection

should be done before doing anything else on a project.

Create Project

MPLAB Project Wizard will be used to Create a Project.

Select Language Tools

In the Project Wizard the language tools will be selected. For this tutorial, the built-in assembler

and linker will be used. For other projects one of the Microchip compilers or other third party tools

might be set.

Put Files in Project

Two files will be put into the project, a template file and a linker script. Both of these exist in sub-

folders in the MPLAB IDE folder and with these two files it is easy to get started quickly.

Create Code

Then some code will be added to the template file to send an incrementing value out an I/O port.

Build Project

The project will be built - causing our source files to be assembled and linked into machine code

that can run on the selected PICmicro MCU.

Test Code with Simulator

And finally, the code will be tested with the simulator

Page 83: Prepaid Energy Meter Final Year Project Report

76

7.1.4 DataBase Development Tool

The development of database is done by using Microsoft® SQL Server™ 2000, features include:

� Internet Integration

The SQL Server 2000 database engine includes integrated XML support. It also has the scalability,

availability, and security features required to operate as the data storage component of the largest

Web sites. The SQL Server 2000 programming model is integrated with the Windows DNA

architecture for developing Web applications, and SQL Server 2000 supports features such as

English Query and the Microsoft Search Service to incorporate user-friendly queries and powerful

search capabilities in Web applications.

� Scalability and Availability

The same database engine can be used across platforms ranging from laptop computers running

Microsoft Windows® 98 through large, multiprocessor servers running Microsoft Windows 2000

Data Center Edition. SQL Server 2000 Enterprise Edition supports features such as federated

servers, indexed views, and large memory support that allow it to scale to the performance levels

required by the largest Web sites.

� Enterprise-Level Database Features

The SQL Server 2000 relational database engine supports the features required to support

demanding data processing environments. The database engine protects data integrity while

minimizing the overhead of managing thousands of users concurrently modifying the database.

SQL Server 2000 distributed queries allow you to reference data from multiple sources as if it were

a part of a SQL Server 2000 database, while at the same time, the distributed transaction support

protects the integrity of any updates of the distributed data. Replication allows you to also maintain

multiple copies of data, while ensuring that the separate copies remain synchronized. You can

replicate a set of data to multiple, mobile, disconnected users, have them work autonomously, and

then merge their modifications back to the publisher.

� Ease of Installation, Deployment, and Use

SQL Server 2000 includes a set of administrative and development tools that improve upon the

process of installing, deploying, managing, and using SQL Server across several sites. SQL Server

2000 also supports a standards-based programming model integrated with the Windows DNA,

making the use of SQL Server databases and data warehouses a seamless part of building powerful

and scalable systems. These features allow you to rapidly deliver SQL Server applications that

customers can implement with a minimum of installation and administrative overhead.

Page 84: Prepaid Energy Meter Final Year Project Report

77

� Data Warehousing

SQL Server 2000 includes tools for extracting and analyzing summary data for online analytical

processing. SQL Server also includes tools for visually designing databases and analyzing data

using English-based questions.

Major components of Microsoft SQL Server are as Follows:

SQL Server Database Architecture

Microsoft® SQL Server™ 2000 data is stored in databases. The data in a database is organized

into the logical components visible to users. A database is also physically implemented as two or

more files on disk.

When using a database, you work primarily with the logical components such as tables, views,

procedures, and users. The physical implementation of files is largely transparent. Typically, only

the database administrator needs to work with the physical implementation.

Each instance of SQL Server has four system databases (master, model, tempdb, and msdb) and

one or more user databases. Some organizations have only one user database, containing all the

data for their organization. Some organizations have different databases for each group in their

organization, and sometimes a database used by a single application. For example, an organization

could have one database for sales, one for payroll, one for a document management application,

and so on. Sometimes an application uses only one database; other applications may access several

databases.

It is not necessary to run multiple copies of the SQL Server database engine to allow multiple users

to access the databases on a server. An instance of the SQL Server Standard or Enterprise Edition

is capable of handling thousands of users working in multiple databases at the same time. Each

instance of SQL Server makes all databases in the instance available to all users that connect to the

instance, subject to the defined security permissions.

When connecting to an instance of SQL Server, your connection is associated with a particular

database on the server. This database is called the current database. You are usually connected to a

database defined as your default database by the system administrator, although you can use

connection options in the database APIs to specify another database. You can switch from one

database to another using either the Transact-SQL USE database name statement, or an API

function that changes your current database context.

SQL Server 2000 allows you to detach databases from an instance of SQL Server, then reattach

them to another instance, or even attach the database back to the same instance. If you have a SQL

Page 85: Prepaid Energy Meter Final Year Project Report

78

Server database file, you can tell SQL Server when you connect to attach that database file with a

specific database name.

SQL Server Query Analyzer

SQL Query Analyzer includes Object Browser, which allows you to navigate through and get

information (such as parameters and dependencies) about database objects, including user and

system tables, views, stored procedures, extended stored procedures, and functions. The Object

Browser also supports generating scripts to either execute or create objects. Other enhancements

include server tracing and client statistics that show information about the server-side and client-

side impact of a given query. SQL Query Analyzer includes a stored procedure debugger. SQL

Query Analyzer also includes templates that can be used as the starting points for creating objects

such as databases, tables, views, and stored procedures.

SQL Server Enterprise Manager

SQL Server Enterprise Manager is the primary administrative tool for Microsoft® SQL Server™

2000 and provides a Microsoft Management Console (MMC)–compliant user interface that allows

users to:

� Define groups of servers running SQL Server.

� Register individual servers in a group.

� Configure all SQL Server options for each registered server.

� Create and administer all SQL Server databases, objects, logins, users, and permissions in each registered server.

� Define and execute all SQL Server administrative tasks on each registered server.

� Design and test SQL statements, batches, and scripts interactively by invoking SQL Query Analyzer.

� Invoke the various wizards defined for SQL Server

7.1.5 Microsoft Visual Basic 6

Visual Basic (VB) is an event driven programming language and associated development

environment from Microsoft for its COM programming model. VB has been replaced by Visual

Basic .NET. The older version of VB was derived heavily from BASIC and enables the rapid

application development (RAD) of graphical user interface (GUI) applications, access to databases

using DAO, RDO, or ADO, and creation of ActiveX controls and objects.

Page 86: Prepaid Energy Meter Final Year Project Report

79

A programmer can put together an application using the components provided with Visual Basic

itself. Programs written in Visual Basic can also use the Windows API, but doing so requires

external function declarations

Event-Driven Programming

Event-driven programming is a computer programming paradigm in which the flow of the program

is determined by user actions (mouse clicks, key presses) or messages from other programs. In

contrast, in batch programming the flow is determined by the programmer. Batch programming is

the style taught in beginning programming classes while event driven programming is what is

needed in any interactive program. Event driven programs can be written in any language although

the task is easier in some languages than in others. Some programming environments make the

task quite easy, others less so [19].

Overview

Instead of waiting for a complete command which may make it to process information, the system

is preprogrammed with an event loop, to look repeatedly for information to process (whether this

might be the appearance of a file in a folder, a keyboard or mouse operation, or a timer event) and

then perform a trigger function to process it. Programming an event driven system is thus a matter

of rewriting the default trigger functions of the system, to match the required behavior.

The method by which information on events is acquired by the underlying system is immaterial.

Inputs can be polled in the event loop, or interrupt handlers can be registered to react to hardware

events; many systems use a mixture of both techniques. The preprogrammed algorithm ensures

that triggers provided are executed when they are needed, thus providing a software abstraction

that emulates an interrupt driven environment.

Event-driven programs typically consist of a number of small programs called event handlers,

which are to be called in response to external events, and a dispatcher, which calls the event

handlers, often using an event queue to hold unprocessed events.

In many cases event handlers can trigger events themselves, possibly leading to an event cascade.

Event-driven programming stresses flexibility and asynchrony as virtues, and tries to be as

modeless as possible. Graphical user interface programs are typically programmed in an event-

driven style.

Computer operating systems are another classic example of event-driven programs on at least two

levels. At the lowest level, interrupt handlers act as direct event handlers for hardware events, with

the CPU hardware performing the role of the dispatcher. Operating systems also typically act as

Page 87: Prepaid Energy Meter Final Year Project Report

80

dispatchers for software processes, passing data and software interrupts to user processes that in

many cases are programmed as event handlers themselves. A command line interface can be

viewed as a special case of the event driven model in which the system, which is inactive, awaits

one very complex event--the entry of a command by the user.

Event-driven programming is a flexible way to allow your programs to respond to many different

inputs or events. Visual Basic for Applications (VBA) is included in many Microsoft applications

(Microsoft Office), and also in many third-party products like AutoCAD, WordPerfect Office 2002

and ESRI ArcGIS. There are small inconsistencies in the way VBA is implemented in different

applications, but it is largely the same language as VB6 [19].

Here is an example of the language:

� Function that returns the area of a circle:

Private Function AreaOfCircle(ByVal Radius)

PI = 3.14159265358979323846264

AreaOfCircle = PI * Radius ^ 2

End Function

� Another example is to write the words "Hello World" on the form:

Private Sub Form1_Load()

Print "Hello World"

End Sub

Language Features

Visual Basic was designed to be easy to learn and use. The language not only allows programmers

to easily create simple GUI applications, but also has the flexibility to develop fairly complex

applications as well. Programming in VB is a combination of visually arranging components or

controls on a form, specifying attributes and actions of those components, and writing additional

lines of code for more functionality. Since default attributes and actions are defined for the

components, a simple program can be created without the programmer having to write many lines

of code. Performance problems were experienced by earlier versions, but with faster computers

and native code compilation this has become less of an issue.

Although programs can be compiled into native code executables from version 5 onwards, they

still require the presence of runtime libraries of approximately 2 MB in size. This runtime is

Page 88: Prepaid Energy Meter Final Year Project Report

81

included by default in Windows 2000 and later, but for earlier versions of Windows it must be

distributed together with the executable.

Forms are created using drag and drop techniques. A tool is used to place controls (e.g., text boxes,

buttons, etc.) on the form (window). Controls have attributes and event handlers associated with

them. Default values are provided when the control is created, but may be changed by the

programmer. Many attribute values can be modified during run time based on user actions or

changes in the environment, providing a dynamic application. For example, code can be inserted

into the form resize event handler to reposition a control so that it remains centered on the form,

expands to fill up the form, etc. By inserting code into the event handler for a keypress in a text

box, the program can automatically translate the case of the text being entered, or even prevent

certain characters from being inserted.

Visual Basic can create executables (EXE), ActiveX controls, DLL files, but is primarily used to

develop Windows applications and to interface web database systems. Dialog boxes with less

functionality (e.g., no maximize/minimize control) can be used to provide pop-up capabilities.

Controls provide the basic functionality of the application, while programmers can insert additional

logic within the appropriate event handlers. For example, a drop-down combination box will

automatically display its list and allow the user to select any element. An event handler is called

when an item is selected, which can then execute additional code created by the programmer to

perform some action based on which element was selected, such as populating a related list.

Alternatively, a Visual Basic component can have no user interface, and instead provide ActiveX

objects to other programs via Component Object Model (COM). This allows for server-side

processing or an add-in module.

The language is garbage collected using reference counting, has a large library of utility objects,

and has basic object oriented support. Since the more common components are included in the

default project template, the programmer seldom needs to specify additional libraries. Unlike many

other programming languages, Visual Basic is generally not case sensitive, although it will

transform keywords into a standard case configuration and force the case of variable names to

conform to the case of the entry within the symbol table entry. String comparisons are case

sensitive by default, but can be made case insensitive if so desired.

Performance

Early versions of Visual Basic were not competitive at performing computationally intensive tasks

because they were interpreted, and not compiled to machine code. Although this roadblock was

removed with VB5 (which compiles to the same intermediate language and uses the same back end

as Visual C++[citation needed]), some features of the language design still introduce overhead

Page 89: Prepaid Energy Meter Final Year Project Report

82

which can be avoided in languages like Delphi or C++. These are more likely to be encountered in

code involving objects, methods, and properties than in strictly numerical code.

Error Handling

Visual Basic does not have exception handling with the same capabilities of C++ or Java, but the

On Error facility does provide nonlocal error handling with features similar to Windows Structured

Exception Handling, including the ability to resume after an error (a feature that is not provided by

either of the other two languages, although of dubious utility in production code).

Simplicity

Some critics of Visual Basic explain that the simple nature of Visual Basic is harmful in the long

run. Many people have learned VB on their own without learning good programming practices.

Even when VB is learned in a formal classroom, the student may not be introduced to many

fundamental programming techniques and constructs, since much of the functionality is contained

within the individual components and not visible to the programmer. Since it is possible to learn

how to use VB without learning standard programming practices, this often leads to unintelligible

code and workarounds. Second, having many of the checks and warnings that a compiler

implements turned off by default may lead to difficulties in finding bugs. Experienced

programmers working in VB tend to turn such checks on.

Debugging

Visual Basic has a comprehensive set of debugging tools comparable to those available in the

Visual C++ products of the same time period. Features include breakpoints, the ability to watch

variables and modify watched variables while paused, the ability to modify the point of execution,

and the ability to make modifications to code while paused, often not requiring a program restart.

Arbitrary code could be executed in the "immediate window", an online interpreter, a very

powerful feature. In some cases, these features were more capable than their counterparts in Visual

C++—for instance, edit and continue in VC was inspired by the VB feature, and there has never

been a VC equivalent of the immediate window.

Some Visual Basic programmers perceive these as strengths needed to avoid case-sensitive

compiler errors, and accidentally omitting line-termination characters some languages require

(usually semicolons). For example, the ability to enter variable and subroutine names in any case,

coupled with the IDE's automatic correction to the case used in the declaration, can be used to the

programmer's advantage: by declaring all names in mixed case, but entering them in lower case

elsewhere, allows the programmer to type faster and to detect typos when a token remains in lower

case.

Page 90: Prepaid Energy Meter Final Year Project Report

83

The language continues to attract much praise and criticism, and it continues to cater to a large

base of users and developers. The language is well suited for certain kinds of GUI applications

(e.g., front end to a database), but less suited for others (e.g., compute-bound programs). Its

simplicity and ease of use explain its popularity as a tool for solving business problems — most

business stakeholders do not care about technical elegance and effectiveness, and concentrate

instead on the cost effectiveness of Visual Basic [19].

Characteristics Present in Visual Basic

Visual Basic has the following uncommon traits:

� Boolean constant True has numeric value -1. In most other languages, True is mapped to

numeric value 1. This is because the Boolean data type is stored as a 16-bit signed integer. In

this construct -1 evaluates to 16 binary 1s (the Boolean value True), and 0 as 16 0s (the

Boolean value False). This is apparent when performing a Not operation on a 16 bit signed

integer value 0 which will return the integer value -1, in other words True = Not False. This

inherent functionality becomes especially useful when performing logical operations on the

individual bits of an integer such as And, Or, Xor and Not.

� Logical and bitwise operators are unified. This is unlike all the C-derived languages (such as

Java or Perl), which have separate logical and bitwise operators.

� Variable array base. Arrays are declared by specifying the upper and lower bounds in a way

similar to Pascal and FORTRAN. It is also possible to use the Option Base statement to set the

default lower bound. Use of the Option Base statement can lead to confusion when reading

Visual Basic code and is best avoided by always explicitly specifying the lower bound of the

array. This lower bound is not limited to 0 or 1, because it can also be set by declaration. In

this way, both the lower and upper bounds are programmable. In more subscript-limited

languages, the lower bound of the array is not variable. This uncommon trait does not exist in

Visual Basic .NET and VBScript.

� Relatively strong integration with the Windows operating system and the Component Object

Model.

� Banker's rounding as the default behavior when converting real numbers to integers.

� Integers are automatically promoted to reals in expressions involving the normal division

operator (/) so that division of an odd integer by an even integer produces the intuitively

correct result. There is a specific integer divide operator (\) which does truncate.

� By default, if a variable has not been declared or if no type declaration character is specified,

the variable is of type Variant. However this can be changed with Deftype statements such as

DefInt, DefBool, DefVar, DefObj, DefStr. There are 12 Deftype statements in total offered by

Visual Basic 6.0.

Page 91: Prepaid Energy Meter Final Year Project Report

84

7.2 Implementation of Digital Field Unit (Power Meter)

7.2.1 Digital Field Unit (Postpaid Meter)

U18

12live

neutral

U17

1234

RC0RC1RC2RC3

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 202122232425262728293031323334353637383940

MCLR

RA0

RA1

RA2

RA3

RA4

RA5

RE0

RE1

RE2

VDD

VSS

OSC1

OSC2

RC0

RC1

RC2

RC3

RD0

RD1

RD2

RD3

RC4

RC5

RC6

RC7

RD4

RD5

RD6

RD7

VSS

VDD

RB0

RB1

RB2

RB3

RB4

RB5

RB6

RB7

R3

130k

C8

+2V5

R6 1.6k

U21

MYRSH

12

LN

Y2

3.579545

R5

1M

U19

12live

neutral

-2V5

C2220nF

RSH

D4Zener

R2

110k

C6820nF

R10

680R

4MHz

U20

1234

RC4RC5RC6RC7

SA9903B

123456789

10

20191817161514131211

IINIIPVrefTp4Tp5Tp6TestVDDTp9OSC2

GNDIVPCSDI

Tp16FMOVSSDO

SCKOSC1

R1210k

R11

680R

R7 1.6k

D1

1N4003

C7

C4220uF

R424k R13

D3Zener

R8 24k

D2

1N4003

GND

R1

110k

U13

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

GND

VCC

VEE

RS R/W

E DB0

DB1

DB2

DB3

DB4

DB5

DB6

DB7

15 16

C1220nF

R14

R9

47 R 2W

C5

470nF

C3220uF

Fig 7.1 : Schematic of Postpaid Meter

Page 92: Prepaid Energy Meter Final Year Project Report

85

7.2.2 Digital Field Unit (Prepaid Meter)

D2

1N4003

R1

110k

+2V5

C7

33PF

C5

470nF

R10

680R

-2V5

R14

U22

Relay

1

2

34

5

Common

NC

NOop

op1

R9

47 R 2W GND

SA9903B

123456789

10

20191817161514131211

IINIIPVrefTp4Tp5Tp6TestVDDTp9OSC2

GNDIVPCSDI

Tp16FMOVSSDO

SCKOSC1

R5

1M

U28

PUSH BUTTON

1

2 3

4PIN1

PIN2PIN3

PIN4

C2220nF

U26

KEYPAD

1234567

ROW0ROW1ROW2ROW3COL0COL1COL2

U21

MYRSH

12

LN

RSH

U18

12liv e

neutralC3220uF

D1

1N4003

R16BADI

1 2 3 4 5 6 7 8 9 10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

MC

LR

RA

0R

A1

RA

2R

A3

RA

4R

A5

RE

0R

E1

RE

2V

DD

VS

SO

SC

1O

SC

2R

C0

RC

1R

C2

RC

3R

D0

RD

1R

D2

RD

3R

C4

RC

5R

C6

RC

7R

D4

RD

5R

D6

RD

7V

SS

VD

DR

B0

RB

1R

B2

RB

3R

B4

RB

5R

B6

RB

7

C4220uF

C833PF

R3

130k

D3Zener

Y2

3.579545

D4Zener

IYAZ BADA1CAP

R7 1.6k

U20

lcd new

1 2 3 4 5 6 7 8 9 10

11

12

13

14

15

16

gn

dv

cc

ve

eR

SR

/WE

1E

2D

B0

DB

1D

B2

DB

3D

B4

DB

5D

B6

DB

7N

C

R13

IYAZ BADACPS

R15BADI

R2

110k

U19

12liv e

neutral

4MHz

R6 1.6k

R11

680R

R8 24k

U17

Relay

1

2

34

5

Common

NC

NOop

op1

U27

PORTC

1234567

RC0RC1RC2RC3RC4RC5RC6

R424k

C6820nF

R12

10k

C1220nF

Fig 7.2 : Schematic of Prepaid Meter

Page 93: Prepaid Energy Meter Final Year Project Report

86

7.2.3 PCB Layout of Postpaid Meter

Fig 7.3 :PCB Layout of Postpaid Meter

7.2.4 PCB Layout of Prepaid Meter

Fig 7.4 : PCB Layout of Prepaid Meter

Page 94: Prepaid Energy Meter Final Year Project Report

87

7.3 Implementation of Data Concentrator (Brick)

7.3.1 Schematic of Data Concentrator

C2220nF

C9

10UF

U17

MAX232

12345678 9

10111213141516

C1+V+C1-C2+C2-V-T2outR2in R2out

T2inT1in

R1outR1in

T1outGNDVCC

U27

PORTC

123456

RC0RC1RC2RC3RC4RC5

C4220uF

R10

680R

U16

memory

1234 5

678

E0E1E2GNDSDA

SCLWC

VCC

GND

C1210UF

R12

10k

D1

1N4003

D2

1N4003

D3Zener

D4Zener

C8

C1010UF

R9

47 R 2W

4MHz

1 2 3 4 5 6 7 8 9 10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

MC

LR

RA

0R

A1

RA

2R

A3

RA

4R

A5

RE

0R

E1

RE

2V

DD

VS

SO

SC

1O

SC

2R

C0

RC

1R

C2

RC

3R

D0

RD

1R

D2

RD

3R

C4

RC

5R

C6

RC

7R

D4

RD

5R

D6

RD

7V

SS

VD

DR

B0

RB

1R

B2

RB

3R

B4

RB

5R

B6

RB

7

U18

12liv e

neutral

R11

680R

C7

C1110UF

C5

470nF

+2V5

U30PORTE

1 2 3R

E0

RE

1R

E2

U28

PORTB

12345678

RB0RB1RB2RB3RB4RB5RB6RB7

C3220uF

-2V5

U29

PORTD

12345678

RD

0R

D1

RD

2R

D3

RD

4R

D5

RD

6R

D7

C1220nF

J1

CON9

123456789

Fig 7.5 : Schematic of Data Concentrator

Page 95: Prepaid Energy Meter Final Year Project Report

88

7.3.2 PCB Layout of Data Concentrator

Fig 7.6 :PCB Layout of Data Concentrator

Page 96: Prepaid Energy Meter Final Year Project Report

89

REFERENCES

[1] http://www.electricityforum.com/history-of-electricity.html

[2] http://www.electricityforum.com/what-is-electricity.htm

[3] http://www.electricityforum.com/electricity-generation.html

[4] http://www.electricityforum.com/hydroelectricity.html

[5] http://www.electricityforum.com/basic-electricity.html

[6] SAMES, “Single Phase Power / Energy IC with SPI Interface”. Available:

http://www.sames.co.za, pp. 1-12

[7] http://www.maxim-ic.com/maxqdevtools

[8] M.F. Schwendtner, “Technological developments in electricity metering and associated fields”,

in Proceedings of the 8th International Con erence on Metering and Tarif sfor Energ Supply, pp.

240-242, July 1996.

[9] M.H. Shwehdi and C. Jacobsen, “A microprocessor-based digital wattmeter system design”, in

Proceedings of the 31st Intersociety Con erence on Energy Conversion Engineering (IECEC 96),

vol. 3, pp. 1840-1845, August 1996.

[10] J. Zhang, W. Oghanna and C.L. Bai, “A DSP based electricity meter with remote reading”, in

Proceedings o the 4th International Con erence on Signal Processing (ICSP 1998), vol. 2, pp. 1581-

1584, October 1998.

[11] B.S. Koay, S.S. Cheah, Y.H. Sng, P.H.J. Chong, P. Shum, Y.C. Tong, et al, “Design and

Implementation of a Bluetooth energy meter”, in Proceeding o Joint 4th International Conference

on Information, Communications and Signal Processing and the 4th Pacific Rim Conference on

Multimedia, vol. 3, pp. 1474-1477, December 2003.

[12] "Electronics Now", August 1998, page 51. Dean F. Poeth II, Ph.D.,K8TM and Gernsback

Publications, Inc. 1998

[13] Microchip, “PIC16F87XA Data Sheet 28/40/44-Pin Enhanced Flash Microcontrollers

”. Available: http:// www.microchip.com/cn

[14] S. Vougioukas, and M. Roumeliotis, “A system for basic-level network fault management

based on the GSM short message service (SMS)”, in Proceedings o the International Conference

on Trends in Communication (EUROCON 2001),Vol. 1, pp. 218-222, July 2001.

[15] SHENZHEN JINGHUA DISPLAYS CO.,LTD., “Character Type Dot Matrix LCD Module

JM164A ”. Available: http://www.alldatasheet.com

[16] http://francis.courtois.free.fr/jc1/serial/Basics/DB9.html

[17] ST Microelectronics, “4Kbit, 2Kbit and 1Kbit Serial SPI Bus EEPROM with High Speed

Clock”. Available: http:// www.st.com/

[18] Conexant, “AT Commands Reference Manual”, Available: http:// www.conexant.com

[19] http://en.wikipedia.org/wiki/Visual_Basic_.NET

Page 97: Prepaid Energy Meter Final Year Project Report

90

APPENDIX A

Source Codes (Field Unit)

A.1 Field Unit Code for Energy Measurement,Control and dispaly of

Data(Postpaid)

#include <pic.h> //#include<pic1687x.h> #include<string.h> // Basic Defines // LCD Definitions #define LCD_EN RB4 // Enable #define LCD_RS RB5 // Register select #define LCD_RW RB6 // Read/Write Option #define LCD_STROBE ((LCD_EN = 1),(LCD_EN=0)) #define threshold 654546 //SPI Definations #define SCK RB0 // CLOCK #define CS RB1 // Enable __CONFIG (XT & WDTDIS & PWRTDIS & BORDIS & UNPROTECT & LVPDIS & DEBUGDIS); //Array declared for 24 bit register values const long unsigned int rftable[24]={8388608,4194304,2097152,1048576,524288,262144,131072,65536,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}; //Global Variables Declaration unsigned int vari=0; long unsigned int result=0; long unsigned int presentresult=0; long unsigned int oldresult=0; long unsigned int deltavalue=0; long unsigned int units=0; long unsigned int remains=0; int check=0,pulse=0; const char acadd[10]={1,1,0,0,0,0,0,0,0,0}; char k=0; char i1=0; char i2=0; char sw=0; //Message to be dispalyed on LCD const char msg1[]=" ARMS"; // PIC LCD Functions void DELAY(unsigned char n) { while (--n); } void DelayMs (unsigned char x) {

Page 98: Prepaid Energy Meter Final Year Project Report

91

unsigned char i; unsigned char count; count = 159; while (x > 0) { for (i=0; i<6; i++) { while (count > 0) count --; } x--; } } /*------------LCD Char Function--------*/ //sends one character or number to the display for setup and messages void lcd_write(char data) { LCD_EN = 1; PORTD = data; DelayMs (1); LCD_EN = 0; } /*------------LCD Message Function--------*/ //sends a series of words to display by calling character //function and checking the line number void lcd_message (const char *ptr, unsigned char line) { if (line == 1) { LCD_RS = 0; lcd_write(0x80); //select first row } else if(line==2) { LCD_RS = 0; lcd_write(0xC0); //select seond row } else if(line==26) { LCD_RS = 0; lcd_write(0xC6); //select seond row } else if(line==3) { LCD_RS=0; lcd_write(0x90); //select third row } else if(line==36) { LCD_RS=0; lcd_write(0x96); //select third row } else if(line==46) { LCD_RS=0; lcd_write(0xD6); //select fourth row } else {

Page 99: Prepaid Energy Meter Final Year Project Report

92

LCD_RS=0; lcd_write(0xD0); //select fourth row } LCD_RS = 1; while(*ptr) { lcd_write(*ptr++); //sendind string } } void lcd_init(void) //initialises display to be on, clear etc { LCD_RW = 0; //clear RW-essentially tied to ground LCD_RS = 0; //clear RS LCD_EN = 0; //clear enable lcd_write (0x38); //set display, 8-bit, 2-line, 5x7dots DelayMs (1); //wait 5ms lcd_write (0x0C); //display on, cursor on, blinking on DelayMs (1); //wait 5ms lcd_write (0x06); //Entry Mode Set, Increment Mode, Cursor Shift On DelayMs (1); //wait 5ms lcd_write (0x01); //clear display DelayMs (1); //wait 5ms lcd_message(msg1,1); //calls function for message to be dispalyed on LCD lcd_message("Units:",2); lcd_message("Pulse:",3); lcd_message("Remain",4); } void init(void) { // This disables the A/D module to allow digital I/O //ADCON0 = 0; //ADCON1 = 0x07; //PORTD bits are connected to data bits of LCD TRISD = 0x00; // Control Signals for LCD TRISB4=0; // EN TRISB5=0; // RS TRISB6=0; // R/W TRISB0=0; //FOR SCK TRISB1=0; //FOR CHIP SELECT TRISB2=0; //ADDRESS BIT FOR REGISTER SELECT (DATA IN FOR SA9903B)--DI TRISB3=1; //FOR DATA IN (DATA OUT FOR SA9903B)--DO RB0=1; RB1=RB2=0; } // Function for converting interger into ascii //It is used to convert units consumed into string to be dispayed on LCD //At line3 of LCD units are dispalyed

Page 100: Prepaid Energy Meter Final Year Project Report

93

void init_timerzero(void) { //Initialization of TIMER INTERRUPT (TMR0) GIE=1; // Global Interrupt PSA=0; // Pre-Scaler Assignment(Prescaler assigned to the TMR0) PS0=1; // 1:8 PS1=0; PS2=0; T0CS=0; // TMR0 Clock Source Select Bit (Internal instruction cycle clock CLKOUT) T0IE=1; // TMR0 Overflow Interrupt Enable Bit (Enables The TMR0 Interrupt) TMR0=5; // Initialise the TMRO interrupt from 5 } void itoa_lcd_msg(long unsigned int int_value, unsigned char line) { char ascii_str[11]; int loop = 0; int remainder = 0; for(loop=0;loop<10;loop++) { remainder = int_value % 10; ascii_str[9-loop] = remainder + 48; int_value = int_value / 10; } lcd_message(ascii_str,line); } void main (void) { init (); //calls all initilisation function lcd_init(); //calls LCD initialisation function init_timerzero(); while(1){ while(CS==0) { if(oldresult>presentresult) { deltavalue = remains + ((16777215 - oldresult) + presentresult); check = deltavalue / threshold; pulse=pulse+check; if(pulse>=100) { units++; pulse=pulse-100; } } else if(oldresult<presentresult) { deltavalue=presentresult - oldresult + remains; check = deltavalue / threshold; pulse=pulse+check; if(pulse>=100) { units++; pulse=pulse-100; } } else {}

Page 101: Prepaid Energy Meter Final Year Project Report

94

remains = deltavalue%threshold; oldresult=presentresult; itoa_lcd_msg(units,26); itoa_lcd_msg(pulse,36); itoa_lcd_msg(remains,46); } } // end of while loop } // end of main // IINTERRUPT FUNCTION static void interrupt timer() { T0IF=0; // TMR0 Overflow Interrupt Flag Bit (cleared) TMR0=5; // Initialise the TMRO interrupt from 5 vari++; if(vari%4==0) { if(k==0) { if(vari<77) { CS=1; RB2=acadd[i1]; i1++; } else if(vari<269) { result=(rftable[i2]*RB3) + result; i2++; sw=0; } else { if(sw==0) { CS=0; i1=0; i2=0; presentresult=result; result=0; sw=1; } } } SCK=!SCK; k=!k; if(vari==4000) vari=0; } }

Page 102: Prepaid Energy Meter Final Year Project Report

95

A.2 Field Unit Code for Energy Measurement,Control and dispaly of Data

(Prepaid)

//#include <pic.h> #include<pic1687x.h> #include<string.h> #define THRESHOLD 16777215 #define FU_DO RC0 #define FU_CS RC1 #define CODE_CS RC2 #define CODE_OUT RC3 #define timeout 500 // LCD Definitions #define LCD_EN RB4 // Enable //#define LCD_EN RB7 // Enable E2 FOR 8*24 LCD #define LCD_RS RB5 // Register select #define LCD_RW RB6 // Read/Write Option #define LCD_STROBE ((LCD_EN = 1),(LCD_EN=0)) #define threshold 654546 // KeyPad Definations #define COL0 RE0 #define COL1 RE1 #define COL2 RE2 #define ROW0 RA0 #define ROW1 RA1 #define ROW2 RA2 #define ROW3 RA3 //SPI Definations #define SCK RB0 // CLOCK #define CS RB1 // Enable __CONFIG (XT & WDTDIS & PWRTDIS & BORDIS & UNPROTECT & LVPDIS & DEBUGDIS); //Array declared for 24 bit register values const long unsigned int rftable[24]={8388608,4194304,2097152,1048576,524288,262144,131072,65536,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}; const unsigned int utable[16]={32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1}; //Global Variables Declaration unsigned char ke=255; unsigned int temp_ke=0; unsigned char pk=0; unsigned int vari=0; long unsigned int result=0; long unsigned int presentresult=0; long unsigned int oldresult=0; long unsigned int deltavalue=0; unsigned int units=100; long unsigned int remains=0; long unsigned int fu_units=0; //variable used to transfer data to memory in form of binary bits unsigned char check=0; unsigned char npulse=0;//,opulse=0; const char acadd[10]={1,1,0,0,0,0,0,0,0,0}; unsigned int i=0; unsigned char i1=0; unsigned char i2=0; unsigned int incr=0; unsigned int cd=0;

Page 103: Prepaid Energy Meter Final Year Project Report

96

char loop; bit sw=0; char df=1; void DelayMs () //Delay Function { i=0; while(i<3){} } void calculation(void) //Units Calculation function { if(oldresult>presentresult) { deltavalue = remains + ((THRESHOLD - oldresult) + presentresult); check = deltavalue / threshold; npulse=npulse+check; if(npulse>=100) { units--; npulse=npulse-100; } } else if(oldresult<presentresult) { deltavalue=presentresult - oldresult + remains; check = deltavalue / threshold; npulse=npulse+check; if(npulse>=100) { units--; npulse=npulse-100; } } else {} oldresult=presentresult; remains = deltavalue%threshold; } unsigned char key(void) //Keypad Function { ROW0=1;ROW1=0;ROW2=0;ROW3=0; if(COL0==1) return '1'; else if(COL1==1) return '2'; else if(COL2==1) return '3'; else ; ROW0=0;ROW1=1;ROW2=0;ROW3=0; if(COL0==1) return '4'; else if(COL1==1) return '5'; else if(COL2==1) return '6'; else ; ROW0=0;ROW1=0;ROW2=1;ROW3=0; if(COL0==1)

Page 104: Prepaid Energy Meter Final Year Project Report

97

return '7'; else if(COL1==1) return '8'; else if(COL2==1) return '9'; else ; ROW0=0;ROW1=0;ROW2=0;ROW3=1; if(COL0==1) return '*'; else if(COL1==1) return '0'; else if(COL2==1) return '#'; else ; return 255; } /*------------LCD Char Function--------*/ //sends one character or number to the display for setup and messages void lcd_write(char data) { LCD_EN = 1; PORTD = data; // DelayMs (1); LCD_EN = 0; } /*------------LCD Message Function--------*/ //sends a series of words to display by calling character //function and checking the line number void lcd_message (const char *ptr) { LCD_RS = 1; while(*ptr) { lcd_write(*ptr++); //sendind string } LCD_RS = 0; } void lcd_init(void) //initialises display to be on, clear etc { LCD_RW = 0; //clear RW-essentially tied to ground LCD_RS = 0; //clear RS LCD_EN = 0; //clear enable lcd_write (0x38); //set display, 8-bit, 2-line, 5x7dots DelayMs (); //wait 5ms lcd_write (0x0C); //display on, cursor on, blinking on DelayMs (); //wait 5ms lcd_write (0x06); //Entry Mode Set, Increment Mode, Cursor Shift On DelayMs (); //wait 5ms lcd_write (0x01); //clear display DelayMs (); //wait 5ms } void lcd_initial_msgs (void) //LCD start-up messages

Page 105: Prepaid Energy Meter Final Year Project Report

98

{ //LCD_RS= 0; lcd_write(0x80); //select first row lcd_message(" ARMS "); //calls function for message to be dispalyed on LCD lcd_write(0xC0); //select second row lcd_message("Units:"); lcd_write(0x90); //select third row lcd_message("Pulse:"); lcd_write(0xD0); //select fourth row lcd_message("Remain"); } void init(void) //PORTS Initialization + assigning { // This disables the A/D module to allow digital I/O ADCON0 = 0; ADCON1 = 0x07; //PORTD bits are connected to data bits of LCD TRISD = 0x00; // Control Signals for LCD TRISB4=0; // EN TRISB5=0; // RS TRISB6=0; // R/W

TRISB0=0;RB0=1; //FOR SCK TRISB1=0;RB1=0; //FOR CHIP SELECT TRISB2=0;RB2=0; //ADDRESS BIT FOR REGISTER SELECT (DATA IN //FOR SA9903B)--DI TRISB3=1; //FOR DATA IN (DATA OUT FOR SA9903B)--DO TRISC4=1; TRISC0=0; //FOR DATA OUT TO MASTER(controller in data concentrator //module) RC0=1; TRISC1=1; //CHIP SELECT INPUT FROM MASTER TRISC2=1; //FOR DATA IN FROM MASTER(controller in data concentrator module) TRISC3=0;RC3=1; //CLOCK from slave to master // Used for Keypad initialization COLUMNS & ROWS are used as input TRISE0=1; //COL 0 TRISE1=1; //COL 1 TRISE2=1; //COL 2 TRISA0=0; //ROW 0 TRISA1=0; //ROW 1 TRISA2=0; //ROW 2 TRISA3=0; //ROW 3 RA0=RA1=RA2=RA3=0; } //Initialization of TIMER INTERRUPT (TMR0) void init_timerzero(void) { //Initialization of TIMER INTERRUPT (TMR0) GIE=1; // Global Interrupt PSA=0; // Pre-Scaler Assignment(Prescaler assigned to the TMR0) PS0=1; // 1:16 PS1=1; PS2=0;

Page 106: Prepaid Energy Meter Final Year Project Report

99

T0CS=0; // TMR0 Clock Source Select Bit (Internal instruction cycle clock CLKOUT) T0IE=1; // TMR0 Overflow Interrupt Enable Bit (Enables The TMR0 Interrupt) TMR0=5; // Initialise the TMRO interrupt from 5 } // Function for converting interger into ascii //It is used to convert units(consumed) into string to be dispayed onto LCD //At line3 of LCD units are dispalyed void itoa_lcd_msg(long unsigned int int_value) { char ascii_str[11]; unsigned char remainder = 0; for(loop=0;loop<10;loop++) { remainder = int_value % 10; ascii_str[9-loop] = remainder + 48; int_value = int_value / 10; } lcd_message(ascii_str); } //Keypad scanning calls to recharge card void keypad (void) { lcd_write(0x90); //select third row lcd_message("Enter Card ? "); lcd_write(0xD0); //select fourth row lcd_message("1 for Y&2 for N "); while(COL0==1||COL1==1||COL2==1){} ke=255; while(1) { i=0; while(ke==255&&i<timeout) //if no key pressed, scan keypad again and again //untill timeout ke=key(); if(i>=timeout) ke=200; lcd_write(0xD0); //select fourth row lcd_message("1 for Y&2 for N "); if(ke=='1') { lcd_write (0x01); //clear display DelayMs (); //wait 5ms lcd_write(0x80); //select first row lcd_message(" ARMS "); //calls function for message to be //dispalyed on LCD lcd_write(0xC0); //select second row lcd_message("Enter 5 No. code"); //while(1){} temp_ke=0; for(incr=149;incr<=153;incr++) //accept 5 digit code from user { while(COL0==1||COL1==1||COL2==1){} ke=255; i=0; while(ke==255&&i<timeout) ke=key(); for(pk=incr;pk<153;pk++) temp_ke= ke*10+temp_ke; if(i>=timeout)

Page 107: Prepaid Energy Meter Final Year Project Report

100

{ ke=200; break; } lcd_write(incr); //select third row lcd_message(&ke); } //end 5 digit code accept if(incr==154) //if 5 digit code is completely entered { lcd_write(0xD0); //select fourth row lcd_message("sure ? 1(y) 2(n)"); //are you sure to patch while(COL0==1||COL1==1||COL2==1){} ke=255; i=0; while(ke==255&&i<timeout) ke=key(); if(i>=timeout) ke=200; if(ke=='1') //if YES, i m sure to patch then patch it { lcd_write (0x01); //clear display DelayMs (); //wait 5ms lcd_write(0x80); //select first row lcd_message(" ARMS "); //calls function for //message to be dispalyed on LCD lcd_initial_msgs(); break; } while(COL0==1||COL1==1||COL2==1){} if(ke!=200) ke='1'; } //end if(incr==154) else //entered 5 digit code is not complete ke=200; } else { while(COL0==1||COL1==1||COL2==1){} lcd_write (0x01); //clear display DelayMs (); //wait 5ms lcd_write(0x80); //select first row lcd_message(" ARMS "); //calls function for message to be //dispalyed on LCD lcd_write(0x90); //select third row lcd_message("Timer Expires!!!"); i=0; while(ke==200&&i<=timeout/2){} lcd_initial_msgs(); break; } }// end while(1) }// end function keypad() void main (void) { init (); //calls all initilization function init_timerzero(); //calls Initialization of TIMER ZERO INTERRUPT (TMR0) lcd_init(); //calls LCD initialisation function lcd_write(0x80); //select first row lcd_message(" ARMS "); //calls function for message to be dispalyed on LCD lcd_write(0xC0); //select second row

Page 108: Prepaid Energy Meter Final Year Project Report

101

lcd_message("You Have 10Units"); keypad(); lcd_initial_msgs(); while(1) { ROW0=0;ROW1=0;ROW2=0;ROW3=1; if(COL2==1) //if # is pressed then input for card { lcd_write(0xC0); //select first row lcd_message(" ");//calls function for message to be dispalyed //on LCD keypad(); } if(vari<3500 && vari>270) //if no communication with SA9903B then //calculate UNITS { calculation(); } //if(opulse!=npulse) ////////////////// JAHLEAT //{ LCD_RS=0; lcd_write(0xC6); //select seond row (6th location) itoa_lcd_msg(units); lcd_write(150); //select third row (6th location) itoa_lcd_msg(npulse); lcd_write(0xD6); //select fourth row (6th location) itoa_lcd_msg(remains); //opulse=npulse; //} } // end of while loop } // end of main // IINTERRUPT FUNCTION static void interrupt timer(void) { T0IF=0; // TMR0 Overflow Interrupt Flag Bit (cleared) TMR0=5; // Initialise the TMRO interrupt from 5 vari++; i++; // FU_CK = !FU_CK; if(i2>0) { FU_DO = fu_units%2; fu_units = fu_units/2; i2--; } else if(i2==0&&FU_CS==0) { fu_units = units; i2=30; FU_DO=0; } else { if(i2>32) { cd = (utable[i2-33]*FU_CS) + cd; i2++; } else if(i2==0&&CODE_CS==0) { df=0; i2=33; FU_DO=0;

Page 109: Prepaid Energy Meter Final Year Project Report

102

} else { if(df==0){ units=units + cd; df=1; } i2=0; FU_DO=1; } } if(SCK==1) { if(vari<21) { CS=1; RB2=acadd[i1]; i1++; } else if(vari<69) { result=(RB3*rftable[i1-10]) + result; i1++; sw=0; } else { if(sw==0) { presentresult=result; CS=0; i1=0; result=0; sw=1; } } } SCK=!SCK; if(vari==4000) vari=0;

}

Page 110: Prepaid Energy Meter Final Year Project Report

103

APPENDIX B

Source Codes (Data Concentrator)

B.1 DataConcentrator Code For Acquisating and Sending of Data

#include<pic1687x.h> #define DC_DO1 RC0 #define DC_CS1 RC1 #define DC_DO2 RC2 #define DC_CS2 RC3 unsigned int i=0; unsigned char vari=0; long unsigned int result=0; const long unsigned int rftable[26]={0,8388608,4194304,2097152,1048576,524288,262144,131072,65536,32768,16384,8192,4096,2048,1024,512,256,128,64,32,16,8,4,2,1,0}; char message[46] = {13,'t','+','c','m','g','s','=','"','0','3','2','1','6','9','0','5','0','4','5','"',13,' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',26}; void itoa(long unsigned int int_value) { // char ascii_str[11]; char loop; int remainder = 0; for(loop=0;loop<10;loop++) { remainder = int_value % 10; message[44-loop] = remainder + 48; int_value = int_value / 10; } } void init_timer0(void) { //Initialization of TIMER INTERRUPT (TMR0) GIE=1; // Global Interrupt PSA=0; // Pre-Scaler Assignment(Prescaler assigned to the TMR0) T0CS=0; // TMR0 Clock Source Select Bit (Internal instruction cycle clock CLKOUT) PS0=1; // 1:16 PS1=1; PS2=0; T0IE=1; // TMR0 Overflow Interrupt Enable Bit (Enables The TMR0 Interrupt) TMR0=130; // Initialise the TMRO interrupt from 5 } void init_timer1(void) { //Initialization of TIMER INTERRUPT (TMR0) GIE=1; // Global Interrupt PSA=0; // Pre-Scaler Assignment(Prescaler assigned to the TMR0) T0CS=0; // TMR0 Clock Source Select Bit (Internal instruction cycle clock CLKOUT) PS0=1; // 1:256 PS1=1; PS2=1; T0IE=1; // TMR0 Overflow Interrupt Enable Bit (Enables The TMR0 Interrupt) TMR0=5; // Initialise the TMRO interrupt from 5 } void usart_init(void) { SPEN = 1; TX9 = 0; //0 = Selects 8-bit transmission SPBRG = 129; BRGH = 1; //BRGH: High Baud Rate Select bit (1 = High speed)

Page 111: Prepaid Energy Meter Final Year Project Report

104

SYNC = 0; //SYNC: USART Mode Select bit (0 = Asynchronous mode) } void usart_tx(char ch) { TXREG = ch; while(!TRMT); TRMT = 0; //continue; } void init(void) //PORTS Initialization + assigning { TRISC0=1; //FOR DATA OUT TO SLAVE (Field Unit 1) TRISC1=0; //CHIP SELECT INPUT FROM Slave (Field Unit 1) TRISC2=1; //FOR DATA OUT TO SLAVE(Field Unit) (Field Unit 2) TRISC3=0; //CHIP SELECT INPUT FROM Slave (Field Unit 2) RC1=1; RC3=1; } void main (void) { unsigned char loop = 0; init(); usart_init(); init_timer1(); while(1) { while(i>=300) { DC_CS1=0; if(DC_DO1==0) { result=0; T0IE=0; // TMR0 Overflow Interrupt Enable Bit (Disables The TMR0 Interrupt) i=0; vari=1; DC_CS1=1; init_timer0(); while(i<=24); vari=0; T0IE=0; // TMR0 Overflow Interrupt Enable Bit (Disables The TMR0 Interrupt) itoa(result); TXEN = 1; for(loop=0;loop<46;loop++) usart_tx(message[loop]); TXEN = 0; i=0; result=0; init_timer1(); // break; } } while(i<100) { DC_CS2=0; if(DC_DO2==0) { T0IE=0; // TMR0 Overflow Interrupt Enable Bit (Disables The TMR0 Interrupt) i=0;

Page 112: Prepaid Energy Meter Final Year Project Report

105

vari=2; DC_CS2=1; result=0; init_timer0(); while(i<=24); vari=0; T0IE=0; // TMR0 Overflow Interrupt Enable Bit (Disables The TMR0 Interrupt) itoa(result); TXEN = 1; for(loop=0;loop<46;loop++) usart_tx(message[loop]); TXEN = 0; i=100; init_timer1(); // break; } } } } static void interrupt timer(void) { T0IF=0; // TMR0 Overflow Interrupt Flag Bit (cleared) TMR0=5; // Initialise the TMRO interrupt from 5 i++; if(vari==1) { result=(DC_DO1*rftable[26-i]) + result; } if(vari==2) { result=(DC_DO2*rftable[26-i]) + result; }

}

Page 113: Prepaid Energy Meter Final Year Project Report

106

APPENDIX C

Source Codes (Database Unit)

C.1 DataBase Code For Storage of Data,ConsumerPersonal Info and

Computation of Electricity Bill

Private Sub cardSave_Click()

Dim Conn As New ADODB.Connection

Dim rsMaxID As New ADODB.Recordset

Dim query As String, connectionString As String

Dim output As Double

Dim mType As String

Dim recNo As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial

Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select Max(CardId) from CardInfo"

rsMaxID.Open query, Conn

'MsgBox rsMaxID(0)

If rsMaxID(0).Value > 0 Then

recNo = rsMaxID(0)

Else

recNo = 0

End If

query = "insert into CardInfo values(" & recNo + 1 & "," & "'" & txtCardNo.Text & "'" & "," &

txtUnits.Text & "," & "null,null,null,null)"

Conn.Execute query

Conn.Close

End Sub

Private Sub cmdGenerate_Click()

Dim Conn As New ADODB.Connection

Dim rsPerson As New ADODB.Recordset

Dim rsMeterNo As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Page 114: Prepaid Energy Meter Final Year Project Report

107

Dim i As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select CustName,CustAddress from CustomerInfo where MeterNo like " & "'" &

cmbPostBillMeterNo.Text & "'"

query1 = "Select MeterNo,Units from MeterInfo where MeterNo like " & "'" &

cmbPostBillMeterNo.Text & "'"

rsMeterNo.Open query1, Conn

rsPerson.Open query, Conn

Lblpostpaidname = rsPerson(0)

Lblpostpaidaddress = rsPerson(1)

lblMeterNo = rsMeterNo(0)

lblUnit = rsMeterNo(1)

lblElecCost = rsMeterNo(1) * 3

Conn.Close

End Sub

Private Sub cmdPreGenerate_Click()

Dim Conn As New ADODB.Connection

Dim rsPerson As New ADODB.Recordset

Dim rsMeterNo As New ADODB.Recordset

Dim rsCardNos As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim query2 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Dim i As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select CustName,CustAddress from CustomerInfo where MeterNo like " & "'" &

cmbPreMeterNo.Text & "'"

query1 = "Select Units from MeterInfo where MeterNo like " & "'" & cmbPreMeterNo.Text & "'"

query2 = "Select CardNo from CardInfo where MeterNo like " & "'" & cmbPreMeterNo.Text & "'" & "

AND STATUS like '0'"

rsMeterNo.Open query1, Conn

rsPerson.Open query, Conn

Page 115: Prepaid Energy Meter Final Year Project Report

108

rsCardNos.Open query2, Conn

lblPreAddress = rsPerson(1)

lblPreName = rsPerson(0)

lblRemainUnit = rsMeterNo(0)

lstCardHistory.Clear

Do While Not rsCardNos.EOF

lstCardHistory.AddItem (rsCardNos(0).Value)

rsCardNos.MoveNext

Loop

Conn.Close

End Sub

Private Sub IsPostpaid_Click()

If IsPostpaid.Value = 1 Then

IsPrepaid.Value = 0

End If

End Sub

Private Sub IsPrepaid_Click()

If IsPrepaid.Value = 1 Then

IsPostpaid.Value = 0

End If

End Sub

Private Sub meterSave_Click()

Dim Conn As New ADODB.Connection

Dim rsMaxID As New ADODB.Recordset

Dim query As String, connectionString As String

Dim output As Double

Dim mType As String

Dim recNo As Integer

If IsPrepaid.Value = 1 Then

mType = IsPrepaid.Tag

End If

If IsPostpaid.Value = 1 Then

mType = IsPostpaid.Tag

End If

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial

Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select Max(MeterId) from MeterInfo"

rsMaxID.Open query, Conn

Page 116: Prepaid Energy Meter Final Year Project Report

109

If rsMaxID(0).Value > 0 Then

recNo = rsMaxID(0)

Else

recNo = 0

End If

query = "insert into MeterInfo values(" & recNo + 1 & "," & "'" & mType & txtMeterNo.Text & "'" & ","

& 0 & "," & "'" & mType & "'" & "," & "'" & Now() & "'" & ")"

Conn.Execute query

Conn.Close

End Sub

Private Sub myTab_Click(PreviousTab As Integer)

Dim currentTab As String

currentTab = myTab.Tab

If currentTab = 1 Then

pType.Clear

pType.AddItem ("Postpaid")

pType.AddItem ("Prepaid")

End If

If currentTab = 2 Then

cmbPreMeterNo.Clear

InsertMeterNo

End If

If currentTab = 3 Then

PreInsertMeterNo

End If

End Sub

Private Sub InsertMeterNo()

Dim Conn As New ADODB.Connection

Dim rsMaxID As New ADODB.Recordset

Dim rsMeterNo As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Dim i As Integer

cmbPostBillMeterNo.Clear

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select Count(*) from MeterInfo where Type like 'PST'"

Page 117: Prepaid Energy Meter Final Year Project Report

110

rsMaxID.Open query, Conn

tRec = rsMaxID(0)

rsMaxID.Close

query = "Select MeterNo from CustomerInfo where CustomerInfo.MeterNo like 'PST'"

rsMeterNo.Open query, Conn

cmbPostBillMeterNo.Clear

Do While Not rsMeterNo.EOF

cmbPostBillMeterNo.AddItem (rsMeterNo(0).Value)

rsMeterNo.MoveNext

Loop

Conn.Close

End Sub

Private Sub PreInsertMeterNo()

Dim Conn As New ADODB.Connection

Dim rsMaxID As New ADODB.Recordset

Dim rsMeterNo As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Dim i As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select Count(*) from MeterInfo where Type like 'PRE'"

rsMaxID.Open query, Conn

tRec = rsMaxID(0)

rsMaxID.Close

query = "Select MeterNo from CustomerInfo where MeterNo like 'PRE%'"

rsMeterNo.Open query, Conn

cmbPostBillMeterNo.Clear

Do While Not rsMeterNo.EOF

cmbPreMeterNo.AddItem (rsMeterNo(0).Value)

rsMeterNo.MoveNext

Loop

Conn.Close

End Sub

Private Sub personInfoSave_Click()

Dim Conn As New ADODB.Connection

Page 118: Prepaid Energy Meter Final Year Project Report

111

Dim rsMaxID As New ADODB.Recordset

Dim query As String, connectionString As String

Dim output As Double

Dim mType As String

Dim recNo As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial

Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select Max(CustId) from CustomerInfo"

rsMaxID.Open query, Conn

'MsgBox rsMaxID(0)

If rsMaxID(0).Value > 0 Then

recNo = rsMaxID(0)

Else

recNo = 0

End If

query = "insert into CustomerInfo values(" & recNo + 1 & "," & "'" & pType.Text & "'" & "," & "'" &

MeterNos.Text & "'" & "," & "'" & txtName.Text & "'" & "," & "'" & txtAddress.Text & "'" & "," & "'" &

Now() & "'" & ")"

Conn.Execute query

Conn.Close

End Sub

Private Sub pType_Click()

Dim Conn As New ADODB.Connection

Dim rsMaxID As New ADODB.Recordset

Dim rsMeterNo As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Dim i As Integer

If pType.Text = "Postpaid" Then

mType = "PST"

Else

mType = "PRE"

End If

MeterNos.Clear

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Page 119: Prepaid Energy Meter Final Year Project Report

112

Conn.Open connectionString

query = "Select Count(*) from MeterInfo where Type like " & "'%" & mType & "%'"

rsMaxID.Open query, Conn

tRec = rsMaxID(0)

rsMaxID.Close

query = "Select MeterNo from MeterInfo where Type like " & "'%" & mType & "%'"

rsMeterNo.Open query, Conn

Do While Not rsMeterNo.EOF

MeterNos.AddItem (rsMeterNo(0).Value)

rsMeterNo.MoveNext

Loop

Conn.Close

End Sub

Page 120: Prepaid Energy Meter Final Year Project Report

113

C.2 Data logger

Dim counter As Integer

Private Sub Command1_Click()

Unload Me

End Sub

Private Sub Form_Load()

counter = 0

MSComm1.CommPort = 1

MSComm1.PortOpen = True

ReadInterval.Enabled = True

runcode.Enabled = False

CMGF.Enabled = False

CPMS.Enabled = False

CMGR.Enabled = False

End Sub

Private Sub InsertUnit(MeterNo_ As String, units_ As String)

Dim Conn As New ADODB.Connection

Dim rsMeterType As New ADODB.Recordset

Dim rsMeterUnits As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim query2 As String

Dim query3 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Dim i As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select Type from MeterInfo where MeterNo like " & "'" & MeterNo_ & "'"

query2 = "Select units from MeterInfo where MeterNo like " & "'" & MeterNo_ & "'"

rsMeterType.Open query, Conn

rsMeterUnits.Open query2, Conn

Dim tUnit As Integer

If rsMeterType(0) = "PST" Then

tUnit = rsMeterUnits(0) + units_

Page 121: Prepaid Energy Meter Final Year Project Report

114

query1 = "Update MeterInfo Set MeterInfo.units=" & tUnit & " where MeterInfo.MeterNo like " &

"'" & MeterNo_ & "'"

Conn.Execute query1

Else

tUnit = rsMeterUnits(0) - units_

query1 = "Update MeterInfo Set MeterInfo.units=" & tUnit & " where MeterInfo.MeterNo like " &

"'" & MeterNo_ & "'"

Conn.Execute query1

End If

Conn.Close

End Sub

Private Sub InsertCard(MeterNo As String, CardNo As String)

Dim Conn As New ADODB.Connection

Dim rsCardUnits As New ADODB.Recordset

Dim rsMeterUnits As New ADODB.Recordset

Dim query As String, connectionString As String

Dim query1 As String

Dim query2 As String

Dim query3 As String

Dim output As Double

Dim mType As String

Dim tRec As Integer

Dim i As Integer

connectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security

Info=False;Initial Catalog=ARMS;Data Source=(local)"

Conn.Open connectionString

query = "Select unit from CardInfo where CardNo like " & "'" & CardNo & "'"

query1 = "Select Units from MeterInfo where MeterNo like " & "'" & MeterNo & "'"

rsCardUnits.Open query, Conn

rsMeterUnits.Open query1, Conn

Dim tUnit As Double

tUnit = Conversion.CDbl(rsMeterUnits(0).Value) + Conversion.CDbl(rsCardUnits(0).Value)

query2 = "Update MeterInfo Set MeterInfo.units=" & tUnit & " where MeterInfo.MeterNo like " & "'"

& MeterNo & "'"

query3 = "Update CardInfo Set CardInfo.MeterNo=" & "'" & MeterNo & "'" & " where

CardInfo.CardNo like " & "'" & CardNo & "'"

Conn.Execute query2

Page 122: Prepaid Energy Meter Final Year Project Report

115

Conn.Execute query3

Conn.Close

End Sub

Private Sub mnuAbout_Click()

frmAbout.Show vbModal, Me

End Sub

Private Sub mnuExit_Click()

Unload Me

End Sub

Private Sub ReadInterval_Timer()

ReadInterval.Enabled = False

CMGF.Enabled = True 'by Shahbaz

End Sub

Private Sub runcode_Timer()

runcode.Enabled = False

Dim MessageStr As String

Dim cardmessageStr As String

MessageStr = MSComm1.Input 'by Shahbaz

If MessageStr = "" Then

frmSplash2.Show vbModal, Me

Else

'MsgBox MessageStr, , "SMS" 'by Shahbaz

Dim seg() As String

Dim CopyOfMessage As String

CopyOfMessage = MessageStr

seg = Split(CopyOfMessage)

If seg(2) = "ERROR:" Then

frmSplash1.Show vbModal, Me

ElseIf seg(5) = "0" Or seg(5) = "1" Then

Dim messageType As String

messageType = seg(5)

'MsgBox messageType, , "Message Type" 'by Shahbaz

If messageType = "0" Then

Dim cMeterNo As String

Dim CardNo As String

cMeterNo = seg(6)

Page 123: Prepaid Energy Meter Final Year Project Report

116

'MsgBox cMeterNo, , "cMeterNo" 'by Shahbaz

CardNo = seg(7)

'MsgBox CardNo, , "CardNo" 'by Shahbaz

Call InsertCard(cMeterNo, CardNo)

End If

If messageType = "1" Then

Dim cMeterNo1 As String

Dim cMeterNo2 As String

Dim unit1 As String

Dim unit2 As String

cMeterNo1 = seg(6)

unit1 = seg(7)

cMeterNo2 = seg(8)

unit2 = seg(9)

Call InsertUnit(cMeterNo1, unit1)

Call InsertUnit(cMeterNo2, unit2)

End If

'MSComm1.output = "at+cmgd=" & counter & Chr$(13) 'by Shahbaz

frmSplash.Show vbModal, Me

Else

frmSplash2.Show vbModal, Me

End If

End If

ReadInterval.Enabled = True

End Sub

Private Sub CMGF_Timer() 'by Shahbaz

CMGF.Enabled = False

MSComm1.output = "AT+CMGF=1" & Chr$(13)

'MsgBox "Selecting Mobile Phone Format"

CPMS.Enabled = True

End Sub

Private Sub CMGR_Timer() 'by Shahbaz

CMGR.Enabled = False

counter = counter + 1

If counter = 5 Then

counter = 1

End If

MSComm1.output = "at+cmgr=" & counter & Chr$(13)

'MsgBox "Selecting Mobile Phone Memory Read Loction"

Page 124: Prepaid Energy Meter Final Year Project Report

117

runcode.Enabled = True

End Sub

Private Sub CPMS_Timer() 'by Shahbaz

CPMS.Enabled = False

MSComm1.output = "AT+CPMS=" & Chr$(34) & "ME" & Chr$(34) & Chr$(13)

'MsgBox "Selecting Mobile Phone Memory"

CMGR.Enabled = True

End Sub


Recommended