You are on page 1of 61

Prototype for electric meter to detect electric theft

Using Pic 18F452

Supervisor

Malik Tariq Awan


Assistant Professor

Submitted By

Saad Bin Yousuf 11A01EE/4037

DEPARTMENT OF ELECTRICAL ENGINEERING


FACULTY OF ENGINEERING AND APPLIED SCIENCES
RIPHAH INTERNATIONAL UNIVERSITY, ISLAMABAD

i
March-2014

Prototype for electric meter to detect electric theft


Using Pic 18F452

Supervisor

Malik Tariq Awan


Assistant Professor

Submitted By

Saad Bin Yousuf 11A01EE/4037

A Project Report submitted in partial fulfilment of the


requirements for the award of Bachelors Degree in
Electrical Engineering

DEPARTMENT OF ELECTRICAL ENGINEERING


FACULTY OF ENGINEERING AND APPLIED SCINCES
RIPHAH INTERNATIONAL UNIVERSITY, ISLAMABAD

ii
MARCH-2014

Undertaking

We certify that project work titled Electricity theft detection Using Pic 18F452 is

my own work. No portion of the work presented in this project has been submitted

in support of another award or qualification either at this institution or elsewhere.

Where material has been used from other sources it has been properly

acknowledged / referred.

________________

Saad Bin Yousuf

11A01EE/4037

iii
Acknowledgements

I would like to thank following people for their help throughout in the development

of this project:

Our project supervisor Malik Tariq Awan, without whose help our project would

not have been possible. My family for their unconditional support and especially

my mother whose prayers have helped me on the tough course of life and my

friends who have been loyal to me and supported me throughout my life.

My wife who stood by me throughout this project.

And lastly the people from IESCO without them this idea would have never come

to my mind.

iv
Abstract

One of my teachers told me that an engineer is a person who can fly a plane

with one wing only. Electricity theft is a major problem in Pakistan. This meter

is just a prototype of how we can stop electricity theft.

The projects heart is a PIC 18F452 microcontroller and it the main technique

used is of current measuring in the forward current wire and reverse current

wire.

We can easily detect any theft if we compare the current in the two wires.

This project is of immense importance in our country where electricity theft is a

common problem. Of course real time application will require quite a few

changes. My project takes the input voltage value and also takes in the

forward and reverse current converts all three to digital domain calculates the

RMS value of all three. It then compares the forward and reverse current

notifies if there is any theft. It also shows the power being consumed at the

load.

v
Table of Contents
Undertaking __________________________________________________________ iii
Acknowledgements _____________________________________________________ iv
Abstract _______________________________________________________________v
Chapter 1 ______________________________________________________________ 1
Introduction __________________________________________________________ 1
BACKGROUND __________________________________________________________________ 1
1.1 POJECT MOTIVATION _______________________________________________________ 1
1.2 My Project __________________________________________________________________ 4
1.3 Application _________________________________________________________________ 5
1.4 Proposed Scheme ____________________________________________________________ 6
1.5 Objectives __________________________________________________________________ 7
Chapter 2 ______________________________________________________________ 8
Current Measurement Techniques and Devices _______________________________ 8
2.1 Principles _____________________________________________________________________ 8
2.2 Resistive(Direct) ______________________________________ Error! Bookmark not defined.
2.2.1 Current Sense Resistor ___________________________________________________ 9
2.2.2 Inductor DC resistance __________________________ Error! Bookmark not defined.
2.3 Megnatic Sensing (Indirect) ____________________________ Error! Bookmark not defined.
2.3.1 Current Transformer ____________________________________________________ 11
2.3.2 Rogowski Coil _________________________________________________________ 12
2.3.3 Hall Effect ____________________________________________________________ 13
2.4 Transistors (Direct Method) _____________________________________________________ 15
2.4.1 RDS(ON) Method ________________________________________________________ 15

Chapter 3 _____________________________________________________________ 17
Circuits Designing and Implementation ___________________________________ 17
3.1 Designing __________________________________________________________________ 17
3.2 Signal Conditioning Section ____________________________________________________ 17
3.3 Power Section _______________________________________________________________ 19
3.4 Theft Indication Section ________________________________________________________ 20
3.5 The PIC 18F452 ______________________________________________________________ 21
3.6 Coding of the controller ________________________________________________________ 22
3.6.1 The Main Body of The code _______________________________________________ 22
3.6.2 Other Codes and files _____________________________________________________ 26
3.7 Integrated Circuits ____________________________________________________________ 34
3.7.1 The PIC microcontroller 18F452 ____________________________________________ 34
3.7.2 OP Amp LM 358P_______________________________________________________ 37
3.7.3 L7805CV (Voltage Regulator) ____________________________________________ 41

Chapter 4 _____________________________________________________________ 42
Project Working and Results ____________________________________________ 42
4.1 Bill Of Materials ______________________________________________________________ 42
4.2 Project Schematics And Signals __________________________________________________ 43

vi
4.2.1 Voltage Signal RMS value Calculation ________________________________________ 44
4.3 CUR-F and CUR-R signals _____________________________________________________ 45
4.4 Conditions on Theft ___________________________________________________________ 48

Conclusion and Evaluation ____________________________________________ 50


Future Recommendations ______________________________________________ 51
References __________________________________________________________ 52

vii
List of Figures
Figure 1.1 Theft Picture ........................................................................................................................ 3

Figure 2.1 AC Current transformer ..................................................................................................... 11

Figure 2.2 Rogowski Coil .................................................................................................................... 13

Figure 2.3 Hall Effect Principle ........................................................................................................... 14

Figure 2.4 Ratio Metric Current Sense MOSFET ............................................................................... 15

Figure 2.5 Current Sensing Using MOSFET ... 16

Figure 3.1 Signal Conditioning Circuit ................................................................................................ 18

Figure 3.2 Power Section Circuit. .................... 19

Figure 3.3 Theft Indication Section ..................................................................................................... 20

Figure 3.4 PIC Microcontroller Section ............................................................................................... 21

Figure 3.5 PIC Microcontroller ............................................................................................................ 34

Figure 3.6 LM 358............................................................................................................................... 37

Figure 3.7 LM 358 Pin configration..................................................................................................... 38

Figure 3.8 L 7805CV........................................................................................................................... 41

Figure 4.1 The Main Project ............................................................................................................... 43

Figure 4.2 Signal Conditioning Of Voltage Signal .............................................................................. 43

Figure 4.3 Simulation Of Voltage Signal............................................................................................. 44

Figure 4.4 CUR-F and CUR-R Conditioning Circuits ......................................................................... 45

Figure 4.5 Simulation of CUR-F and CUR-R Signals ......................................................................... 46

Figure 4.6 Picture of Project Operating Without Theft....................................................................... 46

Figure 4.7 Display of LCD without Theft ............................................................................................. 47

Figure 4.8 Simulation of Proteus ........................................................................................................ 47

Figure 4.9 Display of Project on Theft ................................................................................................ 48

Figure 4.10 Display of Signals on Oscilloscope of theft ..................................................................... 48

Figure 4.11Display Of LCD on Theft .................................................................................................. 49

Figure 4.12Display of Simulation of Proteus ...................................................................................... 49

viii
List of Tables
Table 2.1 AC Shunt Resistances Advantages and Disadvantages ..................................................... 9

Table 2.2 DC shunt Resistances Advantages and Disadvantages .................................................... 10

Table 2.3Advantages and Disadvantages of Current Transformer .................................................... 12

Table 2.4Hall Effect sensing Advantages and Disadvantages .......................................................... 14

Table 3.1 LM 358 Electrical Parameters ............................................................................................ 39

ix
Chapter 1

Introduction

BACKGROUND

Electricity theft is common problem in Pakistan.It is a major reason for the decline of the

quality of life in the country. We have seen in cases that there had been an immense

amount of power theft in industrial sector which had caused the power companies millions

of dollars.

Electricity theft is common in many countries and a considerable amount is stolen every

year from electricity grids. It deteriorates the financial condition of utilities, curtails new

investments for capacity development that eventually leads to electricity shortage.

In Pakistan it is reported that FESCO, GEPCO, LESCO, MEPCO, IESCO, SEPCO,

HESCO, PEPCO, and KESCO lost Rs600 million, Rs360 million, Rss2.35billion, Rs280

million, Rs3.66 billion, Rs7.47 billion, Rs16.17 billion, Rs59billion and Rs90 lost

respectively on account of theft and line losses. The total mounts to 90 billion in a Year.

Electricity theft is not only a major reason for load shedding, while the financial loss

occurring from theft of electricity also does not allow electricity companies to improve

their distribution system of electricity.

What people usually do in their homes is that they hook a wire to the main phase wire

1
before the meter or they connect the load from one phase wire from the electricity pole

and the other neutral wire they take from the meter.

1.1 POJECT MOTIVATION

The idea of building such a system came to my mind when my aunts family had to go

through a painful experience. What happened was that they had two meters installed at

their house in Soan garden. As their house was under construction, they only used one

meter at a time.

What happened was that an employee of the electric supply company came to the house

and in the absence of the guard took the meter which was not being used by the workers at

that time.

We complained and wrote applications to the company but there was no response.

After two weeks the person who took the meter came back with it. And the amounts of

units used were up to 900 on the meter. We had to pay 11000 Rupees for units which we

did not use.

This issue prompted me to design such a system that would not only detect Electricity

theft but it will also notify it. Again I say this that this is an industrial project with great

market potential. Due to the limited time and the level of my education I was able to

detect theft initially and display it on the LCD.

2
Fig 1.1: A picture of theft by unknown persons

Further motivation and guidance came from an uncle who will not me named who worked

with the electric supply company .He is the one who gave the plan of action of how to

proceed and how to model my project the specifications of how the project should be.

Further my project supervisors guidance was of immense value to me. His practical

knowledge was of great help. It was only due to his unwavering support that I was able to

complete this project alone.

3
1.2 My Project

My projects sole purpose is to stop electricity theft. It can also be used for profit if

properly marketed. There are no such meters or detection methods currently being

employed in Pakistan.

The main problem in my project or the main step was to read the current value and the

voltage value at 220v 50 Hz and then step it down to the level of the PIC microcontroller

and then manipulate it and detect theft by comparing the forward current and the reverse

current.

The way I have designed this project is that it will have to be mounted before the meter. It

wont be movable for every meter and connection it will have to be fixed. We can modify

it to be used as movable electricity theft detection unit. Such meters already exist in the

market for example the clamp on meter.

I have concentrated more on fixed and final solution then on a temporary one.

4
1.3 Application

There are various different applications for this type of meter. First of all it can be used as

a theft detection meter. Then this meter can also be used to find the power consumed by

the load and also this meter can be used in the industry to manage their loads and to

control electricity usage at the peak hours. Thus playing an instrumental role in managing

unit consumption in the industry.

Telemetry is the wireless transmission and reception of measured quantities for the

purpose of remotely monitoring environmental conditions or equipment parameters. The

term is also used in reference to the signals containing such data. Thus this project can

also be used for telemetry applications.

It can also be used in industrial control system and also it can be used in SCADA

(Supervisory Control and Data Acquisition System).

5
1.4 Proposed Scheme

Fig 1.2: Block Diagram for Project

6
1.5 Objectives

MAIN OBJECTIVES OF MY PROJECT ARE AS DESCRIBED BELOW

I will take three signals from the ordinary home powers supply.

One for voltage and two for currents. Forward or Phase line current.

One for Neutral or reverse line current.

I will step the three signals after reconditioning them to the level of the PIC

microcontroller.

Then I will digitalize these signals.

I will calculate all of these values in RMS form using the PIC microcontroller.

I will calculate power at load.

Then I will detect any theft at load by comparing the neutral and phase

voltages.

I will display the phase and neutral currents.

I will display the power being consumed at the load.

I will indicate theft and sound an alarm when theft occurs.

7
Chapter 2

Current Measurement
Techniques and Devices
2.1 Principles

Current sensing is used to perform essential circuit functions. In our case we will use it to

measure how much current is flowing in a circuit, and then make decisions on it.

There are many different components that measure a current flowing through a wire.

Each component uses different theory. Each method has advantages for current

measurement, but also comes with tradeoffs that can be critical to the end reliability of the

application. Different laws that are used are listed below

Ohms law

Amperes law

There are two methods to detect current one is direct and other is indirect method.

Resistive (Direct)
a. Current Sense Resistors
b. Inductor DC resistance

Magnetic (Indirect)
a. Current Transformer
b. Rogowski Coil
c. Hall Effect Device

Transistor (Direct) MOSFETS


a. RDS(ON)
b. Ratio-metric

8
2.2 Resistive (Direct)

2.2.1 Current Sense Resistor

The resistor is a direct method of current measurement that has the benefit of simplicity

and linearity. The current sense resistor is placed in line with the current being measured

and the resultant current flow causes a small amount of power to be converted into heat.

This power conversion is what provides the voltage signal. Other than the favorable

characteristics of simplicity and linearity, the current sense resistor is a cost-effective

solution with stable Temperature Coefficient of Resistance of less than 100 ppm per

degree centigrade or 0.01% per degree centigrade and does not suffer the potential of

avalanche multiplication or thermal runaway. Additionally, the existence of low resistance

metal alloy current sense products offer superior surge performance for reliable protection

during short circuit and overcurrent events.

Table 2.1: AC shunt Resistances Advantages and Disadvantages

9
2.2.2 Inductor DC resistance

The DC resistance of an inductor can also be used to provide a resistive current

measurement. This method is considered lossless because of the low resistance value of

the copper, typically less than one milli ohm and because it is providing a secondary use

of an existing component. In higher current applications; a 30 amp current would provide

a 30 mV signal for a 1 m resistance value. This method has two drawbacks; first copper

has a high TCR (temperature coefficient of resistivity) of approximately 3900 ppm, which

causes the resistance value to increase by 39% for a 100C rise above room temperature.

Because of this high TCR, the temperature must be monitored and compensated to provide

an acceptable current measurement. The second drawback is the variance in the resistance

of the copper due to dimensional changes that occur due to the conductor being wider or

thinner from one lot to the next.

Dc resistive shunt

Table 2.2: DC Shunt Resistances Advantages and Disadvantages

10
2.3 Magnetic Sensing (Indirect)

2.3.1 Current Transformer

A current transformers three key advantages are that it provides isolation from the line

voltage, provides lossless current measurement, and the signal voltage can be large

providing a measure of noise immunity. This indirect current measurement method

requires a changing current, such as an AC, transient current, or switched DC; to provide a

changing magnetic field that is magnetically coupled into the secondary windings.

The secondary measurement voltage can be scaled according to the turns ratio between the

primary and secondary windings. This measurement method is considered lossless

because the circuit current passes through the copper windings with very little resistive

losses. However, a small amount of power is lost due to transformer losses from the

burden resistor, core losses, and primary and secondary DC resistance.

Fig 2.1: AC Current Transformer

11
.

Table 2.3 Advantages and Disadvantages of Current Transformer

2.3.2 Rogowski Coil

The Rogowski coil is similar to a current transformer in that a voltage is induced into a

secondary coil that is proportional to the current flow through an isolated conductor. The

exception is that the Rogowski coil, is an air core design as opposed to the current

transformer that relies upon a high permeability core, such as laminated steel, to

magnetically couple to a secondary winding. The air core design has a lower inductance

providing a faster signal response and very linear signal voltage. Because of its design, it

is often used as a temporary current measurement method on existing wiring such as a

handheld meter. This could be considered a lower cost alternate to the current transformer.

12
Fig 2.2: Rogowski Coil

2.3.3 Hall Effect

When a current carrying conductor is placed in a magnetic field, a difference in potential

occurs perpendicular to the magnetic field and the direction of current flow. This potential

is proportional to the magnitude of the current flow. When there is no magnetic field and

current flow exists, then there is no difference in potential. However, when a magnetic

field and current flow exists the charges interact with the magnetic field, causing the

current distribution to change, which creates the Hall voltage. The advantage of Hall effect

devices are that they are capable of measuring large currents with low power dissipation.

13
However, there are numerous drawbacks that can limit their use, including non-linear

temperature drifts requiring compensation, limited bandwidth, low range current detection

requires a large offset voltage that can lead to error, susceptibility to external magnetic

fields, and high cost.

Fig 2.3: Hall Effect Principle

Table 2.4: Hall efect sensing advantages and Disadvantages

14
2.4 Transistors (Direct Method)

2.4.1 RDS(ON) method

Transistors are considered a lossless overcurrent detection method since they are

standard control components to the circuit design and no further resistance or power

dissipating devices are required to provide a control signal. Transistor datasheets provide

the on-resistance for the drain-to-source, RDS(ON), with a typical resistance in the m range

for power MOSFETs . This resistance comprises several components that begin with the

leads connecting to the semiconductor die through the resistance that makes up the

numerous channel characteristics. Based on this information, the current passing through

the MOSFET can be determined by ILoad = VRDS(ON) / RDS(ON).

Fig 2.4: Ratio Metric Current Sense MOSFETs

15
The MOSFET consists of thousands of parallel transistor cells that reduce the on-

resistance. The current sensing MOSFET uses a small portion of the parallel cells and

connects to the common Gate and Drain, but separate Source. This creates a second

isolated transistor; a Sense transistor. When the transistor is turned on, the current

through the sense transistor will be a ratio comparable to the main current through the

other cells.

Depending on the transistor product, the accuracy tolerance range can vary from as low as

5% or as wide as 15% to 20%. This is not suitable for current control applications that

typically require 1% measurement accuracy, but is intended for over current and short

circuit protection.

Fig 2.5: Current sensing using MOSFETs

16
Chapter 3

Circuits Designing and


Implementation

3.1 Designing

There are three main sections of the project that have to be designed

1. The signal conditioning section

2. The power section

3. The theft indication section

4. The PIC 18F452

5. The coding section

3.2 The Signal Conditioning Section

One of the main section is the signal conditioning section this is very important

section. The main question is that why we need this section? We need this section

because our PIC controller takes input at 0-5 volt. Therefore we have to bring a our

signals to the level of the microcontroller.

Now we have three signals that we have to recondition to bring them to the level of

0-5 volt so that it can be processed by the microcontroller.

17
The first signal is of voltage from the supply. The other two signals are of reverse

current and forward current. Now the procedure is same for all the signals.

Fig 3.1: Signal conditioning circuit

The voltage signal is stepped down using a 220-12v transformer. Now a voltage

divider circuit is used to further step it down to approximately to 1volt rms peak. Then

a coupling capacitor is used and then a potentiometer is used to give DC shift to the

signal. The DC shift is given so that all the signal the negative and positive peaks fall

in the range of the microcontroller. Then a buffer circuit is used. Why? This circuit is

used so that two kilo Ohm pull up resistor that is used with the microcontroller does

not combine with the potentiometer at the back end and form a voltage divider circuit thus

disrupting the circuit. A DC shift of 2.5 volt is given by adjusting the potentiometer.

18
3.3 The Power section

Fig 3.2: Power section circuit

Firstly I used an adapter to convert 220v to 12volt dc and one ampere current. And

in this section I used a simple regulator LM 7805 to convert to 12 volt to 5 volt dc.

There is not much technicalities in this section. I additionally used an LED to

indicate whether the circuit is receiving the power or not.

This section is necessary to give the microcontroller the power and also to power

all the integrated circuits

19
3.4 The Theft Indication Section

Fig 3.3: Theft indication section

The main purpose of this section is to sound the alarm and also to show it on the

LCD. A simple FET is used in this section as trigger mechanism. The signal from the

microcontroller acts as a trigger which sounds the alarm through the FET.

20
3.5 The PIC 18F452

Fig 3.4: PIC Microcontroller section

The PIC 18F452 is the heart of the project all the coding done is C language is in

the controller .The capacitors and the quartz crystal and the supply and the

resistors are shown in the diagram. This is the general configuration which has to

be used in order for the project to run. Also I used MPLAB software and PIC2

programmer to burn the coding on my Microcontroller.

21
3.6 The coding of the controller

3.6.1 This is the main body of the code

#include<htc.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
#include"delay.h"
#include"adc.h"
#include"usart.h"
#include"lcd.h"

#define MUL 0.0048828125 //ACdc 1 step value in volt(LEASTCONT) 5volt/1024


#define ALARM RB0

__CONFIG(1, OSCSDIS & HS);


__CONFIG(2,BOREN & BORV42 & PWRTEN & WDTDIS);
__CONFIG(3, CCP2RC1);
__CONFIG(4, DEBUGDIS & LVPDIS & STVRDIS);
__CONFIG(5, CPALL); // UNPROTECT
__CONFIG(6, WPB);
__CONFIG(7, TRPALL);

int RES;
unsigned int i=0;
double volt;
unsigned char STRR[15];
double sqrd=0.0;
double sum=0.0;
double mean;
double root;
double vrms;
double IrmsF;
double IrmsR;
double IrmsD=0;
double Prms;
unsigned char Vrms=0;

void main (void)


{
TRISB=0X00; //output for PORTB
PORTB=0x00;
adc_init();

22
SetUARTBaud(9600);

lcd_init(FOURBIT_MODE);
lcd_cmd(CURSOR_BLINK_OFF);
lcd_clear();

lcd_goto(FIRST_LINE);
lcd_puts("Vrms V");
lcd_goto(SECOND_LINE);
lcd_puts("Irms[F] A");
lcd_goto(THIRD_LINE);
lcd_puts("Irms[R] A");
lcd_goto(FOURTH_LINE);
lcd_puts("Prms W ");

DelayS(1);

while(1)
{
sum = 0;
set_adc_channel(0);//RA0 setting reading from
for(i=0;i<512;i++)
{

RES=adc_read();
volt=(RES-511)*MUL; // BRING 2.5 BACLK TO ZERO AND
MEASURE mV
sqrd=volt*volt;
sum=sum+sqrd;

}
mean=sum/512;
root=sqrt(mean);
vrms=fabs(root); //remoing negative of sqrt
sum=0.0;
vrms=vrms+0.0689;
vrms=vrms*230.0;

set_adc_channel(1);
for(i=0;i<512;i++)
{

RES=adc_read();
volt=(RES-511)*MUL;
sqrd=volt*volt;
sum=sum+sqrd;

23
}
mean=sum/512;
root=sqrt(mean);
IrmsF=fabs(root);
sum=0.0;
//IrmsF=(IrmsF+0.02681);
//IrmsF=(IrmsF*10.0);
IrmsF=(IrmsF)/(0.0689655174); //turn ratio ,resistance, error all in one
value

set_adc_channel(2);
for(i=0;i<512;i++)
{

RES=adc_read();
volt=(RES-511)*MUL;
sqrd=volt*volt;
sum=sum+sqrd;

}
mean=sum/512;
root=sqrt(mean);
IrmsR=fabs(root);
sum=0.0;
//IrmsR=(IrmsR+0.02681);
//IrmsR=(IrmsR*10.0);
IrmsR=(IrmsR)/(0.0689655174);

if(IrmsF > IrmsR)


{

Prms=(IrmsF*vrms);
IrmsD=IrmsF-IrmsR;
IrmsD=fabs(IrmsD);

}
else if(IrmsR > IrmsF)
{
Prms=(IrmsR*vrms);
IrmsD=IrmsF-IrmsR;
IrmsD=fabs(IrmsD);

}
else
{
NOP();
}

24
sprintf(STRR,"%3.1f",vrms);//diplay value
TransmitString(STRR);
Transmit('\r');
lcd_goto(FIRST_LINE+9);
lcd_puts(STRR);
DelayMs(20);

sprintf(STRR,"%2.2f",IrmsF);
TransmitString(STRR);
Transmit('\r');
lcd_goto(SECOND_LINE+9);
lcd_puts(STRR);
DelayMs(20);

sprintf(STRR,"%2.2f",IrmsR);
TransmitString(STRR);
Transmit('\r');

lcd_goto(THIRD_LINE+9);
lcd_puts(STRR);
DelayMs(20);

sprintf(STRR,"%3.0f",Prms);
TransmitString(STRR);
Transmit('\r');
lcd_goto(FOURTH_LINE+5);
lcd_puts(STRR);
DelayMs(20);

if(IrmsD > 0.3)


{

lcd_goto(FOURTH_LINE+11);
lcd_puts("Theft");
ALARM=1;
DelayBigMs(500);
lcd_goto(FOURTH_LINE+11);
lcd_puts(" ");
ALARM=0;
DelayBigMs(500);

}
else
{
NOP();

25
}

}
}

3.6.2 other files and codes used

#include<htc.h>
#include"adc.h"
#include "delay.h"

#define Low(c) (*(unsigned char *)&(c))


#define High(c) (*((unsigned char *)&(c)+1))
void adc_init(void)
{
TRISA=0xFF;
ADCS0=0;ADCS1=1;ADCS2=0;
ADON=1;
ADFM=1;
PCFG3=0;PCFG2=0;PCFG1=0;PCFG0=0;
}
void set_adc_channel(unsigned char channel)
{
channel&=0x07; // truncate channel to 3 bits
ADCON0&=0xC5; // clear current channel select
ADCON0|=(channel<<3); // apply the new channel selec
}
unsigned int adc_read(void)
{
unsigned int result;
GODONE=1; // initiate conversion on the selected channel
DelayUs(20);
while(GODONE)continue;
Low(result)=ADRESL;
High(result)=ADRESH;
return result;
}

/*

high level delay routines - see delay.h for more info.

Designed by Shane Tolmie of www.microchipC.com corporation. Freely distributable.


Questions and comments to webmaster@microchipC.com.
PICuWEB - Program PIC micros with C. Site has FAQ and sample source code.
www.microchipC.com.

26
For Microchip 12C67x, 16C7x, 16F87x and Hi-Tech C

*/

#ifndef __DELAY_C
#define __DELAY_C

#include <htc.h>

unsigned char delayus_variable;

#include "delay.h"

void DelayBigUs(unsigned int cnt)


{
unsigned char i;

i = (unsigned char)(cnt>>8);
while(i>=1)
{
i--;
DelayUs(253);
CLRWDT();
}
DelayUs((unsigned char)(cnt & 0xFF));
}

void DelayMs(unsigned char cnt)


{
unsigned char i;
do {
i = 4;
do {
DelayUs(250);
CLRWDT();
} while(--i);
} while(--cnt);
}

//this copy is for the interrupt function


void DelayMs_interrupt(unsigned char cnt)
{
unsigned char i;
do {
i = 4;
do {
DelayUs(250);

27
} while(--i);
} while(--cnt);
}

void DelayBigMs(unsigned int cnt)


{
unsigned char i;
do {
i = 4;
do {
DelayUs(250);
CLRWDT();
} while(--i);
} while(--cnt);
}

void DelayS(unsigned char cnt)


{
unsigned char i;
do {
i = 4;
do {
DelayMs(250);
CLRWDT();
} while(--i);
} while(--cnt);
}

#endif

/*
* LCD interface example
* Uses routines from delay.c
* This code will interface to a standard LCD controller
* like the Hitachi HD44780. It uses it in 4 or 8 bit mode
*
*/

#include <htc.h>
#include "lcd.h"
#include "delay.h"

static bit fourbit; // four or eight bit mode?

#ifdef CHECKBUSY

28
unsigned char
lcd_read_cmd_nowait(void)
{
unsigned char c, readc;

LCD_DATA_TRIS = INPUT_DATA;

LCD_RW = 1; // Read LCD


asm("nop"); // short propagation delay
asm("nop"); // short propagation delay

if (fourbit)
{
LCD_STROBE_READ(readc); // Read high nibble
// Move 4 bits to high nibble while zeroing low nibble
c = ( ( readc << 4 ) & 0xF0 );
LCD_STROBE_READ(readc); // Read low nibble
c |= ( readc & 0x0F ); // Or in 4 more bits to low nibble
}
else
{
LCD_STROBE_READ(readc);
c = readc;
}
LCD_RW = 0; // Return to default mode of writing LCD
LCD_DATA_TRIS = OUTPUT_DATA; // Return to default mode of
writing LCD

return(c);
}

void
lcd_check_busy(void) // Return when the LCD is no longer busy, or we've waiting long
enough!
{
// To avoid hanging forever in event there's a bad or
// missing LCD on hardware. Will just run SLOW, but still run.
unsigned int retry;
unsigned char c;

for (retry=1000; retry-- > 0; ) {


c = lcd_read_cmd_nowait();
if (0==(c&0x80)) break; // Check busy bit. If zero, no longer busy
}
}

#endif

29
/* send a command to the LCD */
void
lcd_cmd(unsigned char c)
{
LCD_WAIT; // may check LCD busy flag, or just delay a little, depending
on lcd.h

if (fourbit)
{
LCD_DATA = ( c & 0xF0 );
LCD_STROBE();
LCD_DATA = ( ( c << 4) & 0xF0 );
LCD_STROBE();
LCD_BACKLIGHT=1;
}
else
{
LCD_DATA = c;
LCD_STROBE();

}
}

/* send data to the LCD */


void
lcd_data(unsigned char c)
{
LCD_WAIT; // may check LCD busy flag, or just delay a little, depending
on lcd.h

LCD_DATA = 0;
LCD_RS = 1;
if (fourbit)
{
LCD_DATA |= ( c & 0xF0 );
LCD_STROBE();
LCD_DATA &= 0x0F;
LCD_DATA |= ( ( c << 4) & 0xF0 );
LCD_STROBE();
LCD_BACKLIGHT=1;
}
else
{
LCD_DATA = c;
LCD_STROBE();

}
LCD_RS = 0;

30
}

/* write a string of chars to the LCD */

void
lcd_puts(const char * s)
{
while(*s)
lcd_data(*s++);
}

/* initialize the LCD */


void
lcd_init(unsigned char mode)
{
char init_value;

fourbit = 0;
if (mode == FOURBIT_MODE){
fourbit = 1;
init_value = 0x3;
LCD_BACKLIGHT=1;
}else{
init_value = 0x3F;
}
LCD_RS = 0;
LCD_EN = 0;
LCD_RW = 0;
LCD_BACKLIGHT=1;
LCD_RS_TRIS = OUTPUT_PIN;
LCD_EN_TRIS = OUTPUT_PIN;
LCD_RW_TRIS = OUTPUT_PIN;
LCD_DATA_TRIS = OUTPUT_DATA;
DelayMs(15);
LCD_DATA = (init_value << 4);
LCD_STROBE();
DelayMs(5);
LCD_DATA = (init_value << 4);
LCD_STROBE();
DelayUs(200);
LCD_DATA = (init_value << 4);
LCD_STROBE();
LCD_BACKLIGHT=1;
if (fourbit)
{
LCD_WAIT; //may check LCD busy flag, or just delay a little,
depending on lcd.h
LCD_DATA = (0x2 << 4); // Set 4-bit mode

31
LCD_STROBE();
lcd_cmd(0x28); // Function Set: Two Lines, 5x7 Matrix
LCD_BACKLIGHT=1;
}
else
{
lcd_cmd(0x38);
}

lcd_cmd(0xF); //Display On, Cursor On, Cursor Blink


lcd_cmd(0x1); //Display Clear
lcd_cmd(0x6); //Entry Mode
lcd_cmd(0x80); //Initialize DDRAM address to zero
}

#include <htc.h>
#include <stdio.h>
#include "usart.h"

#define FOSC 20000000

/* Serial initialization */

static bit Bit9;

void Transmit(unsigned char byte)


{
/* output one byte */
while(!TXIF) /* set when register is empty */
continue;
TX9D=1;
TXREG = byte;
}

void TransmitString(const char * s)


{
while(*s)
{
Transmit(*s++);
}
}

unsigned char Recieve(void)


{

32
/* retrieve one byte */
while(!RCIF ); /* set when register is not empty */

Bit9=RX9D;
return RCREG;
}

void RecieveString(unsigned char * r)


{
while(*r)
*r++=Recieve();
}

void SetUARTBaud(unsigned int baud)


{
TRISC7=1;
TRISC6=0;
SPBRG=((FOSC/baud)/16) -1;
BRGH=1;
SYNC = 0; /* asynchronous */
SPEN = 1; /* enable serial port pins */
TXEN = 1; /* enable the transmitter */
CREN = 1; /* enable reception */
TX9=1;
RX9=0; // Change Back to 0
TX9D=1;
TXREG=0;

void DisableUART(void)
{
SPEN=0;
CREN=0;
}

33
3.7 INTEGRATED CIRCUITS:

PIC 18F452 (Microcontroller)

LM358P (op amp)

L7805CV (Voltage regulator)

3.7.1 The PIC Microcontroller 18F452

Fig 3.5: PIC Microcontroller

Some of the Features of PIC microcontroller:

C compiler optimized architecture/instruction set

Linear program memory addressing to 32 Kbytes

Linear data memory addressing to 1.5 Kbytes

Up to 10 MIPs operation:

- DC - 40 MHz oscillations per clock input

- 4 MHz - 10 MHz oscillations per clock input with PLL active

16-bit wide instructions, 8-bit wide data path

34
Priority levels for interrupts

8 x 8 Single Cycle Hardware Multiplier

Peripheral Features:

High current sink/source 25 mA/25 mA

Three external interrupt pins

Timer0 module: 8-bit/16-bit timer/counter with 8-bit programmable prescaler

Timer1 module: 16-bit timer/counter

Timer2 module: 8-bit timer/counter with 8-bit

Timer3 module: 16-bit timer/counter

Secondary oscillator clock option - Timer1/Timer3

Two Capture/Compare/PWM (CCP) modules.

Peripheral Features (Continued):

Addressable USART module.

Analog Features:

Compatible 10-bit Analog-to-Digital Converter module (A/D) with:

- Fast sampling rate

- Conversion available during SLEEP

-Linearity less than or equal to 1 LSB

Programmable Low Voltage Detection (PLVD)

- Supports interrupt on-Low Voltage Detection

Programmable Brown-out Reset (BOR)

35
Special Microcontroller Features:

100,000 erase/write cycle Enhanced FLASH program memory typical

1,000,000 erase/write cycle Data EEPROM memory

FLASH/Data EEPROM Retention: > 40 years

Self-reprogrammable under software control

Power-on Reset (POR), Power-up Timer (PWRT) and Oscillator Start-up Timer (OST)

Watchdog Timer (WDT) with its own On-Chip RC

Oscillator for reliable operation

Programmable code protection

Power saving SLEEP mode

Fully static design

Wide operating voltage range (2.0V to 5.5V)

Industrial and Extended temperature ranges

Low power consumption:

- Less than 1.6 mA typical @ 5V, 4 MHz

-25 A typical @ 3V, 32 kHz

- Less than 0.2 A typical standby current

36
3.7.2 The Operational Amplifier LM358P

The LM358 series consist of two independent, high gain internally frequency compensated

operational; amplifiers which were designed specifically to operate from a single power supply

over a wide range of voltages. Operation from split power supply is also possible and low power

supply current drain is independent of magnitude of the power supply voltages.

Application areas include transducer amplifiers, dc gain blocks and all the conventional op amp

circuits which now can be more easily implemented in single power supply systems.

Fig 3.6: LM 358

Unique Characteristics:

In the linear mode the input common mode voltage range includes ground and the

37
output voltage can also swing to ground, even though operated from only a signal

power supply.

The unity gain cross frequency is temperature compensated.

The input bias current is also temperature compensated.

Advantages:

Two internally compensated op amps.

Eliminates the need of dual supply.

Allow direct sensing near GND and VOUT also goes to GND.

Compatible with all forms of logic.

Power drain suitable for battery operation.

Figure 3.7: LM358 Pin Configuration

Features:
Internally frequency compensated for unity gain.

38
Large dc voltage gains 100 db.

Wide bandwidth unity gain: 1 MHz (temperature compensated).

Wide power supply range:

Single supply 3-32 volt

Dual supply +1.5 to +16v and -1.5v to -16v

Very low power supply current drain 500microamp-essentially independent of

supply voltage.

Low input offset voltage:2 millivolt

Input common mode voltage range includes ground.

Differential input voltage range equal to the power supply voltage.

Large output voltage swing: 0V to V-1.5V.

Electrical Characteristics:

Parameter conditions LM358


min typ mx

Input offset V TA=25C 0 2 3


Input Bias I Vcm=o,T=25c 0 45 100
Input Common Mode V+=30v 0 - v-1.5+
Supply Current RL=infinity V+=30v 0 1 2
V+=5v 0 0.5 1.2

Table 3.1: LM358 Electrical Parameters

FOR operating at high temperature LM358 must be rated on a +125 c max junction

temperature and a thermal resister of 120c\w for MDIP, 182 C/W for metal Can, 189

C/w for small outline package and 230 C/w for MICRO SMD, which applies for the

39
device soldered in a printed circuit board operating in a still air ambient. The dissipation

is the total of both amplifier use external resistor to saturate or to reduce the power

which is dissipated in the integrated circuit.

Short circuit from the output to V+ can cause excessive heating and eventual

destruction. When considering short circuits to ground the maximum, output current is

approximately 40 milliamps independent of the magnitude of v+. At values of supply

voltage in excess of +15V continuous short circuits can exceed the power dissipation

rating and cause eventual destruction. Destructive dissipation can result from

simultaneous shorts on all amplifiers.

40
3.7.3 L7805CV (Voltage regulator)

Fig 3.8:L7805CV

Device specifications:

Output current to 1.5A

Output voltages of 5; 5.2; 6; 8; 8.5; 9; 10; 12; 15; 18; 24V

Thermal overload protection

Short circuit protection

These types of regulators can provide local on-card regulation. After eliminating the

distribution problems associated with single point regulation. Each type employs internal

current limiting, thermal shut-down and safe area protection, making it essentially

indestructible. If adequate heat sinking is provided, they can deliver over 1A output

current.

41
Chapter 4

Project Working and Results

4.1 Bill of Materials:

1 PIC 18F452

2 Op amps

1 crystal Oscillator

1 LED

1LCD 164

5 potentiometers

2 current transformers

2 bulbs and their holders

1 button

1 voltage regulator

1 step down transformer

Couple of resistors and capacitors

1 AC to DC adapter

42
4.2 Project Schematic and Signals

Fig 4.1: The Main overlook of the project

Now I have chosen three points to display simulation and results of my project.

The three main signals that are used are voltage input from the main supply indicated

as VOL in the schematics.

Fig 4.2: Signal conditioning of voltage signal

Now the according to oscilloscope the signal at VOL is shown in Fig 4.3

43
Fig 4.3: Simulation of The voltage signal on oscilloscope also showing DC shift of 2.5 volt

We can clearly see the DC shift of 2.5 volts in the Fig. This is mainly because the

input should lie in the range of 05 volts. This is 1 volts rms signal.

4.2.1 Voltage signal rms value calculation and conversion into digital
domain
Now this signal is first shifted to zero level in the microcontroller because only

then we can calculate the Root Mean Square value. This process is done by this

piece of code.

for(i=0;i<512;i++)
{

RES=adc_read();
volt=(RES-511)*MUL; // BRING 2.5 BACLK TO ZERO AND
MEASURE mV
sqrd=volt*volt;
sum=sum+sqrd;

44
Now this controller has an 10 bit analog to digital converter this gives us 1024

discrete(since 210 =1024) levels in the digital domain and each level has a value of

4.88 mV(5 divided by 1024(the number of levels)). So after this piece of code the

signal is now digital and available for processing.

4.3 The CUR-F and CUR-R signals

The other two signals are the CUR-F and CUR-R as shown in the schematics. The

same procedure is carried out for the other two signals.

Fig 4.4: Signal conditioning circuits of forward and reverse line current

After signal conditioning the signals are shown in Figure 4.5 when no theft is taking place.

45
Fig 4.5: Both Forward and Reverse line currents displayed on Oscilloscope

As we can clearly see from the Fig 4.5 that at no theft condition the signal of forward and reverse current are

exactly the same.

Fig 4.6: Picture of project operating without theft

46
The LCD display of values is shown in Fig 4.7 at no theft condition.

Fig 4.7: Display of LCD without theft

Fig 4.8: Simulation on Proteus

47
4.4 Conditions at theft

Fig 4.9: Display of Project on theft

Now when theft occurs the code in PIC microcontroller detects it and sounds the alarm

and displays it on the LCD.

Fig 4.10: Display of signals on Oscilloscope of theft

48
As it can be clearly seen on the Fig 4.10 that there is clear difference between the two

current signals. The PIC controller detects this difference and displays the theft.

Fig 4.11: Display of LCD on theft

Fig 4.12: Display of Proteus Simulation on theft

49
Conclusion and Evaluation

This project has turned out to be challenging in many ways. Each stage has presented its

own problems to be overcome.

The most challenging part of the project was current sensing part I had decided that I

would use the Hall Effect components to detect theft but due to the attenuating supply and

undependable power source and also due to the undesirable results I had to switch over to

current sensing part through the current transformers.

Then came the coding part the loop that converted the signal to digital domain was a

challenge itself. The time period for one complete wave was 20ms (1/50Hz).

Now designing a loop to match this time specially when hardware multiplication was

involved also a difficult task. Also the frequency fluctuated.

In the end due to the prayers of my mother and the support of my supervisor I was able to

complete my objectives.

50
Future Recommendations

This project is just a prototype. To make it a marketable project there are many different

specifications which will have to be added to make it marketable. I urge my juniors to take

up this project and advance it to make it money worthy.

The improvements that can be made are as follows:

1. A GSM module can be added to message a main data centre of any theft.

2. A data centre can be made to monitor all meters real time.

3. Real time theft can be detected and quick action can be taken to apprehend the

culprits.

4. A remote switch can be added to remotely shut down the meter connection.

51
References

1 Current Sense Amplifiers for Embedded SRAM in High-Performance System-on-a-

Chip Designs: For Embedded SRAM in High-Performance System-on-a-Chip

Designs, Bernhard Wicht, Springer, ISBN 3-540-00298-7

2 Current sensing methods at web link http://powerelectronics.com/power-

electronics-systems/components-and-methods-current-measurement

3 Multimeters: Quantities Measured, Alternating Current Sensing, Digital Multimeters,

Probes, and More,Gaby Alez,Websters Digital services, ISBN-1276220782-

9781276220781

4 Hall effect handbook at http://serge77.rocketworkshop.net/hall/hallbook.pdf

5 Microchip website http://ww1.microchip.com/downloads/en/AppNotes/01332A.pdf

6 Methods of current sensing , Bill Drafts,P.E.

7 Fair child semiconductors at www.fairchildsemi.com

8 Texas instruments at www.ti.com

9 Maxim integrated www.maximintegrated.com

52

You might also like