You are on page 1of 96

SMART ENERGY METER

1

KEYWORDS

ACC : Accumulator
B : B Register
PSW : Program Status Word
SP : Stack Pointer
DPTR : Data Pointer
DPL : Low byte
DPH : High byte
P0 : Port 0
P1 : Port 1
P2 : Port 2
P3 : Port 3
IE : Interrupt Enable control
IP : Interrupt Priority control
TMOD : Timer/counter Mode control
TCON : Timer/counter control
T2CON : Timer/counter 2 control
T2MOD : Timer/counter mode2 control
TH0 : Timer/counter 0high byte
TL0 : Timer /counter 0low byte
TH1 : Timer/counter 1high byte
TL1 : Timer/counter 1low byte
TH2 : Timer/counter 2 high byte
TL2 : Timer/counter 2 low byte
SCON : Serial control
SBUF : Serial data buffer
PCON : Power control
IR : Infra Red
SMART ENERGY METER
2

INDEX

ACKNOWLEDGE ------------------------------------ 6
ABSTRACT ------------------------------------ 7

I.INTRODUCTION 9
II. LITERATURE SURVEY
2.1 Motivation 11
2.2 Background 11
2.3 Aim 11
2.4 Requirement Analysis 12
2.4.1 Hardware Requirements 12
2.4.2 Software Requirements 12
2.5 Scope 12
2.6 Advantages 12
III.DESIGN METHODOLOGY
3.1 Hardware system design 14
3.1.1 Block level design of Smart Energy Meter 14
3.1.2 Selection of Hardware 15
3.1.3 Design consideration of Microcontroller 15
3.1.3.1 8051 15
3.1.3.2 Internal architecture of P89C51RD2FN 16
3.1.3.2.1 I/O ports 17
3.1.3.2.2 Interrupt controls 18
3.1.3.2.3 Bus controllers 19
3.1.3.2.4 Memory organization 19
3.1.3.2.5 Registers in 8051 20
3.1.3.2.6 Oscillator 22
3.1.3.3 Features 23
3.1.4 Serial communication 24
3.1.4.1 Introduction 24
3.1.4.2 Baud rate 25
3.1.5 Hardware design of LCD 25
3.1.5.1 LCD screen 26
3.1.5.2 Features 29
3.1.5.3 Pin configuration 29
3.1.5.4 Specifications 30
3.1.5.5 Functionality of LCD in project 32
3.1.6 MAX232 32
3.1.6.1 Pin configuration 33
3.1.7 RS232 (Female port) 33
3.1.7.1 Voltage levels 33
3.1.7.2 Pin configuration 34
3.1.7.3 DB9 interfacing microcontroller using MAX232 34
3.1.8 Serial port connector 35
3.1.9 Design of KEYPAD 35
SMART ENERGY METER
3
3.1.10 IR sensors and IC NE555 Timer 37
3.1.10.1 Photo transmitter 37
3.1.10.2 Principle of operation 38
3.1.10.3 Application 39
3.1.10.4 Features 39
3.1.10.5 IR receivers 39
3.1.10.6 Photo transistor 39
3.1.10.7 Principle of operation 39
3.1.11 IC NE555 timer 40
3.1.12 Resistors 41
3.1.13 Capacitors 41
3.1.14 Crystal oscillators 42
3.2 Software design 43
3.2.1 Liquid Crystal Display 43
3.2.1.1 Initialization of LCD 43
3.2.1.2 Checking busy state of LCD 43
3.2.2 KEYPAD 47
3.2.2.1 Flow chart of keyboard scanning algorithm 47

IV. IMPLEMENTATION
4.1 Hardware implementation 49
4.1.1 Complete Schematic of Smart Energy Meter 50
4.1.2 Connections of P89C51RD2FN 51
4.1.3 Pin connections of LCD 52
4.1.4 Keypad connections 53
4.1.5 MAX232 and DB9 connections 53
4.1.6 IC555 timer and IR transmitter connections 54

V. SOFTWARE IMPLEMENTATION
5.1 JHD162A LCD interfacing 56
5.1.1 Initialization of LCD 56
5.1.2 Initialization sequence code 56
5.1.3 Checking the busy state of LCD 56
5.1.4 Writing the command to display 57
5.1.5 Writing data to display 57
5.1.6 Displaying the data into LCD 57
5.1.7 4*4 matrix Keypad interfacing 58
5.1.8 Sensors 58

VI. DEBUGGING TECHNIQUES
6.1 KEIL micro vision debugger 61
6.1.1 Introduction to KEIL IDE 61
6.1.2 Features 61
6.1.3 Steps to follow while writing program in KEIL 62
6.2 Flash Magic 63
6.2.1 Features 63
6.3 Null MODEM checking (HYPER TERMINAL) 64
6.4 Hardware debugging techniques 65
CONCLUSION 65
SMART ENERGY METER
4
RESULT 66
VII. BIBILOGRAPHY 67
VIII. APPENDIX
KEIL MICROVISION IDE 68
FLASH MAGIC 77
SET UP OF HYPER TERMINAL 80
COMPLETE CODE 83





















SMART ENERGY METER
5

ABSTRACT

Saving energy is high on the agenda for consumers and businesses, but with most of
the electrical devices today, its difficult to know how much energy we are actually
using at any given point in time. Smart Energy Meter is a meter which helps the
consumers to know their day to day power consumption to better control their usage
and producers to manage production. This meter records consumption of electric
energy in intervals of hour or less. Smart meters enable two-way communication
between the meter and the central system. The proposed project comprises of
hardware design using a low-cost 8-bit P89C51RD2xx microcontroller and the
complete hardware design will be proposed .The Communication is through
SMS.They are two one is admin password and second is user. By this admin password
the cost per unit can be changed by the concerned officerThe system software driver
is also developed using embedded-C programming language in Keil Vision 4 IDE. .
Smart meters are also believed to be a less costly alternative to traditional interval or
time-of-use meters and are intended to be used on a wide scale with all customer
classes, including residential customers. The project also addresses about the various
debugging tools such as Keil Vision 4 C51 debugger and Flash magic tool 9.25
version used to test the implemented prototype.

Keywords: Embedded System , Micro controller , Cross-compiler and Debugging.













SMART ENERGY METER
6
















CHAPTER-1










SMART ENERGY METER
7
CHAPTER - I
INTRODUCTION
Now-a-days electricity has become a basic need to humans. The consumption
of electricity has increased a lot compared to the past years. The theft of electricity
has also become a problem these days and there is no control over the loss due to theft
of electricity. In this project we present you the smart energy meter device used to
measure the consumption of the electricity by the individual and provide security
against theft of electricity.
A smart meter is usually an electrical meter that records consumption of
electric energy in intervals of an hour or less and communicates that information at
least daily back to the utility for monitoring and billing purposes.

Smart meters enable
two-way communication between the meter and the central system. Unlike home
energy monitors, smart meters can gather data for remote reporting.
The term Smart meter often refers to an electricity meter, but it can
increasingly also mean a device measuring natural gas or water consumption. Smart
energy meter is software based, power efficient device that accurately tracks energy
consumption and performs computation. Meter readings can be transmitted to
distributors/utilities over wireless media; thus, eliminating the need of manual meter
reading collection process. The smart energy meter offers major benefits to both
customers and companies in terms of efficiency, reliability, and cost saving.
Imagine if you knew how much energy you were consuming at home at any
time of the day, and knew how much energy each device was using, will you stop
using those energy hog appliances? or use them at the time of the day when the
energy is cheapest? in the economy turmoil we are currently in, I believe all of us are
willing to make those small sacrifices to lower down the bill numbers at the end of the
month.
Smart energy meters are devices that will sit on your home, monitor energy
data from your electricity meter, and let you know how much energy you are using
this put more control on your hands on how you spend your energy at home.
Conventional electricity meters are normally hidden somewhere on a wall on the
basement, and the only time you realize how much energy youve been spending is
when the bill hit the door.
The new smart meters will provide Indian consumers with information
regarding energy consumption that was not previously available with a traditional
meter. This system will allow the easy disconnection of defaulted customers and
power connections from a remote site. The new smart system is also able to instantly
detect tampering with the power lines and sends signals to security personnel if
necessary. Utility employees will also have the ability to change a customers billing
method from pre paid to post paid in a matter of seconds, without having to physically
visit the meter.






SMART ENERGY METER
8




















CHAPTER-2




















CHAPTER- II
SMART ENERGY METER
9
LITERATURE SURVEY

2.1 MOTIVATION
In the present scenario, the use of advanced technologies such as
digital metering has become extremely necessary to achieve greater efficiency, theft
reduction to reduce AT & C losses and to improve revenue collection. The utilities
and planners should now focus on best use of electronic technology to develop a full
smart system, which is capable of offering long term benefits and comprehensive
solutions in addition to theft reduction. In undeveloped and under developing
countries proper distribution of power has to be done. So its the duty of us, engineers
to develop the equipments to reduce the power losses and power thefts.


2.2 BACKGROUND

An electricity meter or energy meter is a device that measures the
amount of electric energy consumed by a residence, business, or an electrically
powered device. Electricity meters are typically calibrated in billing units, the most
common one being the kilowatt hour. Periodic readings of electric meters establish
billing cycles and energy used during a cycle. In settings when energy savings during
certain periods are desired, meters may measure demand, the maximum use of power
in some interval. In some areas, the electric rates are higher during certain times of
day, to encourage reduction in use. The billing of the electricity consumption in these
present days are done with human observation, but this project deals with the
communication for the proper billing through GSM without any human involvement.
Due to theft of electricity leads to power shut down in many of the rural areas in
India.

2.3 AIM:
To design and implement the smart energy meter by using 8051 micro
controller coded in embedded c program.








SMART ENERGY METER
10

2.4 Requirement Analysis:
2.4.1 Hardware requirements
The components those are required for Smart Energy Meter project
is given below.
1. Micro Controller (P89C51R2FN).
2. MAX 232.
3. DB9 or RS232 connector.
4. Power supply.
5. 4*4 matrix keypad.
6. LCD display.
7. 555 timer IC
8. IR sensors.

2.4.2 Software requirements
1. FLASH MAGIC Philips Serial ISP programming utility.
2. KEIL Vision 4IDE C51 Embedded Cross Compiler.

2.5 SCOPE:
The scope of the project work is to introduce advanced technology in
converting dc voltage in to ac voltage and introducing smart energy metering concept.
In future this project can be used to measuring natural gas or water
consumption. These meters can be connected to GSM module and data (i.e.
consumption) can be transmitted over GSM networks and the bills can be
automatically issued to the particular customer through SMS. By making small
modifications in the program (code) we can break the connection if user does not pay
the bills in time. There is no need for the electricity officials to visit the spot to
disconnect the connections i.e., everything can be controlled over the GSM module.
The user can also sell the electricity to the government which is created in his home
using solar cells. These meters can also be used as prepaid energy meters by slightly
modifying them.

2.6 Advantages:
More accurate bills.
Lower bills.
Track of energy usage.
Sell energy back to the grid.
Flexible tariffs.
No more meter readings.

SMART ENERGY METER
11















CHAPTER-3









SMART ENERGY METER
12
CHAPTER - III
DESIGN METHODOLOGY

3.1 Hardware System Design:
3.1. 1 Block level design of smart energy meter
The functional diagram of Smart Energy Meter using GSM or Hyper
Terminal is given below.
Fig 3.1 : Functional block diagram of Smart Energy Meter.


SMART ENERGY METER
13
3.1.2 SELECTION OF HARDWARE:
The hardware selected must be such a way that
Low cost
Low power consumption, small, fast
Continually reacts to changes in the systems environment
Must compute certain results in real-time without delay
Simple design
Easy maintainability and interoperability
Bug-free/Correctness, safety, many more


3.1.3 DESIGN CONSIDERATIONS OF
MICROCONTROLLER
WHY P89C51RD2BN?
The system requirements and control specifications clearly rule out the use of
16, 32 bit microcontrollers.
The P89C51RD2xx contains non-volatile 64KB Flash program memory that is
both parallel programmable and serial In-System and In-Application
Programmable.
In-System Programming (ISP) allows the user to download new code while
the microcontroller sits in the application.
In-Application Programming (IAP) means that the microcontroller fetches new
program code and reprograms itself while in the system. This allows for
remote programming over a modem link. A default serial loader (boot loader)
program in ROM allows serial In-System programming of the Flash memory
via the UART without the need for a loader in the Flash code. For In-
Application Programming, the user program erases and reprograms the Flash
memory by use of standard routines contained in ROM.

3.1.3.1 8051
The 8051 is an 8 bit microcontroller originally developed by Intel in 1980. It is
one of the most popular microcontrollers in the world for its high performance, rich
instruction set and low cost. This device is a Single-Chip 8-Bit Microcontroller
manufactured in an advanced CMOS process and is a derivative of the 8051
microcontroller family. The instruction set is 100% compatible with the 8051
instruction set. Three criteria in choosing the microcontrollers are as follows:
1. Meeting the computing needs of the task at hand efficiently and cost
effectively.
2. Availability of software development tools such as compliers,
assemblers, and debuggers.
3. Wide availability and reliable sources of the microcontroller.
SMART ENERGY METER
14

Some of the features that have made the 8051 popular are:
64 KB on chip program memory.
128 bytes on chip data memory (RAM).
4 register banks.
128 user defined software flags.
Four 8-bit data bus
16-bit address bus
32 general purpose registers each of 8 bits
16 bit timers (usually 2, but may have more, or less).
3 internal and 2 external interrupts.
Bit as well as byte addressable RAM area of 16 bytes.
Four 8-bit ports, (short models have two 8-bit ports).
16-bit program counter and data pointer.
1 Microsecond instruction cycle with 12 MHz Crystal.
8051 models may also have a number of special, model-specific features, such as
UARTs, ADC, Op Amps, etc...

3.1.3.2 Internal architecture of P89C51RD2XX
The P89C51RD2xx contains a non-volatile 8KB/16KB/32KB/64KB Flash
program memory that is both parallel programmable and serial In-System and In-
Application Programmable. In-System Programming (ISP) allows the user to
download new code while the microcontroller sits in the application. In-Application
Programming (IAP) means that the microcontroller fetches new program code and
reprograms itself while in the system.



















SMART ENERGY METER
15
The internal architecture of P89C51RD2FN microcontroller with suitable
diagram


Fig 3.2: Internal architecture of P89C51RD2FN.




3.1.3.2.1 I/O ports:
All 8051 microcontrollers have 4 I/O ports each comprising 8 bits which can
be configured as inputs or outputs. Accordingly, in total of 32 input/output pins
enabling the microcontroller to be connected to peripheral devices are available for
use. Pin configuration, i.e. whether it is to be configured as an input (1) or an output
(0), depends on its logic state. In order to configure a microcontroller pin as an input,
it is necessary to apply logic zero (0) to appropriate I/O port bit. In this case, voltage
level on appropriate pin will be 0.

The 4I/O ports of 8051 are designated as port 0, port 1, port 2, and port
3. All these I/O ports have different functions and conditions while connecting to
external peripherals.


3.1.3.2.1. a Port 0 (P0)-
The P0 port is characterized by two functions. If external memory is used then
the lower address byte (addresses A0-A7) is applied on it. Otherwise, all bits of this
port are configured as inputs/outputs. The other function is expressed when it is
SMART ENERGY METER
16
configured as an output. Unlike other ports consisting of pins with built-in pull-up
resistor connected by its end to 5 V power supply; pins of this port have this resistor
left out. If any pin of this port is configured as an input then it acts as if it floats.
Such an input has unlimited input resistance and undetermined potential. When the
pin is configured as an output, it acts as an open drain. By applying logic 0 to a port
bit, the appropriate pin will be connected to ground (0V). By applying logic 1, the
external output will keep on floating. In order to apply logic 1 (5V) on this output
pin, it is necessary to built in an external pull-up resistor.

3.1.3.2.1. b Port 1 (P1)-
P1 is a true I/O port, because it doesn't have any alternative functions as is the
case with P0, but can be configured as general I/O only. It has a pull-up resistor built-
in and is completely compatible with TTL circuits.

3.1.3.2.1. c Port 2 (P2)-
P2 acts similarly to P0 when external memory is used. Pins of this port occupy
addresses intended for external memory chip. This time it is about the higher address
byte with addresses A8-A15. When no memory is added, this port can be used as a
general input/output port showing features similar to P1.

3.1.3.2.1. d Port 3 (P3)-
All port pins can be used as general I/O, but they also have an alternative
function. In order to use these alternative functions, a logic one (1) must be applied to
appropriate bit of the P3 register. In terms of hardware, this port is similar to P0, with
the difference that its pins have a pull-up resistor built-in.
3.1.3.2.2 Interrupts controls:
There are 7 kinds of interrupt controllers that 8051 handles. They are as
follows.
1. INT0 external interrupt.
2. INT1 external interrupt.
3. Timer 0
4. Timer 1
5. Reset.
6. Transmitted interrupt (TXD).
7. Received interrupt (RXD).
There are two types of external hardware interrupts. Pin 12 (P3.2) and pin 13
(P3.3) of the 8051, designated as INT0 and INT1, are used as external hardware
interrupts. Upon the activation of these pins, the 8051 gets interrupted in whatever it
is doing and jumps to the vector table to perform the interrupt service routines (ISR).

Timer 0 and timer 1 interrupts can be used in pooling method. In this method,
we have to wait until the TF is raised. The problem with this method is that the
microcontroller is tied down the controller. If the timer interrupt in the IE register is
enabled, whenever the timer rolls over, TF is raised, and the microcontroller is
SMART ENERGY METER
17
interrupted in whatever it is doing, and jumps to the interrupts vector table to service
the ISR.

Reset pin is an input pin and is active high (normally low). Upon applying a
high pulse to this pin, the microcontroller will reset and terminate all activities. This is
often referred to as power-on reset. In order for RESET input to be effective, it must
have a minimum duration of two machine cycles. In other words, the high pulse must
be high for a minimum of two machine cycles before it is allowed to go low. TXD
and RXD are serial communication interrupts.

3.1.3.2.3 BUS CONTROLS
The main bus controllers available in 8051 are ALE, EA, RST and PSEN.
ALE (Address Latch Enable):
Output pulse for latching the low byte of the address during an access to
external memory. In normal operation, ALE is emitted twice every machine cycle,
and can be used for external timing or clocking. Note that one ALE pulse is skipped
during each access to external data memory. ALE can be disabled by setting SFR
auxiliary.0. With this bit set, ALE will be active only during a MOVX instruction.

EA (External Access Enable/Programming Supply Voltage):
EA must be externally held low to enable the device to fetch code from
external program memory locations. If EA is held high, the device executes from
internal program memory. The value on the EA pin is latched when RST is released
and any subsequent changes have no effect. This pin also receives the programming
supply voltage (VPP) during Flash programming.

RST (Reset):
A high on this pin for two machine cycles while the oscillator is running
resets the device. An internal resistor to VSS permits a power-on reset using only an
external capacitor to VCC.

PSEN (Program Store Enable):
The read strobe to external program memory. When executing code from the
external program memory, PSEN is activated twice each machine cycle, except that
two PSEN activations are skipped during each access to external data memory. PSEN
is not activated during fetches from internal program memory.


3.1.3.2.4 Memory organization
The 8051 has two types of memory and these are Program Memory and Data
Memory. Program Memory (ROM) is used to permanently save the program being
executed, while Data Memory (RAM) is used for temporarily storing data and
intermediate results created and used during the operation of the microcontroller.
Depending on the model in use (we are still talking about the 8051 microcontroller
SMART ENERGY METER
18
family in general) at most a few Kb of ROM and 128 or 256 bytes of RAM is used.
All 8051 microcontrollers have a 16-bit addressing bus and are capable of addressing
64 kb memory. It is neither a mistake nor a big ambition of engineers who were
working on basic core development. It is a matter of smart memory organization
which makes these microcontrollers a real programmers goody.

3.1.3.2.4. a Program memory
The first models of the 8051 microcontroller family did not have internal
program memory. It was added as an external separate chip. These models are
recognizable by their label beginning with 803 (for example 8031 or 8032). All later
models have a few Kbyte ROM embedded. Even though such an amount of memory
is sufficient for writing most of the programs, there are situations when it is necessary
to use additional memory as well. A typical example is so called lookup tables. They
are used in cases when equations describing some processes are too complicated or
when there is no time for solving them. In such cases all necessary estimates and
approximates are executed in advance and the final results are put in the tables
(similar to logarithmic tables).

3.1.3.2.4. b Data memory
Data Memory is used for temporarily storing data and intermediate results
created and used during the operation of the microcontroller. Besides, RAM memory
built in the 8051 family includes many registers such as hardware counters and timers,
input/output ports, serial data buffers etc. The previous models had 256 RAM
locations, while for the later models this number was incremented by additional 128
registers. However, the first 256 memory locations (addresses 0-FFh) are the heart of
memory common to all the models belonging to the 8051 family.

3.1.3.2.5 Registers in 8051
In the CPU, registers are used to store information temporarily. That
information could be a byte of data to be processed, or an address pointing to the data
to be fetched. The vast majority of 8051 registers are 8- bit registers. In the 8051 there
is only one data type: 8 bits. With an 8-bit data type, any data larger than 8 bits must
be broken into 8- bit chunks before it is processed. The most widely used registers of
the 8051 are A(Accumulator), B, and SPF (special function registers) and PSW
(Program Status Word).

A register is a general-purpose register used for storing intermediate results
obtained during operation. Prior to executing an instruction upon any number or
operand it is necessary to store it in the accumulator first. All results obtained from
arithmetical operations performed by the ALU are stored in the accumulator. Data to
be moved from one register to another must go through the accumulator. In other
words, the A register is the most commonly used register and it is impossible to
SMART ENERGY METER
19
imagine a microcontroller without it. More than half instructions used by the 8051
microcontroller use somehow the accumulator. Multiplication and division can be
performed only upon numbers stored in the A and B registers. All other instructions in
the program can use this register as a spare accumulator (A).

3.1.3.2.5. a R Registers (R0-R7)
This is a common name for 8 general-purpose registers (R0, R1, R2 ...R7).
Even though they are not true SFRs, they deserve to be discussed here because of
their purpose. They occupy 4 banks within RAM. Similar to the accumulator, they are
used for temporary storing variables and intermediate results during operation. Which
one of these banks is to be active depends on two bits of the PSW Register. Active
bank is a bank the registers of which are currently used.

3.1.3.2.5. b SFR (Special Function Registers)
Special Function Registers (SFRs) are a sort of control table used for running
and monitoring the operation of the microcontroller. Each of these registers as well as
each bit they include, has its name, address in the scope of RAM and precisely
defined purpose such as timer control, interrupt control, serial communication control
etc. Even though there are 128 memory locations intended to be occupied by them,
the basic core, shared by all types of 8051 microcontrollers, has only 21 such
registers.

3.1.3.2.5.c PROGRAM STATUS WORD (PSW):

CY: Carry out from accumulator MSB of ALU operand
AC: Auxiliary carry for BCD operations
FO: General purpose
RS1 & RS0: For register banks selection ( RB0-RB3)
OV: Overflow flag
P: Parity of accumulator set by hardware to 1 if it contains odd no of 1s




Table 3.1.The contents of (RS1-RS0) enable the working register banks
SMART ENERGY METER
20







Carry flag:
Carry flag is set whenever there is carry out from the MSB. This flag is
after 8bit ADD/SUB operation. It can also be set to 1 or 0 directly using SETB C or
CLR C

Auxiliary carry:
If there is a carry from D3 to D4 position during Add/Sub operation,
this bit will set. Otherwise, it is cleared. This flag is used for BCD operations.
Parity flag reflects the number of 1s in A. If A contains an odd number
of 1s, then P=1. Therefore P=0, if A has an even number of 1s.

Overflow flag:
This flag is set whenever the result of a signed number operation is too
large to be accommodated in 7 bits, causing the higher order bit to overflow into the
sign bit.

3.1.3.2.6 Oscillator:
The microcontroller used in this project, P89C51RD2FN requires a baud rate
of 9600. To acquire this baud rate, an 11.0592 MHz crystal must be connected
between 19
th
and 20
th
pins of controller. The determination of machine cycle
frequency and Baud rate is as follows.
MCF = (XTL freq / 12)
= (11.0592 * 10^6) / 12
= 921.6 KHz

Baud rate = MCF/32
= (921.6 10^3) / 32
= 28800 Hz
RS 1 RS 0 BANKS AND REGISTERS
0 0 BANK 0 (00H-07H)
0 1 BANK 1 (08H0FH)
1 0 BANK 2 (10H-17H)
1 1 BANK 3 (18H-1FH)
SMART ENERGY METER
21

Where MCF = Machine Cycle Frequency,
XTL = Crystal.

To synchronize with timer1 (TH1) to set the baud rate as 9600 we need to set
those register value as -3 (decimal) or FD (Hexadecimal) so as to divide the baud rate
i.e.. 28800Hz should be dividing with the decimal value of TH1 to get 9600 value.


Fig 3.3: Oscillator Connections
C1, C2 = 33pF.


3.1.3.3 FEATURES
80C51 Central Processing Unit
On chip Flash Program Memory with In-System Programming (ISP) and In-
Application Programming
Boot ROM contains low level Flash programming routines for downloading
via the UART
Can be programmed by the end-user application(IAP)
Supports 6-clock/12 clock mode via parallel programmer(default clock mode
after Chip Erase is 12-clock)
Speed up to 20MHz with 6-clock cycles per machine cycle
(40MHz equivalent performance), up to 33MHz with 12 clocks per machine
SMART ENERGY METER
22
cycle
RAM expandable externally to 64Kbytes
Four interrupt priority levels
Seven interrupt sources
Four 8-bit I/O ports
Full-duplex enhanced UART
8-Bit ALU , with 2 registers A & B
11 bit program counter & data pointer
8-Bit program status word
8 bit stack pointer
4registers banks, each containing 8 registers
16bytes , which may be addressed at bit level
80 bytes of general purpose data
Two 16 bit timer/counter T0 & T1

Control registers TCON, TMOD, SCON, PCON and IP & IE oscillator & clock
circuits.

3.1.4 SERIAL COMMUNICATION

3.1.4.1 Introduction
In order to connect microcontroller to a modem or a pc to modem a serial port
is used. Serial is a very common protocol for device communication that is standard
on almost every PC. Most computers include two RS-232 based serial ports. Serial is
also a common communication protocol that is used by many devices for
instrumentation; numerous GPIB-compatible devices also come with an RS232 port.
Furthermore, serial communication can be used for data acquisition in conjunction
with a remote sampling device.
Typically, serial is used to transmit ASCII data. Communication is completed
using 3 transmission lines. (1) Ground, (2) Transmit and (3) Receive. Since serial is
asynchronous, the port is able to transmit data on one line while receiving data on
another. Other lines are available for handshaking, but are not required. The important
serial characteristics are baud rate, data bits, stop bits, and parity. For two ports to
communicate, these parameters much match.
Serial communication is a popular means of transmitting data between a
computer and a peripheral device such as a programmable instrument or even another
one bit at a time, over a single communication line to a receiver. You can use this
method when data transfer rates are low or you must transfer data over long distances.
Serial communication is popular because most computers have one or more serial
ports, so no extra hardware is needed other than a cable to connect the instrument to
the computer or two computers together.
Any device you connect to the serial port will need the serial transmission
converted back to parallel so that it can be used. In serial communication, the data
will be sent from one system to another in bit by bit notation. Serial Ports come in two
sizes, there are the D-Type 25 pin connector and the D-Type 9 Pin connector both
of which are male on the back of the PC, and thus you will require a female connector
on your device. The RS-232 and RS-485 come under serial communication.
SMART ENERGY METER
23


3.1.4.2 Baud Rate:
It is a speed measurement for communication. It indicates the number of bit
transfers per second. For example, 300 baud is 300 bits per second. When a clock
cycle is referred it means the baud rate. For example, if the protocol calls for a 4800
baud rate, then the clock is running at 4800Hz. This means that the serial port is
sampling the data line at 4800Hz. Common baud rates for telephone lines are 12200,
28800 and 33600. Baud rates greater than these are possible, but these rates reduce
the distance by which devices can be separated. These high baud rates are used for
device communication where the devices are located together, as is typically the case
with GPIB devices.

3.1.5 HARDWARE DESIGN OF LCD
The LCD (Liquid Crystal Display) used to display the output to the user in the
form of GUI (Graphic User Interface) and a mono chromatic display. LCD used in
this project is JHD162A series. There are 16 pins in all. They are numbered from left
to right 1 to 16 (if you are reading from the backside). LCD shown above is marked to
indicate which the 1st pin was and which the 16th was.

In our project, we use a JHD162A LCD Display which has 2 rows and 16
characters. It contains internal 1 byte latch. It has a better contrast and a wider
viewing angle. To develop a protocol to interface this LCD with 89C51 first we have
to understand how they functions. These displays contain two internal byte-wide
registers, one for command and second for characters to be displayed. There are three
control signals called R/W, RS and EN. Select By making RS signal 0 you can send
different commands to display. These commands are used to initialize LCD, to
display pattern, to shift cursor or screen etc. You can see the markings right next to
1st and 16th pins. The 16by2 LCD with connections is as given below

SMART ENERGY METER
24

Fig 3.4: Pin configuration of LCD

3.1.5.1 LCD screen:-
LCD screen consists of two lines with 16 characters each. Each character
consists of 5*7 dot matrix. Contrast on display depends on the power supply voltage
and whether messages are displayed in one or two lines. For that reason, variable
voltage 0-Vdd is applied on pin marked as V
EE
. Trimmer potentiometer is usually
used for that purpose. Some versions of displays have built in backlight (blue or green
diodes). When used during operating, a resistor for current limitation should be used
(like with any LE diode)


The main control pins on JHD162A are data lines, read or write and enable.

LCD is finding wide spread use replacing LEDs (seven segment LEDs or
other multi segment LEDs) because of the following reasons:
1. The ability to display numbers, characters and graphics. This is in contrast to
LEDs, which are limited to numbers and a few characters.
2. Incorporation of a refreshing controller into the LCD, thereby relieving the
CPU of the task of refreshing the LCD. In contrast, the LED must be refreshed
by the CPU to keep displaying the data.
3. Ease of programming for characters and graphics.
4. These components are specialized for being used with the microcontrollers,
which means that they cannot be activated by standard IC circuits. They are
used for writing different messages on a miniature LCD.

SMART ENERGY METER
25

Fig 3.5: LCD Display




3.1.5.1. a Data lines (D0-D7):
The data lines are connected to the parallel port of the microcontroller. While
connecting the data lines to port0 no pull up resistors are required. These data lines
are used to pass the data from CPU i.e. controller to LCD internal memory and to pass
commands from LCD to CPU. Pin 7 is the Least Significant Bit (LSB) and pin 14 is
the Most Significant Bit (MSB) of the data inputs. If you want to display some
number or letter on the display, you have to input the appropriate codes for that
character on these pins. These pins are also used for giving certain commands to the
display like clearing the display or moving the cursor to a different location. Upon
giving the correct signals to the 3 control pins, the character codes or the commands
that you have given to the Data pins will be written to the display or executed by the
LCD respectively. To make it easier to give the appropriate inputs to these pin, i
recommend wiring up a DIP switch to these pins.


3.1.5.1. b Read and write:
Generally, we always use the LCD to show things on the screen. However, in
some rare cases, we may need to read from the LCD what it is displaying. In such
cases, the R/W pin is used. However, this function is beyond the scope of post and
will not be explained. For all practical purposes, the R/W pin has to be permanently
connected to GND.




The timing diagram for write and read operation of JHD162A is as follows









Write operation:
SMART ENERGY METER
26


Fig 3.6: Timing diagram of write operation in LCD.


Read operation:

Fig 3.7: Timing diagram of read operation in LCD.


3.1.5.1. c Enable Pin:
The enable pin has a very simple function. It is just the clock input for the
LCD. The instruction or the character data at the data pins (D0-D7) is processed by
the LCD on the falling edge of this pin. The Enable pin should be normally held at
Vcc by a pull up resistor. When a momentary button switch is pressed, the Pin goes
low and back to high again when you leave the switch. Your instruction or character
will be executed on the falling edge of the pulse. (i.e. the moment the switch closes).

3.1.5.1. d Reset pin:
The LCD has basically two operating modes: Instruction mode and Character
Mode. Depending on the status of this pin, the data on the 8 data pins (D0-D7) is
treated as either an instruction or as character data. You have to activate the command
mode if you want to give an Instruction to the LCD. Example Clear the display,
Move cursor to home etc. You have to activate the character mode if you want to
tell the LCD to display some character. To set the LCD in Instruction mode, you set
SMART ENERGY METER
27
the 4th pin of the LCD (R/S) to GND. To put it in character mode, you connect it to
Vcc.

3.1.5.2 Features
RS232 compatible serial interface (2400 & 9600 Baud Selectable)
Externally selectable serial polarities (Inverted & Non-Inverted)
Serially controllable contrast and backlight levels
8 user programmable custom characters
16 Byte serial receive buffer

3.1.5.3 Pin Configuration:
There are pins along one side of the small printed board used for connection to
the microcontroller. There are total of 16 pins marked with numbers .Their function is
described in the table below:
Table 3.2 Pin Connections Description
Pins 1 8
Description
Pins 9 -16
Description
Pin1
Ground Pin9
D2 (Not Used in
4bit operation)
Pin2 VCC (+5) Pin10
D3 (Not Used in
4bit operation)
Pin3 Contrast Pin11 D4
Pin4
Data/Comman
d (R/S)
Pin12 D5
Pin5
Read/Write
(W)
Pin13 D6
Pin6 Enable (E1) Pin14 D7
Pin7
D0 (Not Used
in 4bit
operation)
Pin15
VCC
(LEDSV+)
Pin8
D1 (Not Used
in 4bit
operation)
Pin16 Ground
SMART ENERGY METER
28

3.1.5.4 SPECIFICATIONS:
Number of Characters: 16 characters x 2 Lines
Character Table: English-European (RS in Datasheet)
Module dimension: 80.0mm x 36.0mm x 13.2mm(MAX)
View area: 66.0 x 16.0 mm
Active area: 56.2 x 11.5 mm
Dot size: 0.56 x 0.66 mm
Dot pitch: 0.60 x 0.70 mm
Character size: 2.96 x 5.46 mm
Character pitch: 3.55 x 5.94 mm
LCD type: STN, Positive, Yellow/Green
Duty: 1/16
View direction: Wide viewing angle
































To start with LCD the user should initialize it first which should be
programmed with its LCD commands. The LCD commands are given

SMART ENERGY METER
29



Table 3.3 Commands for LCD


CODE COMMANDS TO THE LCD
1 Clear display screen
2 Return home
4 Shift cursor to left
5 Shift display right
6 Shift cursor to right
7 Shift display left
8 Display off, cursor off
A Display off, cursor on
C Display on, cursor off
E Display on, cursor blinking
F Display off, cursor blinking
10 Shift cursor position to left
14 Shift cursor position to right
18 Shift entire display left
1c Shift entire display right
80 Force cursor to begin in 1
st
row
C0 Force cursor to begin in 2
nd
row
38 2 lines &5x7 matrix





SMART ENERGY METER
30


Fig 3.8: LCD Interface with P89C51RD2XX
3.1.5.5 Functionality of LCD in this project:
LCD is used to display any message, like authentication.
It displays the menu of operation, which contains two options automatic and
settings.
It displays the amount of power utilized and price for the relevant consumed
power.
It displays the user to send the data to HyperTerminal.


3.1.6 MAX 232:

Max232 IC is a specialized circuit which makes standard voltages as
required by RS232 standards. This IC provides best noise rejection and very reliable
against discharges and short circuits. MAX232 IC chips are commonly referred to as
line drivers.
To ensure data transfer between PC and microcontroller, the baud rate and
voltage levels of Microcontroller and PC should be the same. The voltage levels of
microcontroller are logic1 and logic 0 i.e., logic 1 is +5V and logic 0 is 0V. But for
PC, RS232 voltage levels are considered and they are: logic 1 is taken as -3V to -25V
and logic 0 as +3V to +25V. So, in order to equal these voltage levels, MAX232 IC is
used. Thus this IC converts RS232 voltage levels to microcontroller voltage levels
and vice versa.



SMART ENERGY METER
31
3.1.6.1 Pin Configuration:





Fig 3.9: Pin diagram of MAX 232 IC


3.1.7 RS 232(Female Port)
RS-232 is the component which is used to connect system (pc) to
microcontroller.
RS-232 (Recommended Standard 232) is the traditional name for a series of
standards for serial binary single-ended data and control signals connecting between a
DTE (Data Terminal Equipment) and a DCE (Data Circuit- terminating Equipment).
It is commonly used in computer serial ports. The standard defines the electrical
characteristics and timing of signals, the meaning of signals, and the physical size and
pinout of connectors.
RS232 is limited to point-to-point connections between PC serial ports and
devices. RS 232 hardware can be used for serial communication up to distances of 50
feet.

3.1.7.1 Voltage levels:
The RS-232 standard defines the voltage levels that correspond to logical one
and logical zero levels for the data transmission and the control signal lines.
For data transmission lines (TxD, RxD and their secondary channel
equivalents) logic one is defined as a negative voltage, the signal condition is called
marking, and has the functional significance. Logic zero is positive and the signal
condition is termed spacing.




Table 3.4: indicating voltage levels for DB 9 connector
SMART ENERGY METER
32
Logic level Voltage level
1 -10V
0 10V

3.1.7.2 PIN CONFIGURATION

Fig 3.10: DB9 Connector with pinout

3.1.7.3 DB9 INTERFACING WITH MICROCONTROLLER USING MAX 232:

Fig 3.11: DB9 interfacing with microcontroller using MAX 232



SMART ENERGY METER
33
3.1.8 Serial port connector:
The microcontroller is connected to the pc via a serial communication port.
The serial communication port is a combination of a female port and a male port. The
male port is connected to the DB-9 connector connected to the microcontroller while
the female port is connected to the serial port of the pc.

Fig 3.12: serial port connector



3.1.9 Design of keypad
The keypad used in this project is AT91. A 4x4 matrix keypad requiring eight
Input/output ports for interfacing is used. Rows are connected to Peripheral
Input/output (PIO) pins configured as output. Columns are connected to PIO pins
configured as input with interrupts.



Fig 3.13: 4x4 matrix Keypad






SMART ENERGY METER
34



The internal structure of keypad is as follows:



Fig 3.14: Internal structure of keypad

I/O configuration: Rows are connected to four PIO pins configured as
outputs. Columns are connected to four PIO pins configured as inputs with interrupts.
The idle state of these pins is high level due to four pull-up resistors. PIO interrupt is
generated by a low level applied to these pins (caused by a key pressed). Four
additional PIO pins are configured as outputs to send the value of the pressed key to
LEDS.

Timer Counter Configuration: The Timer Counter is configured in
waveform operating mode with RC compare interrupt. The Timer Counter is
initialized to be incremented on internal clock cycles. The debouncing time is
programmable by initializing the RC compare register value according to the clock
source selected. A software trigger is used to reset the timer counter and start the
counter clock.

Interrupt: When a key is pressed, a low level is applied to the pin
corresponding to the column associated to the key (pins configured as inputs with
SMART ENERGY METER
35
interrupts). A falling edge applied to a column pin creates a PIO interrupt. Then, the
processor executes the PIO interrupt subroutine (debouncing) and comes back to its
previous state (in the main program). After debouncing time, a RC compare timer
interrupt occurs and the processor then executes the timer interrupt subroutine
(decoding the pressed key) and comes back to its previous state (in the main
program).

Keyboard Operating Sequence
To detect a pressed key, the Microcontroller grounds all rows by
providing 0 to the output latch, and then it reads the columns. If the data read from
the columns isD3- D0=1111 no key has been pressed and the process is continued
until a key is detected. However if one of the columns bits is zero this means that a
key press has occur. For example if D2-D0=1101 this means that a key in D1 column
has been pressed after a key press is detected, the microcontroller will go through
the process of identifying the key. Starting with the top row, the microcontroller
grounds it by providing a low to row D0 only then it reads the columns. If the data
read is all once, no key in that row is achieved and the process is moved to the next
row. It ground the next row reads the column and checks for any zero. This process
continues until the row is identified. After identification of the row in which the key
has been press the next task is to find out which column the pressed key belongs to.
This should be easy since the micro control knows at any time which the row and
column are being accessed.


3.1.10 IR sensors and IC NE555 Timer:

The pair of IR sensors generally constitute of a photo transmitter and a photo
receiver. The photo transmitter generally a photo diode emits IR rays while the
receiver receives the IR rays. Whenever the transmission is blocked the sensor unit
sends a interrupt signal to the microcontroller which then increments the counter.

3.1.10.1 Photo transmitter:
The photo transmitters are IR LEDs or photo diodes used to emit light.
IR LEDs are just like LEDs which emits IR rays. Since the IR rays are out of the
visible range we cannot observe the rays from the transmitter. A photodiode is a type
of photo-detector capable of converting light into either current or voltage, depending
upon the mode of operation.
Photodiodes are similar to regular semiconductor diodes except that they may
be either exposed (to detect vacuum UV or X-rays) or packaged with a window or
optical fibre connection to allow light to reach the sensitive part of the device. Many
diodes designed for use specifically as a photodiode will also use a PIN junction
rather than the typical PN junction.

3.1.10.2 Principle of Operation:
A photodiode is a PN junction or PIN structure. When a photon of sufficient
energy strikes the diode, it excites an electron thereby creating a mobile electron and a
SMART ENERGY METER
36
positively charged electron hole. If the absorption occurs in the junction's depletion
region, or one diffusion length away from it, these carriers are swept from the junction
by the built-in field of the depletion region. Thus holes move toward the anode, and
electrons toward the cathode, and a photocurrent is produced.

3.1.10.2. a Design parameters
1. Transistor
2. TCRT5000 IR transmitter
3. TCRT5000 IR receiver
4. 100ohms , 220ohms resistor (near transmitter)
5. 22ohms,4.7ohms resister (near receiver)



Fig 3.15: IR Transmitter Circuit diagram




Fig 3.16: IR Receiver Circuit diagram

SMART ENERGY METER
37
3.1.10.3 Applications:
Photo diodes are used in
Consumer electronic devices such as compact disc players, smoke
detectors, and the receivers for remote controls in VCRs and television.
Accurate measurement of light intensity.
Detectors for computed tomography (coupled with scintillators) or
instruments to analyze samples (immunoassay), pulse oximeters.
Optical communications and in lighting regulation.
Astronomy, spectroscopy, night vision equipment and laser range finding.

3.1.10.4 FEATURES:
= 940 nm
Chip material =GaAs with AlGaAs window
Medium Emission Angle, 40
High Output Power
Package material and color: Clear, untinted, plastic
Ideal for remote control applications

3.1.10.5 IR Receiver:
IR receiver is used to receive the signals transmitted by the IR transmitter.IR
receiver is similar to a N-P-N transistor. It is a three terminal device but looks like a
two terminal device a base is connected internally. It is a nothing but a
phototransistor.


Fig 3.17: IR receiver
3.1.10.6 Phototransistors:
Phototransistors also consist of a photodiode with internal gain. A
phototransistor is in essence nothing more than a bipolar transistor that is encased in a
transparent case so that light can reach the base-collector junction.


3.1.10.7 Principle of Operation:
The electrons that are generated by photons in the base-collector junction are
injected into the base, and this current is amplified by the transistor operation. Note
that although phototransistors have a higher responsiveness for light they are unable
to detect low levels of light any better than photodiodes. Phototransistors also have
slower response times.

SMART ENERGY METER
38
3.1.11 IC NE555 TIMER:
The 555 timer IC is an integrated circuit used in a variety of timer, pulse
generation and oscillator applications. The full part numbers were NE555
(commercial temperature range, 0 C to +70 C). It has been hypothesized that the
555 got its name from the three 5 k resistors used internally.
Depending on the manufacturer, the standard 555 package includes over 20
transistors, 2 diodes and 15 resistors on a silicon chip installed in an 8-pin mini dual-
in-line package (DIP-8).

Fig 3.18: 555 Timer
The 555 has three operating modes:

3.1.11.1 Monostable mode:
In this mode, the 555 timer functions as a "one-shot" pulse generator.
Applications include timers, missing pulse detection, bounce free switches, touch
switches, frequency divider, capacitance measurement, pulse-width modulation
(PWM) and so on.

3.1.11.2 Astable mode:
Free running mode: the 555 can operate as an oscillator. Uses include LED
and lamp flashers, pulse generation, logic clocks, tone generation, security alarms,
pulse position modulation and so on. Selecting a NTC as timing resistor allows the
use of the 555 in a temperature sensor: the period of the output pulse is determined by
the temperature. The use of a microprocessor based circuit can then convert the pulse
period to temperature, linearize it and even provide calibration means.

3.1.11.3 Bistable mode or Schmitt trigger:
The 555 can operate as a flip-flop, if the DIS pin is not connected and no
capacitor is used. Uses include bounce free latched switches.


3.1.11.4 Features of NE555 Timer:
Timing is from microseconds through hours
O/p is compatible with CMOS, DTL and TTL
High Temperature Stability
Duty cycle is Adjustable
Mono-stable and Astable operations


3.1.11.5 Specifications of NE555Timer:
SMART ENERGY METER
39
Supply voltage V
CC
4.5 to 15V
Supply current (V
CC
=+5V) 3 to 6mA
Maximum O/P Current 200mA
Power Dissipation 600mA
Power consumption (minimum operating) 30mW@ 5V,225mW@15V
Operating temperature 0 to 70 C

3.1.12 Resistors:
A resistor is a two-terminal passive electronic component that implements
electrical resistance as a circuit element. When a voltage V is applied across the
terminals of a resistor, a current I will flow through the resistor in direct proportion to
that voltage. This constant of proportionality is called conductance, G. The reciprocal
of the conductance is known as the resistance R, since, with a given voltage V, a
larger value of R further "resists" the flow of current I as given by Ohm's law:




Fig 3.19: Resistors
Practical resistors can be made of various compounds and films, as well as
resistance wire (wire made of a high-resistivity alloy, such as nickel-chrome).
Resistors are also implemented within integrated circuits, particularly analog devices,
and can also be integrated into hybrid and printed circuits.

3.1.13 Capacitors:
A capacitor (formerly known as condenser) is a device for storing electric
charge. The forms of practical capacitors vary widely, but all contain at least two
conductors separated by a non-conductor. Capacitors used as parts of electrical
systems, for example, consist of metal foils separated by a layer of insulating film.
SMART ENERGY METER
40
A capacitor is a passive electronic component consisting of a pair of
conductors separated by a dielectric (insulator). When there is a potential difference
(voltage) across the conductors, a static electric field develops across the dielectric,
causing positive charge to collect on one plate and negative charge on the other plate.
Energy is stored in the electrostatic field. An ideal capacitor is characterized by a
single constant value, capacitance, measured in farads. This is the ratio of the electric
charge on each conductor to the potential difference between them.

Fig 3.20: capacitors
Capacitors are widely used in electronic circuits for blocking direct current
while allowing alternating current to pass, in filter networks, for smoothing the output
of power supplies, in the resonant circuits that tune radios to particular frequencies
and for many other purposes.
The capacitor is a reasonably general model for electric fields within electric
circuits. An ideal capacitor is wholly characterized by a constant capacitance C,
defined as the ratio of charge Q on each conductor to the voltage V between them:

3.1.14 Crystal oscillator:
A crystal oscillator is an electronic oscillator circuit that uses the mechanical
resonance of a vibrating crystal of piezoelectric material to create an electrical signal
with a very precise frequency. This frequency is commonly used to keep track of time
(as in quartz wristwatches), to provide a stable clock signal for digital integrated
circuits, and to stabilize frequencies for radio transmitters and receivers. The most
common type of piezoelectric resonator used is the quartz crystal, so oscillator circuits
designed around them became known as "crystal oscillators."
SMART ENERGY METER
41

Fig 3.21: crystal oscillator
Quartz crystals are manufactured for frequencies from a few tens of kilohertz
to tens of megahertz. More than two billion (210
9
) crystals are manufactured
annually. Most are used for consumer devices such as wristwatches, clocks, radios,
computers, and cell phones. Quartz crystals are also found inside test and
measurement equipment, such as counters, signal generators, and oscilloscopes.

3.2 Software design:
3.2.1 Liquid Crystal Display
3.2.1.1 Initializing the LCD
Before you using the LCD, the program must initialize and configure it. This
is accomplished by sending a number of initialization instructions to the LCD.
The first instruction to send is the no of data for the LCD i.e., with an 8-bit or
4-bit data bus. The other thing need to specify is display matrix; in the selected LCD
it is a 5x8 dot character font. These two options are selected by sending the command
38h to the LCD as a command. The command can give to the LCD by invoking the
pre defined function call lcdcmd with passing parameters value of 38H, the syntax for
the same can be given like lcdcmd (0x38).

3.2.1.2 Checking the busy status of the LCD
3.2.1.2.1 Busy Flag (BF):
When the busy flag is high or 1 the module is performing an internal
operation and the next instruction will not be accepted. The RS=0 is used to check the
Busy flag bit too see if the LCD is ready to receive information. The Busy flag is D7
and can be read when R/W = 1 and RS = 0, as follows: if R/W = 1, RS= 0.When
D7=1 (busy flag), the LCD is busy taking care of internal operations and will not
accept any new information. When D7=0, the LCD is ready to receive new
information.




SMART ENERGY METER
42


3.2.1.2.1.1 Busy flag flowchart

Fig 3.22: Busy flag flowchart

3.2.1.2.2.1 Writing command to the Display
To give a command to perform some special functions like move to position,
clear LCD ,blink the curser etc. the instruction sequence must follow like first
instruction must be set in the data bus set RS signal to logic 0 and enabling the LCD
will receive the data . After finishing the instruction sequence the application must
wait till the LCD completes the instruction by checking the LCD Busy status.






3.2.1.2.2.2 Writing command display flow chart
SMART ENERGY METER
43

Fig 3.23: Writing command display flow chart
1. Check the Busy flag bit
2. Set the instruction in data lines (if it is writing)
3. Set RS bit to logic 1 to 0
4. Set R/W bit is to low
6. Set En line to high
7. Set line to low

3.2.1.2.4.1 Displaying the data in to the LCD
Writing the string in the LCD, to get the result first the address at which the
string has to display on the screen is given as command followed by displaying the
individual characters as LCD data .That finishes the data to be display in the LCD.









The complete flow chart representation of LCD working process is as follows:
SMART ENERGY METER
44























Fig 3.24: Flow chart for the LCD function.


3.2.2 KEYPAD:
Start
RS=0
E=1
Delay
E=0
LCD
Busy

RS=0
E=1
Delay
P0=command
LCD
Busy
SMART ENERGY METER
45
3.2.2.1 FLOW CHART OF KEY BOARD SCANNING ALGORITHM


Fig 3.25: Flow Chart of Key Board Scanning Algorithm

SMART ENERGY METER
46

COMPLETE FLOW CHART OF SMART ENERGY METER



SMART ENERGY METER
47








CHAPTER - 4






SMART ENERGY METER
48
CHAPTER 4
IMPLEMENTATION

4.1 HARDWARE IMPLEMENTATION
4.1.1 Complete Schematic of Smart Energy Meter

Fig 4.1: Complete schematic of Smart Energy Meter

SMART ENERGY METER
49

4.1.2 Connections of P89C51RD2FN
The pin configuration of P89C51RD2XX:-


Fig 4.2: Pin diagram of P89C51RD2FN
In this project the microcontroller is connected to MAX232, LCD, Keypad, sensors.
The connections of microcontroller are given briefly below:
Pin1 to pin8 (Port 0) of controller are connected to the data lines of keypad
(D0-D8).
The reset pin is connected to the 9
th
pin (RST) of P89C51RD2FN, as it is used
for set reset the program.
While the 10pin is connected to the 12
th
pin of MAX232.
11
th
pin of controller is connected to the 11
th
pin of MAX232.
The interrupt given by the IR sensors from the 555IC timer should be
connected to the 12
th
pin i.e. INTO pin of controller.
13
th
pin is used as an external interrupt, but here in this project there is no use
with this pin.
The crystal oscillator which gives a frequency of 11.0592 MHz for the
required Baud rate of 9600Hz to the microcontroller. This crystal oscillator is
SMART ENERGY METER
50
connected in between 18
th
(XALT 1) and 19
th
(XALT 2) pins of
P89C51RD2FN controller.
The 20
th
pin of controller is grounded.
The pins from 21
st
to 28
th
(port 2 data lines) are used for the external
peripheral connections.
The 29
th
pin is connected to an on-off switch so as to dump and execute the
program. Whenever the PSEN pin is connected to ground then we can execute
the last dumped program, likewise when 29
th
pin is connected to VCC then
code can be dumped into the controller.
Address Latch Enable pin (30
th
pin) of controller is connected to the ground
hence no connections need not to be given to this pin.
External Access Enable or programming supply voltage should be latched
when RST is released and any subsequent changes have no effect. This pin
also receives the programming supply voltage (VPP) during Flash
programming. Hence the pin 31
st
must be connected to high i.e. VCC.
Port0 (pins 32 to 39) are connected to LCD in this project. But these should be
connected to other peripherals through pull up resistors.

4.1.3 Pin connections of LCD
The LCD used for output display is JHD162A series. The detailed connections
of LCD is described briefly as

The 1
st
and 2
nd
pins of JHD162A LCD are connected to ground and high
voltage VCC respectively.
3
rd
pin of LCD is connected to the centre pin of the potentiometer or variable
resistor so as to adjust the contrast of LCD.
The 4
th
, 5
th
, 6
th
pins are connected to 26
th
(P 2.5), 27
th
(P 2.6), 28
th
(P 2.7) pins
of the microcontroller respectively.
The 7
th
to 14
th
pins are data pins and are connected to the 39
th
(P 0.0) to 32
nd

(P 0.7) pins of the microcontroller respectively.
The 15
th
and 16
th
pins are used for backlight purpose. 15
th
pin is connected to
V
CC
and 16
th
pin to ground.


SMART ENERGY METER
51


Fig 4.3: connection of LCD with P89C51RD2FN.

4.1.4 KEYPAD CONNECTIONS:
The keypad used is 4*4 keypad
The pins 1, 2, 3, 4 which are connected to columns of the keypad are
connected to 1, 2, 3, 4(P1.0 to P1.3) pins of the microcontroller
respectively.
The pins 5, 6, 7, 8 which are connected to rows of the keypad are
connected to 5, 6, 7, 8(P1.4 to P1.7) pins of the microcontroller
respectively.

4.1.5 MAX232 AND DB9 CONNECTION:
MAX232 and DB9 connector plays a key role in program dumping and
communication between project kit to the PC host.
Capacitor C10 of capacitance 1Uf is connected across 1
st
and 3
rd
pins of
MAX232 and C9 of capacitance 1Uf is connected in between 4
th
and 5
th
pins.
Charge pump capacitors are required for the MAX232 to work it as voltage
level shifter. The charge pump capacitors used here are C7 and C8 whose
capacitance is 1Uf. C7 is connected between 6
th
pin and ground, while C8 is
connected across 2
nd
pin of MAX232 and Vcc.
12
th
and 11
th
pins of MAX232 are connected to the 10
th
and 11
th
pins of
P89C51RD2FN controller respectively. These acts as a transmitter and
receiver for the data flow.
To connect the MAX232 to the PC host we require a medium named as DB9
connector. The 2
nd
and 3
rd
pin of the DB9 connector should be connected to
the 14
th
and 13
th
pins of MAX232 respectively. While the 5
th
pin is grounded.
SMART ENERGY METER
52

4.1.6 IC555 TIMER and IR transmitter connections:
The sensor is designed using a 555 timer, a IR transmitter and a IR
receiver.
The 555 timer is operated in astable mode of operation.
The 1
st
pin is grounded.
The 2
nd
pin and 6
th
pin are shorted, 2
nd
pin is connected to V
CC
through
the 10K and 220K pot, IR receiver is connected to 2
nd
pin in reverse
bias.
The pin 3 of 555 timer is an output pin which is connected to the 12
th

pin (P 3.2) of the microcontroller.
The 4
th
pin and 8
th
pin are shorted, 8
th
pin is connected to V
CC
and
0.1f capacitor is connected between 8
th
pin and ground.
The 5
th
pin is grounded through 0.01f capacitor.
The IR transmitter is connected between V
CC
and ground through 270
ohm resistor. It is connected in forward bias.
If there is obstruction between transmitter and receiver, the receiver
output gives 3V to 5V.
Whenever there is an obstruction of current between transmitter and
receiver, the current passed to receiver decreases and hence the voltage
across voltage divider decreases. As a result a short pulse is applied to
the port pin of the 8051 microcontroller. On receiving a pulse from the
sensor circuit, the controller increments the counter which indicates the
consumption of electricity.
The IR sensor implementation using 555 timer is shown in figure below:


Fig 4.4: connection of IR sensors with 555 timers.






SMART ENERGY METER
53















CHAPTER - 5










SMART ENERGY METER
54
CHAPTER-5
SOFTWARE IMPLEMENTATION

This chapter explores some real world applications of the
P89C51RD2xx, and also includes how to interface the P89C51RD2xx to
devices such as an LCD and a keyboard and its software functionality
using embedded C language.

5.1 JHD162A LCD INTERFACING
5.1.1Initializing the LCD
Before you using the LCD, the program must initialize and configure it. This
is accomplished by sending a number of initialization instructions to the LCD.
The first instruction to send is the no of data for the LCD i.e., with an 8-bit or
4-bit data bus. The other thing need to specify is display matrix; in the selected LCD
it is a 5x8 dot character font. These two options are selected by sending the command
38h to the LCD as a command. The command can give to the LCD by invoking the
pre defined function call lcdcmd with passing parameters value of 38H ,the syntax for
the same can be given like lcdcmd(0x38).

5.1.2 The initialization sequence code can be given as follows:


lcdcmd(0x38); // 2 lines and 5x7 matrix
lcdcmd(0xC0); // force cursor to begging of 2
nd
line
lcdcmd(0x0E); // display on, cursor blinking
lcdcmd(0x01); //clear display screen
lcdcmd(0x06); // increment cursor (shift cursor right)
lcdcmd(0x80); // force cursor to begging of 1
st
line



5.1.3 Checking the busy status of the LCD
Busy Flag (BF):
void lcdready(void)
{
busy=1;
rs=0; //Register select command
rw=1;
while(busy==1) // if Bit (D7) high, LCD still busy
{
en=0; // Finish the command
MSDelay(1);
en=1; // Start LCD command
SMART ENERGY METER
55
}
}
5.1.4 Writing command to the Display
void lcdcmd (unsigned char value) // LCD command initiation routine
{
Lcdready(); // wait till the LCD executes the instruction
ldata=value; // Set the value(instruction) in Data bus
rs=0; // register select as command
rw=0;
en=1; // set the enable command
MSDelay(1);
en=0; // Reset the enable command
}

5.1.5 Writing Data to Display
void lcddata (unsigned char value) // LCD data placing routine
{
lcdready(); // wait till the LCD executes the instruction
ldata = value; // Set the value(Data) in Data bus
rs=1; //register select as data
rw=0; //read command
en=1; // Send Enable Signal to LCD
MSDelay(1); // This Function Gives Approximate Delay required For LCD
Initialization

en=0; //Reset the Enable Command
}
5.1.6 Displaying the data in to the LCD
void WriteString(unsigned char count,unsigned char *MSG)
{
unsigned char i;
for(i=0;i<count;i++)
{
lcddata(MSG[i]); //Display Character on LCD at Proper Location
}
}

5.1.7 4X4 MATRIX KEYPAD INTERFACING
// key Board variables
sbit r0=P1^0; // keypad rows
sbit r1=P1^1;
sbit r2=P1^2;
sbit r3=P1^3;

sbit c0=P1^4; //keypad columns
sbit c1=P1^5;
sbit c2=P1^6;
sbit c3=P1^7;

SMART ENERGY METER
56
unsigned char KeyTest(void)
{
P1=0xF0;
while (1)
{
while(P1!=0xF0)
{
r0=0; r1=1;r2=1;r3=1;
if(c0==0)
return '1';
else if(c1==0)
return '4';
else if(c2==0)
return '7';
else if(c3==0)
return 'E';
r1=0; r0=1;r2=1;r3=1;
if(c0==0)
return '2';
else if(c1==0)
return '5';
else if(c2==0)
return '8';
else if(c3==0)
return '0';
r2=0; r0=1;r1=1;r3=1;
if(c0==0)
return '3';
else if(c1==0)
return '6';
else if(c2==0)
return '9';
else if(c3==0)
return 'F'; // Down Arrow
r3=0; r0=1;r1=1;r2=1;
if(c0==0)
return 'A';
else if(c1==0)
return 'B';
else if(c2==0)
return 'C'; // Redail
else if(c3==0)
return 'D'; // Enter
} } }

5.1.8 SENSORS:

sbit sense=P3^2; //energy meter

void _Up() interrupt 0
SMART ENERGY METER
57
{
Flag=sense;
if(Flag==1)
{
Count++;
Flag=0;
}
}


















SMART ENERGY METER
58








CHAPTER - 6





Chapter 6
SMART ENERGY METER
59
DEBUGGING TECHNIQUES

6.1 Keil uvision Debugger
6.1.1 Introduction to Keil IDE
Keil is a compiler that has 3 windows, project window, edit window,
and build or command window Schematic. Today, Keil Software provides a broad
range of development tools for the embedded systems marketplace. Their products
include ANSIC compilers, macro assemblers, debuggers, linkers, library managers,
and real-time operating systems.
. It was then that Keil Software implemented the first C compiler designed
from the ground-up specifically for the 89C51 microcontroller.

6.1.2 Features
1. Nine basic data types, including 32-bit IEEE floating-point
2. Flexible variable allocation with bit, data, bdata, idata, xdata, and pdata
memory types
3. Interrupt functions may be written in C
4. Full use of the 8051 register banks
5. Complete symbol and type information for source-level debugging
6. Bit-addressable data objects
7. Built-in interface for the RTX51 real-time kernel
8. Support for dual data pointers on Atmel, AMD, Cypress, Dallas
semiconductor, Infineon, Philips, and Transcend microcontrollers
9. Support for Phillips 8xC510,8xC71,and 8xC752 limited instruction sets
10. Support for the Phillips 80C51 arithmetic unit.



The Keil 8051 Development Tools are designed to solve the complex problems
facing embedded software developers.
When starting a new project, simply select the microcontroller you use from the
Device Database and the vision IDE sets all compiler, assembler, linker, and
memory options for you.
Numerous example programs are included to help you get started with most
popular embedded 8051 devices.
The Keil Vision Debugger accurately simulates on-chip peripherals (CAN,
UART, SPI, Interrupts, I/O Ports, A/D Convertor, D/A convertor, and PWM
Modules) of your 8051 device. Simulation helps you understand hardware
configurations and avoids time wasted on setup problems. Additionally, with
SMART ENERGY METER
60
simulation, you can write and test applications before target hardware is
available.
When you are ready to begin testing your software application with target
hardware, use the MON51, MONADI, or FlashMON51 Target Monitors, the
ISD51 In-system Debugger, or the ULINK USB-JTAG Adapter to download
and test program code on your target system.


6.1.3 Steps to follow while writing a program in keil:
1. Install Keil Micro Vision in your PC, Then after Click on that Keil UVision icon.
After opening the window go to toolbar and select Project Tab then close previous
project.
2. Next select New Project from Project Tab.
3. Then it will open Create New Project window. Select the path where you want to
save project and edit project name.
4. Next it opens Select Device for Target window, it shows list of companies and
here you can select the device manufacturer company.
5. For an example, for your project purpose you can select the chip as 89c51rd2xx
from Philips Group. Next Click OK Button, it appears empty window here you can
observe left side a small window i.e., Project Window. Next create a new file.
6. From the Main tool bar Menu select File Tab and go to New, then it will open a
window, there you can edit the program.
7. Here you can edit the program as which language will you prefer either Assembly
or C.
8. After editing the program save the file with extension as .c or .asm, if you write
a program in Assembly Language save as .asm or if you write a program in C
Language save as .c in the selected path.
9. Then after saving the file, compile the program. For compilation go to project
window select source group and right click on that and go to Add files to
Group.
10. Here it will ask which file has to add. For an example here you can add test.c as
you saved before
11. After adding the file, again go to Project Window and right click on your c file
then select Build target for compilation. If there is any Errors or Warnings in
your program you can check in Output Window that is shown bottom of the Keil
window.
12. Here in this step you can observe the output window for errors and warnings
13. If you make any mistake in your program you can check in this slide for which
error and where the error is by clicking on that error
SMART ENERGY METER
61
14. After compilation then next go to Debug Session. In Tool Bar menu go to
Debug tab and select Start/Stop Debug Session.
15. Write a program for Leds Blinking. LEDS are connected to PORT-1. you can
observe the output in that port.
16. To see the Ports and other Peripheral Features go to main toolbar menu and select
peripherals.
17. In this slide see the selected port i.e., PORT-1.
18. Start to trace the program in sequence manner i.e, step by step execution and
observe the output in port window
19. After completion of Debug Session Create an Hex file for Burning the Processor.
Here to create a Hex file goes to project window and right click on Target next
select Option for Target.
20. It appears one window; here in target tab modify the crystal frequency as you
connected to your microcontroller.
21. Next go to Output tab. In that Output tab click on Create HEX File and then
click OK.
22. Finally Once again compile your program. The Created Hex File will appear in
your path folder

6.2 Flash magic
Flash Magic is a PC tool for programming flash based microcontrollers
from NXP using a serial or Ethernet protocol while in the target hardware.

6.2.1 Features
Straightforward and intuitive user interface
Read any section of Flash and save as an Intel Hex file.
Program security bits
Automatic verifying after programming
Five simple steps to erasing and programming a device and setting key options
Fills unused Flash to increase firmware security
Check which Flash blocks are blank or in use with the ability to easily erase
all blocks in use
Reprogram the Boot Vector and Status Byte with the help of confirmation
features that prevent accidentally programming incorrect values.
SMART ENERGY METER
62
Display the contents of Flash in ASCII and Hexadecimal formats
Single-click access to the manual, Flash Magic home page and NXP
Microcontrollers home page
Use high-speed serial communications on devices that support it.
Command Line interface allowing use in IDEs and Batch Files.
Supports half-duplex communications for many devices
Verify Hex Files previously programmed
Control the DTR and RTS RS232 signals to place the device into Boot ROM
and Execute modes automatically (requires hardware support)
Send commands to place the device in Boot loader mode
Powerful, flexible Just In Time Code feature. Write your own JIT Modules to
generate last minute code for programming, for example serial number
generation.
Displays information about the selected Hex File, including the creation and
modification dates, flash memory used, percentage of the current device used
Read the device signature
Build your own Flash Magic based applications using the DLLs for C, C++,
Python
Build your own Flash Magic based applications using .NET languages
(Windows only)

6.3 Null MODEM checking (Hyper Terminal)
Debugging of 8051 application can be very easy if we able to send debug
information to serial port of PC. And its output can be seen on HyperTerminal (in
Windows ) or Minicom ( in Linux ). We can display content of any variable, memory
location etc. We can also print other useful information on serial terminal which could
replicate the flow of the code.

The Microsoft HyperTerminal terminal emulation application can display
messages sent from the serial port of a SDB or hardware platform. You can use these
messages to verify whether the boot loader is on the SDB, to discover problems that
may occur when the SDB boots, and to obtain the name of the SDB for use in the
Platform Builder integrated development environment (IDE).
To configure HyperTerminal for BSPs
1. From the Windows Start menu, choose All Programs, and then
choose Accessories.
SMART ENERGY METER
63
2. Choose Communications, and then choose HyperTerminal.
3. In the Connection Description dialog box, in the Name box, type a name for
the connection to your SDB.
4. From the Icon list, choose an icon to represent your connection, and then
choose OK.
5. In the Connect To dialog box, in the Connect using box, choose the
communications (COM) port on the development workstation through which
you want to receive messages from the SDB.
The COM port that you choose must be the COM port on the development
workstation to which you attach the null modem cable.
6. Choose OK.
7. In the COM<Port Number> Properties dialog box, modify the settings for
your connection so that the settings are correct for your BSP.



6.4 Hardware debugging techniques

In the context of hardware debugging techniques, we are going to observe the
different types of error and checking of the components in the project.

While considering the microcontroller, the voltage level at 30
th
pin must be
1.6V because of the following reason
1. The voltage supply to the kit or mainly processor is 5V.
2. The duty cycle of the microcontroller is 33%
Duty Cycle = T on / (T on+T off)

Where T off = 2* T on
DC = 1/ (1+2)
DC= 0.333
Hence the voltage at 30
th
pin should be product of Duty Cycle and voltage
supply VCC. Therefore the voltage should be 1.6V.

3. The voltage levels at 2
nd
and 6
th
pins of MAX232 should be -10V and
+10V respectively.


CONCLUSION

Since the inception of electricity deregulation and market-driven pricing
throughout the world, utilities have been looking for a means to match consumption
with generation. Smart meters are also believed to be a less costly alternative to
traditional interval or time-of-use meters and are intended to be used on a wide scale
with all customer classes, including residential customers
Supporting Consumers: a) An end to estimate bills, which are a major source of
complaints for many customers b)A tool to help consumers better manage their
energy use - smart meters with a display can provide up to date information on
electricity consumption in the currency of that country and in doing so help people to
SMART ENERGY METER
64
better manage their energy use and reduce their energy bills and carbon emissions .c)
voltage levels, and power events can be tracked and logged across the entire customer
base.
Supports Power Grid: The Ability to remotely turn power on or off to a customer,
read usage information from a meter, detect a service outage, detect the unauthorized
use of electricity, know the maximum amount of electricity that a customer can
demand at any time. It is projected to reduce the staff required to read meter data
across the customer base.
Supports Environment: The billing is through HyperTerminal or GSM, so lot of
paper can be saved .So Cutting of Trees can be avoided . It is believed that billing
customers by time of day will encourage consumers to adjust their consumption habits
to be more responsive to market prices thereby saving the power by which natural
resources are protected.
It is a Greener, Smarter, New era of Energy Use.

RESULTS
Now the most awaited part of the program is final result which can be seen
by the following steps once the kit is ready.
Give 5V Power supply and connect the pc with serial connector to DB9
connector
Now ON the circuit.
We can see on the LCD display WELCOME RMCE SMART ENERGY
METER and press enter (E) in keypad.
The LCD asks for user id and password. Once they are correct, it shows
AUTHENTICATED.
Now main menu is displayed having options:1.Readings
2. Settings
If 1 is pressed the LCD displays initial count value as 0000
When one interrupt is detected, go to readings and then the count
value is incremented.
Then 2 options will be displayed:1.Send 2.Exit
If 1 is pressed, the data i.e. count value and unit price will be
displayed on the PC through HyperTerminal.
Once data is sent, we will get a reply DATA SENT.
If option 2 is pressed i.e. SETTINGS we can change USER ID,
PASSWORD and UNIT PRICE AND PHONE NO. But it can be
changed only by the administrator only.


7. BIBILOGRAPHY:
SMART ENERGY METER
65

Janci Gillespie Mazidi, Muhammad Ali Mazidi, The 8051 micro controller and
embedded systems, PHI Prentice hall India, Eastern Economy Edition,
www.phindia.com.
Kenneth J. Ayala, The 8051 Microcontroller, architecture, Programming and
Applications, Pen ram international publishing Pvt. Ltd. 1996
Arnold S. Berger, Embedded systems design, an introduction to process, tools,
and
Techniques, CMP Books, 2005. www.cmpbooks.com
Yashvant Kanetkar, Let Us C, BPB Publications, 1999 www.bpbpub.com
Dreamtech Software Team, Programming for Embedded systems, WILEY
Publishing,
Inc, 2003.
http://en.wikipedia.org/wiki/Level_s



























SMART ENERGY METER
66
APPENDICES

KEIL MICRO VISION IDE
Keil is a compiler that has 3 windows, project window, edit window, and build or
command window Schematic. Today, Keil Software provides a broad range of
development tools for the embedded systems marketplace. Their products include
ANSIC compilers, macro assemblers, debuggers, linkers, library managers, and real-
time operating systems.
Steps to follow while writing a program in keil:
1. Click on the Keil Vision Icon on Desktop
2. The following fig will appear

3. Click on the Project menu from the title bar
4. Then Click on New Project

SMART ENERGY METER
67
5. Save the Project by typing suitable project name with no extension in u r
own folder sited in either C:\ or D:\


6. Then Click on Save button above.
7. Select the component for u r project. i.e. NXP
8. Click on the + Symbol beside of NXP


SMART ENERGY METER
68
9. Select P89C51RD2XX as shown below


10. Then Click on OK
11. The Following fig will appear

12. Then Click either YES or NOmostly YES.
13. Now your project is ready to USE.
SMART ENERGY METER
69
14. Now double click on the Target1, you would get another option Source
group 1 as shown in next page.

15. Click on the file option from menu bar and select new.



SMART ENERGY METER
70

16. The next screen will be as shown in next page, and just maximize it by
double clicking on its blue boarder.

17. Now start writing program in either in EMBEDDED C or ASM.
18. For a program written in Assembly, then save it with extension . asm
and for EMBEDDED C based program save it with extension .C






SMART ENERGY METER
71
19. Now right click on Source group 1 and click on Add files to Group
Source.



20. Now you will get another window, on which by default EMBEDDED C files will
appear.



21. Now select as per your file extension given while saving the file
SMART ENERGY METER
72
22. Click only one time on option ADD.







23. Now Press function key F7 to compile. Any error will appear if so happen.



24. If the file contains no error, then press Control+F5 simultaneously.

















SMART ENERGY METER
73
25. The new window is as follows


26. Then Click OK.
27. Now click on the Peripherals from menu bar, and check your required port as
shown in fig below.






SMART ENERGY METER
74
28. Drag the port a side and click in the program file.



29. Now keep Pressing function key F11 slowly and observe.
30. You are running your program successfully.



FLASH MAGIC:
Flash Magic is a PC tool for programming flash based microcontrollers from
NXP using a serial or Ethernet protocol while in the target hardware.

The steps for while using Flash Magic

1) Click on the flash magic icon on the desktop.












SMART ENERGY METER
75
2) The below figure will appear


3) Select the device as P89C51RD2XX.


SMART ENERGY METER
76
4) To check whether the device is connected or not. Click on ISP + Read
device signature.



5) Then the device signature will be shown





6) Then by browsing the required HEX file we can dump the code into controller by
pressing START button.





SMART ENERGY METER
77
Setup of HyperTerminal

Go to

1. Start Menu>> Programs >> Accessories >> Communications >> Hyper Terminal
After that HyperTerminal window will open. If it prompt for checking of default
program as shown in fig, then say yes to it.




2. Click Yes
3. Type Connection Name as 8051 (or as per your Choice)









SMART ENERGY METER
78

4. Select COM PORT (1, 2, 3 etc) whichever is available. (NOTE: Very Less USB-
TO Serial Converters as Reliable)
So use Standard Serial Port




5. Do Port Setting as Given Below.




Then Click Apply and OK.



SMART ENERGY METER
79
6. Now you See Bottom Left side It shows Connected.





7. Now burn the Hex File (Given) and Switch on the Circuit after Connecting
Specified Serial Port .You will see output as Follows:




If everything works fine you will see Hello World on the screen. Otherwise check
your setup.


SMART ENERGY METER
80

COMPLETE CODE:
The complete source code for the project entitled as Smart Energy Meter using
Hyper Terminal is given below.

#include <reg51f.h>
sbit r0=P1^0;
sbit r1=P1^1;
sbit r2=P1^2;
sbit r3=P1^3; //rows
sbit c0=P1^4;
sbit c1=P1^5;
sbit c2=P1^6;
sbit c3=P1^7; //columns
sbit sense=P3^2; //energy meter
sfr ldata=0x80;//port 0 address
sbit rs=P2^5;
sbit rw=P2^6;
sbit en=P2^7; //control pins of lcd
sbit busy=P0^7; //busy pin of lcd
void UpdateService(void);
void lcdcmd(unsigned char);
void lcddata(unsigned char);
void lcdready(void);
void MainMenu(void);
void MSDelay(unsigned int);
void WriteString(unsigned char,unsigned char *);
void serialinit(void);
void sertx(unsigned char);
void sendintdata(unsigned int);
void SendString(unsigned char,unsigned char * );
SMART ENERGY METER
81
unsigned char KeyTest(void);
unsigned char key;
unsigned char mode;
void Start(void);
void LCDClear(void);
unsigned char MY_PWD[4]={'1','2','3','4'};
unsigned int Count;
unsigned char Flag;
//void convertanddisplay(unsigned char value);
void _Up() interrupt 0
{
Flag=sense;
if (Flag==1)
{
Count++;
Flag=0;
}
}
void lcdcmd (unsigned char value)
{
lcdready();
ldata=value;
rs=0;
rw=0;
en=1;
MSDelay(1);
en=0;
}
void lcddata (unsigned char value)
SMART ENERGY METER
82
{
lcdready();
ldata=value;
rs=1;
rw=0;
en=1;
MSDelay(1);
en=0;
}
void lcdready(void)
{
busy=1;
rs=0;
rw=1;
while(busy==1)
{
en=0;
MSDelay(1);
en=1;
}
}

void MSDelay(unsigned int Iter)
{
unsigned int i, j;
for(i=0;i<Iter;i++)
{
for(j=0;j<1275;j++);
}
SMART ENERGY METER
83
}
void WriteString(unsigned char count,unsigned char *MSG)
{
unsigned char i;
for(i=0;i<count;i++)
{
lcddata(MSG[i]);
}
}
void serialinit(void)
{
TMOD=0x20;
TH1=0xFD;
SCON=0x50;
TR1=1;
}
void sertx(unsigned char x)
{
SBUF=x;
while(TI==0);
TI=0;
}
void SendString(unsigned char count,unsigned char *DATA)
{
unsigned char i;
for(i=0;i<count;i++)
{
sertx(DATA[i]);
}
SMART ENERGY METER
84
}
void sendintdata(unsigned int p)
{
unsigned int temp;
temp=p;
sertx(temp/1000+0x30);
temp=temp%1000;
sertx(temp/100+0x30);
temp=temp%100;
sertx(temp/10+0x30);
sertx(temp%10+0x30);
}
unsigned char KeyTest(void)
{
P1=0xF0;
while (1)
{
while(P1!=0xF0)
{
r0=0; r1=1;r2=1;r3=1;
if(c0==0)
return '1';
else if(c1==0)
return '2';
else if(c2==0)
return '3';
else if(c3==0)
return 'A';
r1=0; r0=1;r2=1;r3=1;
SMART ENERGY METER
85
if(c0==0)
return '4';
else if(c1==0)
return '5';
else if(c2==0)
return '6';
else if(c3==0)
return 'B';
r2=0; r0=1;r1=1;r3=1;
if(c0==0)
return '7';
else if(c1==0)
return '8';
else if(c2==0)
return '9';
else if(c3==0)
return 'C'; // Down Arrow
r3=0; r0=1;r1=1;r2=1;
if(c0==0)
return 'E';
else if(c1==0)
return '0';
else if(c2==0)
return 'F'; // Redail
else if(c3==0)
return 'D'; // Enter
}
}
}
SMART ENERGY METER
86
// update service
void UpdateService(void)
{
unsigned int Temp;
Temp=0;
key=0;
while(1)
{
if(Temp!=Count)
{
MSDelay(50); // Intentional Delay of 0.1mSec.
Temp=Count;
LCDClear();
lcdcmd(0x80);
WriteString(11,"Total units:");
lcddata(Temp/1000+0x30);
Temp=Temp%1000;
lcddata(Temp/100+0x30);
Temp=Temp%100;
lcddata(Temp/10+0x30);
lcddata(Temp%10+0x30);
lcdcmd(0xc0);
WriteString(13,"1.send 2.exit");
do
{
key=KeyTest();
}
while(key!='1'&&key!='2');
switch(key)
SMART ENERGY METER
87
{
case '1':
{
SendString(26,"\r\ncustomer no:9491327686\r\n");
SendString(10,"units are:");
sendintdata(Count);
LCDClear();
lcdcmd(0x80);
WriteString(9,"data send");
lcdcmd(0xC0);
WriteString(4,"1:ok");
do
{
key=KeyTest();
}
while(key!='1');
MainMenu();
break;
}
case '2':
{
MainMenu();
break;
}
}
}
}
}
void MainMenu(void) // Start of project
SMART ENERGY METER
88
{
unsigned char key;
unsigned char mode;
// unsigned char Sensor, Data[3];
key=0;
// Sensor=0;
/*do
{
key=KeyTest();
}
while(key!='E');*/
LCDClear();
lcdcmd(0x80);
LCDClear();
WriteString(10,"1. Reading");
lcdcmd(0xC0);
WriteString(11,"2. settings");
do
{
key=KeyTest();
}
while(key!='1'&&key!='2');
switch(key)
{
case '1':
{
//Count=0;
LCDClear();
lcdcmd(0x80);
SMART ENERGY METER
89
//void Init_GSM();
/* Sensor=MyData;
Data[0]=(Sensor/100)+0x30;
Sensor=Sensor%100;
Data[1]=(Sensor/10)+0x30;
Data[2]=(Sensor%10)+0x30;
if(((Data[0]+(Data[1]*10))+Data[2])<30)
WriteString(3,Data);*/
WriteString(6,"units:");
lcddata(Count/1000+0x30);
Count=Count%1000;
lcddata(Count/100+0x30);
Count=Count%100;
lcddata(Count/10+0x30);
lcddata(Count%10+0x30);
lcdcmd(0xc0);
WriteString(16,"press 2 to Exit:");
UpdateService();
MainMenu();
break;
}
case '2':
{
LCDClear();
lcdcmd(0x80);
WriteString(14,"1.Rs/Unit 2.ID");
lcdcmd(0xC0);
WriteString(13,"3.pwd 6.ph no");
do
SMART ENERGY METER
90
{
key=KeyTest();
}
while(key!='1'&&key!='2'&&key!='3'&&key!='6');
mode=key;
switch(key)
{
case '1':
LCDClear();
lcdcmd(0x80);
WriteString(16,"Rs Per Unit=3.50");
lcdcmd(0xC0);
WriteString(15,"1:change 2:exit");
do
{
key=KeyTest();
}
while(key!='1'&&key!='2');
switch(key)
{
case '1':
Start();
break;
case '2':
MainMenu();
break;
};
break;
case '2':
SMART ENERGY METER
91
LCDClear();
lcdcmd(0x80);
WriteString(15,"Change User ID:");
lcdcmd(0xC0);
WriteString(15,"1:change 2:exit");
do
{
key=KeyTest();
}
while(key!='1'&&key!='2');
switch(key)
{
case '1':
Start();
break;
case '2':
MainMenu();
break;
}
case '3':
LCDClear();
lcdcmd(0x80);
WriteString(11,"Pwd is 1234");
lcdcmd(0xC0);
WriteString(15,"1:change 2:exit");
do
{
key=KeyTest();
}
SMART ENERGY METER
92
while(key!='1'&&key!='2');
switch(key)
{
case '1':
Start();
break;
case '2':
MainMenu();
break;
}
break;
case '6':
LCDClear();
lcdcmd(0x80);
WriteString(16,"Ph no:9491327686");
lcdcmd(0xC0);
WriteString(15,"1:change 2:exit");
do
{
key=KeyTest();
}
while(key!='1'&&key!='2');
switch(key)
{
case '1':
Start();
break;
case '2':
MainMenu();
SMART ENERGY METER
93
break;
}
break;
}
}
}
}
void Start(void)
{
unsigned char key;
unsigned char uid[4],loop,pwd[4]={'0','0','0','0'};
key=0x00;
/* do
{
key=KeyTest();
}
while(key!='E'); // wait for enter. */
LCDClear();
WriteString(8,"User ID:");
loop=0;
do
{
key=KeyTest();
if(key>='0' && key<='9')
{
uid[loop]=key;
lcddata(key);
loop++;
MSDelay(100);
SMART ENERGY METER
94
}
}
while(loop!=4);
lcdcmd(0xC0);
WriteString(9,"Password:");
loop=0;
key=0;
do
{
key=KeyTest();
if(key>='0' && key<='9')
{
pwd[loop]=key;
lcddata('*');
MSDelay(100);
loop++;
}
}
while(key!='E');
LCDClear();
if((pwd[0]==MY_PWD[0])&&
(pwd[1]==MY_PWD[1])&&
(pwd[2]==MY_PWD[2])&&
(pwd[3]==MY_PWD[3]))
{
WriteString(15,"Authenticated!!");
MSDelay(50);
MainMenu();
}
SMART ENERGY METER
95
else
{
WriteString(16,"Access Denied!!!");
lcdcmd(0xC0);
WriteString(15,"1:change 2:exit");
do
{
key=KeyTest();
}
while(key!='1'&&key!='2');
switch(key)
{
case '1':
Start();
break;
case '2':
MainMenu();
break;
}
}
}
void LCDClear(void)
{
lcdcmd(0x0E);
lcdcmd(0x01);
lcdcmd(0x06);
lcdcmd(0x80);
}
void main(void)
SMART ENERGY METER
96
{
IE=0x81;
sense=1;
Flag=0;
Count=0;
serialinit();
lcdcmd(0x38);
lcdcmd(0x0E);
lcdcmd(0x01);
lcdcmd(0x06);
lcdcmd(0x80);
//MyData=0xFF;
WriteString(16,"Welcome ECE@MVSR");
lcdcmd(0xC0);
WriteString(16,"SMART ENERGY Mtr");
//Start();
MSDelay(10);
MainMenu();
}

You might also like