energy meter by irfansultan

VIEWS: 12,399 PAGES: 70

									CHAPTER 1


This chapter is about what an electrical energy meter is and what type of electrical energy meters we already have. What problem those conventional meters have. How we can use digital technology to minimize those errors. It briefly states the motivation and objectives of this project.




An energy meter is a device that measures the amount of electrical energy supplied to a residence or business. The most common type is more properly known as a (kilo)watt-hour meter. Utilities record the values measured by these meters to generate an invoice for the electricity. They may also record other variables including the time when the electricity was used The meter comonly used in Pakistan at this time is an electromechanical device based on the rotor element which revolves at a speed proportional to power flow and drives a mechanical registering device on which power consumption is intergrated. The output is the sum of all all the power consumed during the life time of the meter. This valuse is read manually by meter readers, employed by the power companies specifically for this task. In other words it is process that lends itself readily to human errors. The aim of our project is to dgitize this mechanism. The essential parts of an analog ac watt-hour meter are shown in figure 1.1

FIGURE 1.1 Basic Parts and connections of Single Phase Energy meter


FIGURE 1.2 Essential Parts of Analog meter


Means of Operations


As shown in means of operation. (1)Voltage coil – many turns of fine wire encased in plastic, connected in paraledl with load. (2) Current coil – three turns of thick wire, connected in series with load. (3) Stator – concentrates and confines magnetic field. (4) Aluninium rotor disc. (5) rotor brake magnets. (6) spindle with worm gear.(7) display dials. Modern electricity meters operate by continuously measuring the instantaneous electrical powe which is then integrated agains time to give engergy used (joules, kilowatt-hour etc). the most common type of electrical meter is the electromechanical induction meter. This consists of an Aluminium disc which is actyed upon by two coils. One coil is connected in such a way that it produces a magnatic flux in proportion to the voltage and the other produces a magnetic flux in proportion to the current. This produces eddy current in the disc and the effect is such that force is exerted on the disc in proportion to the product of the instantaneous current and voltage. A permanent magnet exerts an opposing force proportional to the speed of rotation of the disc – this acts as a brake which causes the disc to stop spinning when powe stops being drawn rather than allowing it to spin faster and faster. This causes the disc to rotate at a speed proportional to the power being used. The aluminium disc is supported by a spindle which has a worm gear which drives the register. The gegister is a series of dials which record the amount of power used. The dials may be of the cyclmter bype where for each dial a single digit is shown throgh a awindow in th eface of the meter, or of the pointer type where a pointer indicates each digit. It should be noted that with the dial pointer type, adjacent pointers generaly rotate in opposite directions due to the gearing mechanism. The type of meter described above is used on a single-phase AC supply. Different phase configuratins use additional voltage and current coils.

A 3-phase analog meter has the same working priciple as the single phase meter. In fact 3phase induction type meter consists of two single phase meters in a common case have a


common spindle gears and display dials. Total driving torqe on the spindle is the sum of indiviual torqes by both of the discs. The connections and the internal diagram of the 3-phase meter is shown in figure 1.4 and figure1.5.

FIGURE 1.4 Basic structure and connections of 3-Phase analog meter


FIGUER 1.5 Internal of 3-Phase analog meter



As we can see from figures and above discussion that there are number of mechanical parts involved in the working of conventional analog energy meters, so these mechanical parts are responsible for many errors such as 1.2.1 Friction error: - Frictional forces are produced in router bearing and gearing system and because of this an unwanted torque is generated on the disc. This slower the meter speed, and shows incorrect energy measurements. 1.2.2 Creeping error: - Moving of disc without passing current through current coil is called creeping. In other words movement of disc with no load due to excitation of potential coil, so this produce wrong reading on the meter, this phenomenon is called creeping error.


1.2.3 Temperature error: - In this type of instruments temperature change affects the resistance on the paths of eddy currents in the disc. So this reduces the driving torque and causes the wrong reading. 1.2.4 Speed error: - This error is produced due to wrong adjustment of breaking magnet, so causes low or high speed of meter. 1.2.5 Calibration error: - Newly made meters are calibrated by comparison with a completely accurate meter so if there is any error in later the whole calibration will go wrong. 1.2.6 Miscellaneous errors: - Wear and tear, mishandling and installing of meter without proper angle also affect the mechanical working of meter and thus produces multiple errors



The Digital watt hour meter is something that is highly practical and would be useful in real world. It is markeble idea, which is viable not only technically but also financially. The digital meter presents many advantages over the conventional meter due to the fact that it is centered on the digital circuit rather than the moving parts. Some of these advantages are  Analog meter is more prone to tempering as compared to digital meter, this is because the analog meter can be simply tempered by adjusting the distance between the rotating disc and the damping magnet thus reducting the speed of rotation of the disc. Tempering the digital meter, on the other hand would require either reprogramming the device or replacing some components, which is more difficult.  Since the digital meter does not involve any moving parts it does not suffer from any mechanical wear and tear and remains consistent and accurate throughot its life time.  Due to digital circuitry, digital meer has the flexibility of change. To add new functions, all that has to be done is to change the software or interface new digital hardware.



As integrated circuits are getting cheaper and cheaper day by day, industrial production of this digital meter will be more economic than the analog meter. Since the data is available in the digital storage, it can be transmitted through various means (for example through power line carrier or through radio transmitter) to the central billing station.



In this project the aim was to create a digital watt-hour meter, which is   Produced using locally available components and resources: this is essential for making it feasible for manufacturing by local firms. Reliable and cost efficient in long term: the proposed design may require a larger initial investment but would saave money in the logner run if additional features like automatic biliging and remote logging etc. are implemented, eliminationg the need for a large wrkforce employed solely for meter reading.  Inmmune to tempering: an electromechanical device can be easily tempered by adjusting the mechanical parts of the meter. In a digital circuit most of the mechanism would be electronic parts which would not be transparent to most of the people and changing it would require replacing one or two components (RAM, A/D etc)  Maketable: digital watt hour meter is not a project of academic interst only ,it is something that we really need todaay. So it is very practical and can be immediately deployed in the real world.  Additional facilities makde feasible by digital circuitry: A digital circuit makes possible many features that are difficult or very expensive to implement in a mechanical device. Some of these features have been added to the proposed digital meter such as voltage, current and power reading.




This chapter explains the underlying theory, the approach adopted and the working of meter .in the end, it briefly describes the evolution of the project and how it is accomplished.




The average power can be measured by multiplying the R.M.S values of voltage and current along with (cos Φ) cos of the phase difference between them repeatedly at predetermined intervals. And energy can be computed by multiplying the time with the average power. 2.1.1 Mathematically: P = V * I * cos (Φ)

Where, P = average power V = R.M.S. voltage across load I = R.M.S. current through load Φ = phase difference between the voltage and current

As we are going to design a three phase system then the total power is the sum of power of all three individual Phases. i.e.

Pt= Pa+ Pb+Pc Where Pt=total average power from three Phases Pa=Power of Phase A Pb=Power of the Phase B Pc=Power of the Phase C And also E = Pt * t

Where E = energy T =time




As mentioned above the power and energy are calculated by using the r.m.s voltage and current samples, for this purpose the values of the voltage and current are stepped down from the mains (220V) to a measurable level through potential transformer and current transformer, respectively. These analogue values are then digitized by the microcontroller. Then the microcontroller performs all the required functions like calculating power and energy, storage of data and passing data to other microcontroller for displaying on the LCD.



The design of the project is the most critical and important part of the any project especially those related to the electronics and electrical components as a whole of its methodology and performance depends on it. At the start of the project we started with the study of the theory related to our project, we collected all the related material and then determine the best options available keeping in mind the matters like low cost, performance, reliability, security and flexibility. At first after studying we come with a design and its description which is shown in the figure 2.1.

FIGURE 2.1 Block diagram of initial design


Diagram explanation:  Three Phases Pa, Pb, Pc with neutral N are shown in left side of the figure joining the Main supply to the load side. 

Each Phase is passing through a current transformer (CT). CT is used here to sense the current passing through each Phase and to make the current readable to analog to digital converter and microcontroller.


Next to the CT’s and the Neutral going toward the right we can see three PT’s i.e. Potential transformer which are used to sense the voltage across the load of each Phase and to made the voltage readable to analog to digital converter and microcontroller.


Below the every PT block we can see the blocks containing the symbol ‘Φ’, these blocks represent the circuitry of finding the phase difference between the current and the voltage.

 

The outputs from the CTs and PTs are inputs of the blocks ‘AC2DC’ where AC signals from the transformers are converted to DC signals. Now towards the right side of the AC2DC blocks we can see the blocks ADC, these are the Analog to Digital Converters that converts the analog DC values into the digital form readable for the microcontroller.


Next to the ADCs there are three microcontrollers that receives the digital values of voltage, current, and Phase difference between them and calculates the Powers of three Phases individually.

 

The power of each Phase is then added with the help of adder IC shown at the right side of three microcontrollers. Next to the adder is the another microcontroller which is main controller which performs various important tasks like, calculation of energy, converting into kilo watt hours, saving the data, and also displaying the units onto the LCD screen.



At the right side of the main microcontroller there is EPROM, which is used to save the record of consumed units. The main purpose of the EPROM is to restore of previous data in case of power failure.


The last blocks in the diagram represents the LCD screen that is used to shows the units in kilo watt hours.



Several changes are made in the initial design due to several factors like non availability of some components and improvement in the design to make the implementation easy and some other factors are also involved. Details of the changes in initial design are listed below and also shown in figure 2.2. 

The first major change that is made in the project is the replacement of Atmel microcontroller with the PIC microcontroller. Because PIC microcontroller gives us several components built-in on the same chip, which we were going to attach outside the Atmel microcontroller like, EPROM, ADC etc. so, by making this change we get rid of a lot of complex circuitry and soldering on the Vero board.


In figure 2.2 we can see that ADCs are not present in the final design. As we mentioned above PIC microcontroller has built-in five ADCs. So PIC microcontroller takes directly analog values of voltages and currents and save us to buy a lot of ADC ICs and also from making a lot of interconnections and soldering on the Vero board.


Another change in the initial design we made is that we are not using EPROM outside the microcontroller because PIC microcontroller has the onchip EPROM so once again we have saved a lot time and recourses to interconnect the external EPROM. As we can see in the figure 2.2 that there is no EPROM at the right side.



The last change in the design is the elimination of adder as we can see in the figure below there is no adder bock. The reason for this change is that we are doing all the computations in 16 bits. But in the market 16 bit adder was not available, and construction of 16 bit adder using the 4bit adder was a complex and time consuming process. So we use another technique using the interrupts, in the initial design only main microcontroller was calculating energy and was taking the values of power from the other microcontrollers. Now in this design three microcontrollers in the left side also calculate energy in kilo watt hours along with the power form the three Phases. When one unit is completed in the in any of the microcontroller then that microcontroller will send a interrupt to the main microcontroller, than main microcontroller will increment a the number of unit after receiving the interrupt and also save and displays the incremented units.

FIGURE 2.2 Block diagram of final design




The project is done in following main phases. 1ST PHASE    

Studying the components in initial design Interfacing the CT and PT to the phase lines Interfacing the microcontroller with the CT and PT. Trying the program for the microcontroller

2ND PHASE    

Changes in the design Introducing another microcontroller in the circuit Introducing LCD display rather than seven segment display Power supply and backup battery


Final integration of hardware and software blocks Final testing for accuracy

It had been planed to achieve the working model of proposed digital watt house meter, which has been done successfully. In order to achiever this all the three phase were distributed according to total time available during the year. Some of the tasks such as procurement of equipment and design ran in parallel, as one dependent on the other.




This chapter describes the main components of hardware used in the project and provides the description of their functions. It also discusses how these components are interfaced and the experimental setup.




Choosing the apparatus for the design was an important issue as we planned the digital meter to be manufactured using locally available components and resources. So the task was performed after visiting the market in detail and getting valuable information from the advisors and some of the faculty members and friends. The components chosen finally for the above design and which are actually present in the final model are listed in the table 3-1. All these components were purchased from the local market.

Micro-Controller A/D EEPROM TIMER Flash memory Current Transformer Potential Transformer LCD Screen

PIC16F877A Built in MCU Built in MCU Built in MCU Built in MCU 40/5 A 240/6 V 16 X 2


List of main components for design

In order to fulfill all the requirements of the design and get satisfactory results, the components chosen are listed above. There are various reasons for choosing these components, such as their availability and their suitability to all the retirements of this project. The specific reasons for the choice of each component are mentioned in detail with the description of each component in section 3.2.




A brief description of the components is given here so that a person not familiar with these components can get a fairly good idea of the hardware used.

Micro controller is a single IC containing all the circuitry of a microprocessor based system necessary for most control applications. This reduces the chip count for the complete circuit built around a micro-controller. It is the brain behind the system and performs all the critical tasks and computations like calculating the power and displaying it. In this project it was decided to use AT 89C51 micro controller, but on further study of PIC microcontroller which provides us various components built on the microcontroller chip. So we decided to use the PIC 16F877A with crystal of 8MHz, it has 8K X 14 words of FLASH Program Memory, Up to 368 x 8 bytes of Data Memory (RAM), Up to 256 x 8 bytes of EEPROM Data Memory. The package that we are using is DIP 40 that has five Ports A, B, C, D and E; all Ports are 8-bit except the Port A and Port E. A PIC 16F877A microcontroller is shown in figure with labeled pins.

FIGURE 3.1 PIC 16F877A microcontroller


Detail of the built-in components on microcontroller chip that make our work much easier and save us from lot of complex circuitry and soldering of these components outside the controller chip is as follows. 


A successive approximation (SAR) ADC converts the analog voltage to a digital value by first determining the MSB of the required digital value. It determines the next most significant bit and so on until it has determined the LSB of the digital value. Therefore, built-in ADCs, on the PIC 16F877A microcontroller chip are 10-bit and having sampling frequency of 400Hz. The Analog-to-Digital (A/D) Converter module has five inputs for the 28-pin devices and eight for the 40/44-pin devices. The conversion of an analog input signal results in a corresponding 10-bit digital number. The A/D module has high and low voltage reference input that is software selectable to some combination of VDD, VSS, RA2, or RA3. In our project we used RA1 and RA2 for voltage and current analog inputs respectively. As shown in the figure below.

FIGURE 3.2 ADC connections




PIC 16F877A have one 16-bit timer and two 8-bit timers. In our project timers are used to keep track of time and date, with leap year correction as well. So it is helpful to create a multi-tariff TOD (time of day) billing system. Multi-tariff system is not included in this phase it will be considered next phase of enhancements of the meter. 


Stores main program. It is electrically erasable. PIC16F877A have 256 x 8 bytes of EEPROM Data Memory from which 8K is for program code enough for the software program used by this project so no need to attach an external EPROM fro longer codes. 


PIC16F877A gives the built-in facility of flash memory which is ideal for backup storage; keep track of previous data in case of power shut down. Units consumed are saved in flash memory momentarily, so in case of power

shutdown previous readings cannot lost and can be restored when power turns on .

A current transformer (CT) samples the current in a line and reduces it to a level measurable by ordinary ammeters. It consists of a secondary winding wrapped around a ferromagnetic core in the shape of a ring, with a single primary line running through the center of the ring, or a small number of turns around the ring. The ferromagnetic ring holds a small sample of the flux from the primary line. The flux then induces voltage and current in the secondary coil, which is directly proportional to the current in the primary Just like an ordinary step-up transformer. The only difference is that the windings are loosely coupled, so there is less self inductance and hence the current in primary line is dependent on the load on the system and not by the


load on the secondary. So basically it is being used in this project to scale down the current to an acceptable level for an A/D to read it. The CT used in this project has a rating of 40/5 Amperes. A current transformer used in project is shown in figure below.

FIGURE 3.3 Current transformers

A potential transformer is a step down transformer with a low power rating. It has a low power rating because it is not intended to power any device but to provide a sample of the voltage on the line at a low enough voltage to enable ordinary voltmeters to measure it. For this purpose it must be very accurate so as not to distort the true voltage values too much. There is a need to scale down the voltage to an acceptable level so that AID can read it. So in place of a potential transformer, an ordinary step down transformer of 240/5 Volts (r.m.s) rating was used, with the assumption that it is fairly accurate within the required voltage range.


FIGURE 3.4 Potential transformer

LCD screen is used to display the unit for the consumer. LCD used can display 16X2 characters that means two rows of 16 characters. LCD has its own built-in back-light so we can see the units in darkness. LCD interface with MCU is shown in figure below.

FIGURE 3.5 LCD interfacing


For the measurement of Ф (phase different) we need a specific electric circuit, with include zero crossing technique, so beside zero crossing detector circuit we have eight bit counter and parallel in parallel out register. The block diagram of the whole circuit is given below.

FIGURE 3.6 Block diagram for Ф measurement circuit

In above diagram we can see that the voltage and current signals are given to two separate zero crossing detectors circuit as inputs. Next to the zero crossing detectors there are frequency dividers which divide number of crossings by 2, which means that in 50Hz frequency there are hundred zero crossings for a sinusoidal waves, this will limit out to 50 crossings, each spike will now show the starting point of the voltage or current wave. The voltage spike will be given to the counter’s reset pin, this counter will be given clock of 4.5KHz. This clock will be able to count till 90 between two spikes. The


voltage spike resets the counter and counter starts from zero and moves further, meanwhile the current spike reaches at register clock and the register takes input from the counter and give that value to the MCU, that value from counter is the measure of Phase Difference.

NOTE: After working on different methods to measure the phase difference, we have fond the above method is the best, but due to lack of time and resources we have work on it separately and didn’t use it in our hardware rather we used pre-build power factor meter.




This chapter describes the computation involved and their implementation in software. This chapter describes how the programming was done for main microcontroller to increment the units keep the record and display the units. This chapter also describes the programming of other three microcontrollers that calculates the energy of each phase.




The equations to be implemented in the software code of the microcontroller are as follows. Power = V * I * (cos (Φ)) Where, V = R.M.S. digitized voltage I = R.M.S. digitized current Φ = digitized phase difference between the voltage and current As Analog to Digital Converter is taking the samples of voltages and currents continuously with a constant sampling frequency N, so dividing the equation (i) by N we get the energy in watt seconds i.e.

----------------------- (i)

Watt seconds = power / N



Where, N is the sampling frequency and its value in the PIC16F877A is 400Hz. Kilowatt hour can be calculated by dividing the equation (ii) by number 3600000 i.e.

Kilowatt hours = Watt seconds /3600000 ------


Thus summing all the values of equation (iii) after every sample until we get our one unit i.e. one kilowatt hour which is our ultimate goal.



4.2.1 Coding of MCUs calulating KWH : temp_v and temp_i are the digitized values of the current and voltage read by the A/Ds converters from the current transformer and potential transformer outputs. The inputs signals from current transformer and potential transformer range from 0-5V and 10-bit A/Ds samples these amplitudes into different digital numbers ranges from 0-1023. So we will have to convert back these values to the original range i.e. 0-240V in case of


voltage and 0-40A in case of current. This can be done by multiplying a constant to the received values from current transformer and potential transformer. i.e.


RMS voltage Received values from ADC ranges from 0---1023 Maximum rating of the meter 0---240V rms Vrms = (Received from ADC) * 0.236

And similarly for current  RMS Current Received values from ADC ranges from 0---1023 Maximum rating of the meter 0---40 Amp Irms = (Received from ADC) * 0.0391 Also for Phase difference Ф  Ф Received values from Register ranges from 0---255 Maximum rating of the meter 0---90 degrees Irms = (Received from Register) *0.352

A C-language code example that is used to read analog values, converts to digital and brings the values into the original range is given below.


…………… unsigned int temp_v, temp_i, Vrms, Irms; void main() { ADCON1 = 0x80; // Configure analog inputs and Vref TRISA = 0xFF; // PORTA is input

do { temp_v = Adc_Read(2); // Get results of AD conversion temp_ I = Adc_Read(2); // Get results of AD conversion Vrms = temp_v * 0.236; //setting A/D values to original range i.e. 0-240v Irms = temp_i * 0.0391; //setting A/D values to original range i.e. 0-40A } while(1); } …………………

Equations i, ii, and iii are also implemented along with this example to calculate the KWH in three MCUs. An interrupt is signal is also send to the main MCU when a unit is completed, this is done simply asserting high signal to the selected pin.



Flow Chart for MCUs calulating KWH :

FIGURE 3.1 Flow chart to calculate KWH


4.2.3 Coding of main MCU : Main MCU does different important tasks like. i ) Incrementing units after receiving interrupts from other controllers. ii ) Saving units in flash memory. iii) Displaying units on LCD screen.

A C-language code example that is used to handle the interrupts is given below. …………………. void interrupt() if (INTCON.RBIF) { units++; TMR0 = 96; INTCON.RBIF = 0; } ………………….. A C-language code example demonstrates simple write to the flash memory for PIC18, then reads the data and displays it on PORTB. ………………………. unsigned short i = 0, j = 0; unsigned long addr; unsigned short dataRd; unsigned short dataWr[64] = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0, 1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0, 1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0, 1,2,3,4};


void main() { PORTB = 0; TRISB = 0; PORTC = 0; TRISC = 0;

addr = 0x00000A30;

// valid for P18F452

Flash_Write(addr, dataWr);

addr = 0x00000A30; for (i = 0; i < 64; i++) { dataRd = Flash_Read(addr++); PORTB = dataRd; Delay_ms(500); } } ……………………….

A C-language code example that is used to display units on LCD is given below. ……………….. char *text = "COMSATS";

void main() { TRISB = 0; Lcd_Init(&PORTB); Lcd_Cmd(Lcd_CLEAR); // PORTB is output // Initialize LCD connected to PORTB // Clear display

Lcd_Cmd(Lcd_CURSOR_OFF); // Turn cursor off Lcd_Out(1, 1, text); }//~! // Print text to LCD, 2nd row, 1st column


4.2.4 Flow Chart for main MCU :

FIGURE 3.1 Flow chart for main MCU




This chapter explains the actual physical device developed and delivered. It also provides a description of main features of digital watt hour meter, as well as the limitation of the delivered product.




The deliverables of the project are as follows.

5.1.1 Hardware Model: The complete working model of this project is the final product and it has been handed in with all below mentioned features. It was demonstrated several times and has been tested and verified through various routines, which show that all components in the circuit are in working order. Features:        Calculates and displays units consumed in kilo watt hours. Three Phase 4-wire system Power factor measurements Voltage and current measurements Storage of power consumption history in a Flash Memory The meter recovers data after power shut down External interface through Serial port or parallel. (some minor changes will be needed in software code)

5.1.2 Software Code: The software was an integral part of this project, mainly for the micro-controller programming section. The source code in C is provided and compiler used for compiling the code is mikroC. Both the C language and mikroC compiler will be discussed. (See Appendices D and E)

5.1.3 Documentation: The final report explains in detail the various facts of Digital watt Hour Meter. All the mathematical theory and the various formulae used for the development of software are included in it. This is basically for understanding the background of project and for any future enhancements. The report also gives all the details of the hardware and software design and actual implementation. 34


Three Phase 4-wire system:

The meter we have developed is Three Phase 4-wire system. However, can be used as three Phase 3-wire system. 

Quantization is 10-bit:

To save cost we used a 10-bit ADC built in the microcontroller. This is inadequate if we want to reduce sampling error to a minimum. A 12-bit ADC converter or 16-bit ADC can be used to increase accuracy. 

Sampling rate is limited:

Once again due to the limitations of the micro-controller there is a limit on the highest sampling rate for which calculations can be done. However, in our design as we are taking DC values sampling rate is not an important issue. 

Accuracy of the current transformer main hurdle:

The accuracy of the current transformer has limited the accuracy of meter. 

Accuracy of voltage transformer is limited:

Similarly, the voltage transformer is another stumbling block as far as efforts towards accuracy are concerned. 

Limited to only sinusoidal wave form:

This design can only measure power of the sinusoidal waves.




This chapter describes the experiments performed on the different components including the assumptions made and their results. It also contains a discussion of the errors, their sources, and how they have affected the final results.




There were several tests performed to determine the characteristics of certain components, mainly including the Current and Potential transformers, and the A/D converter. On the basis of these results and analysis, the whole circuit was tuned in order to achieve maximum accuracy.

6.1.1 Testing of Potential Transformer: The output voltage of the PT was noted for input voltage out of the mains. The results are shown below.

Primary voltage Secondary voltage

= 240 v = 6.6v

Here 6.6v are exceeding from the range of the maximum input of the ADC i.e.5v so these voltages are calibrated to 5volts by using a small variable resistor. Assumption: The transformer was linear throughput our input range.

6.1.2 Testing of Current Transformer: The output current of the CT is noted in the form of voltage by inserting a resistor between the output terminals of the CT and then note the voltage across the resistor. Different experimental readings of the output current (in the form of voltage across the resistor) are shown below.

Primary current Voltage across resistor

= 0.25A = 0.036v

Primary current Voltage across resistor

= 2.43A = 0.387v

Primary current Voltage across resistor

= 4.28A = 0.68v


Primary current Voltage across resistor

= 6.6A = 1.07v

Like PT outputs of CT are also calibrated to make compatible to the ADC using Operational Amplifiers and variable resistors.

The linearity error of CT therefore is negligible at loads that draw more than two amperes of current, which is the case for the most consumers most of the time.

6.1.2 Testing of ADCs of the MCU: The ADC was connected to the input according to figure 3.2. The digital values at the output for different values of input voltage were noted as listed below.

Input voltage Digital output

= 0v = 0000000000

Input voltage Digital output

= 0.25v = 0000110011

Input voltage Digital output

= 2v =0110011001

Input voltage Digital output

=4v =1100110011

Input voltage Digital output

=5v =1111111111



Calculated errors vs. Actual errors:

The readings were taken for resistive loads. Multi-meters measured the current on the line and the voltage. The multiplication of these values was computed, which was the real power. This value was compared to the power being displayed by the meter and the signal conditioning circuit was tuned to give accurate results. Due to quantization errors, the accuracy of the voltage read is 2 volts- this is because the range -400 to 400 Volts is represented by 0-255; an accuracy of 2.2 volts per step. Similarly the current is accuracy is 0.15A per step. The power calculated, however, is more accurate than you would expect by simply multiplying the two errors. This is because the power is not calculated by simply multiplying the peak voltage and current detected, but is calculated by numerical integration.




This chapter describes the tasks achieved, important issues encountered and output of this project. The benefit of the digital meter due to extra features, suggested improvements and future enhancements possible are explained.




At the end of the project certain landmarks had been achieved, which are briefly described here:      A/D converter interface circuitry with the CT, PT and analog Power factor meter using proper equipment. Interfacing circuitry of LCD with the MCU Completion of MCU programming Power supply Final testing and calibration



The benefits that digital watt hour meter provides due to digital circuitry and which could not be present in an analog meter are as follows  Storage of power consumption history

By storing the power consumption history in its RAM, the meter will provide both the users and the power suppliers with a record of the power consumed during any time period. Storage of power consumption history will also help in record keeping and monitoring efficiency.  Multiple tariffs for different hours

Different tariff rates for peak hours are possible with the availability of power consumption record. This will encourage even distribution of load during the day and hence reduce the burden on the transmission system at peak hours and thus reducing load shedding  Remote logging facility and automatic billing possible

The storage of data in digital format makes its access easy. An extension of this project could be devising a mechanism for the central billing station to access this data by communication through power line carrier, resulting in automatic billing.



Quality- Consistent throughout life cycle

Unlike analog equipment digital integrated circuits do not change the characteristics with time. This means that the digital device does not become inaccurate with time.  Security-difficult to tamper

Unlike an analogue device, tampering with the digital device would involve replacing one or more components, which is a difficult proportion in an industrially produced device with few discrete, separable components.


Phase errors due to transformers

The output current of the CT is not in phase with the line current. This phase error is compensated for in the software. This is done by multiplying the instantaneous voltage with the shifted version of the detected current waveform instead of the detected current waveforms to get the instantaneous power. 

Linearity error in CT

The linearity error, except for small values of line current, is negligible and is not compensated in the design. 

Limit on sampling rate

To get accurate results, it is desirable to sample the voltage and the current at the highest possible rate. However, in our design as we are taking DC values sampling rate is not an important issue. 

Data storage and retrieval

One of the main features of the design is the provision of storage of power consumption data in the meter. As explained in chapter 4, the meter keeps a record of the latest values in its flash memory.


7.4 SUGGESTED IMPROVMENTS  Direct measurement from line into ADC

Digital multi-meters read voltage and current directly without the use of instrumentation transformers by use of voltage and current divider circuits etc. Since the load voltage and current for an ordinary household is not extremely large, this method can be adopted in the digital watt hour meter. This would reduce the errors due to transformers. 

Use of 12-bit or higher resolution A/D converter

Using 12-bit A/D converter instead of 8-bit A/D converter would result in greater accuracy by removing quantization errors.  Give solution of Power factor in software coding

As in our design DC values of voltages are taken and then converted to RMS values, so power factor cannot be calculated in software. AC signals should be taken to give a software solution of power factor.


Remote logging facility

The device developed stores the power consumption history in digital storage, enabling access of this data by any external device through a serial port. By building a module that will communicate this data to a central billing station, automatic billing is possible.  Can easily be extended to prepaid

A prepaid card system can easily be interfaced with this meter, few amendments will be need in software.  Power factor Alert

Can easily be extended to the system that can alert power Supply Company when power factor goes down the minimum range.


Zero crossing detector circuit and explanation: As the name indicates the zero crossing detector is a device for detecting the point where the voltage crosses zero in either direction. As shown in the above circuit diagram the first section is a bridge rectifier, which provides full wave rectified output. This is applied to the base of the transistor through a base resistor, R2. The capacitor charges to maximum of the bridge rectified output through the diode,D5. This charge is available to the transistor as VCC. The capacitance value is kept large in order to minimize ripple and get perfect dc. The transistor remains OFF until the Cut-in voltage VBE is reached. During the OFF period of the transistor the output will be high and approximately equal to VCC. Once the transistor is ON and IB increases according to the input wave, the transistor moves slowly towards saturation where the output reduces to the saturation voltage of the transistor which is nearly equal to zero. Initially VBE = Cut-in voltage of diode, the capacitor will charge through the diode Vm where Vm is the maximum amplitude of the rectified wave. Now the diode is reverse biased and hence does not provide a discharging path for the capacitor, which in turn has two effects. 1. Variation in VCC. 2. It will provide base current to the transistor in the region where both diode and transistor are OFF. Thus an output square wave is produced whenever the input voltage crosses zero thereby acting as a zero crossing detector. Procedure: EDWin 2000 -> Schematic Editor: The circuit diagram is drawn by loading components from the library. Wiring and proper net assignment has been made. The values are assigned for relevant components. EDWin 2000 -> Mixed Mode Simulator: The circuit is preprocessed. The waveform markers are placed at transformer primary, bridge output and detector output. The


Transient Analysis parameters have been set. The Transient Analysis is executed and output observed in the Waveform Viewer.




Current transformer Explained: A current transformer (CT) is a type of instrument transformer designed to provide a current in its secondary winding proportional to the alternating current flowing in its primary. They are commonly used in metering and protective relaying in the electrical power industry where they facilitate the safe measurement of large currents, often in the presence of high voltages. The current transformer safely isolates measurement and control circuitry from the high voltages typically present on the circuit being measured The most common design of CT consists of a length of wire wrapped many times around a silicon steel ring passed over the circuit being measured. The CT's primary circuit therefore consists of a single 'turn' of conductor, with a secondary of many hundreds of turns. The CT acts as a constant-current series device with an apparent power burden a fraction of that of the high voltage primary circuit. Hence the primary circuit is largely unaffected by the insertion of the CT. Common secondaries are 1 or 5 amperes. For example, a 40:5 CT would provide an output current of 5 amperes when the primary was passing 40 amperes. The secondary winding can be single ratio or multi ratio, with five taps being common for multi ratio CTs. Current transformers are used extensively for measuring current and monitoring the operation of the power grid. The CT is typically described by its current ratio from primary to secondary. Often, multiple CTs are installed as a "stack" for various uses (for example, protection devices and revenue metering may use separate CTs). Similarly potential transformers are used for measuring voltage and monitoring the operation of the power grid. Care must be taken that the secondary of a current transformer is not disconnected from its load while current is flowing in the primary, as the transformer secondary will attempt to continue driving current across the effectively infinite


impedance. This will produce a very high voltage across the open secondary (into the range of several kilovolts in some cases), which will compromise operator and equipment safety and may permanently affect the accuracy of the transformer



Simple Power supply circuit:


Basic C Language syntax for PIC microcontroller: In order to understand the basic C syntax for PIC microcontroller, an introduction to C in given below.

PUNCTUATORS The mikroC punctuators (also known as separators) include brackets, parentheses, comma, colon, and dot. Brackets Brackets [ ] indicate single and multidimensional may subscripts: dim alphabet as byte[ 30] alphabet[ 2] = "c" For more information, refer to Arrays. Parentheses Parentheses ( ) are used to group expressions, isolate conditional expressions, and indicate function calls and function declarations: d = c * (a + b) ' Override normal precedence if (d = z) then ... ' Useful with conditional statements

func() ' Function call, no args sub function func2(dim n as word) ' Function declaration For more information, refer to Operators Precedence and Associativity, Expressions, or Functions and Procedures. Comma The comma (,) separates the arguments in routine calls: Lcd Out (1, 1, txt) Further, the comma separates identifiers in declarations: dim i, j, k as word The comma also separates elements in initialization lists of constant arrays: const MONTHS as byte[12] = (31,28,31,30,31,30,31,31,30,31,30,31)


Colon Colon (:) is used to indicate a labeled statement: start: nop goto start For more information, refer to Labels. Dot Dot (.) indicates access to a structure member. For example: person.surname = "Smith" For more information, refer to Structures. Dot is a necessary part of floating point literals. Also, dot can be used for accessing individual bits of registers in mikroBasic.

PROGRAM ORGANIZATION MikroC imposes strict program organization. Below you can find models for writing legible and organized source files. For more information on file inclusion and scope, refer to Modules and to Scope and Visibility. Organization of Main Module Basically, main source file has two sections: declaration and program body. Declarations should be in their proper place in the code, organized in an orderly manner. Otherwise, compiler may not be able to comprehend the program correctly. When writing code, follow the model presented in the following page. Organization of Other Modules Units other than main start with the keyword module; implementation section starts with the keyword implements. Follow the models presented in the following two pages.

Main unit should look like this: program <program name> include <include other modules>


.******************************************************** '* Declarations (globals):

.******************************************************** symbols declarations symbol ... constants declarations const ... variables declarations dim ... procedures declarations sub procedure procedure name(...) <local declarations> end  sub functions declarations sub function function_ name(...) <local declarations> end  sub .******************************************************** '* Program body:

.******************************************************** main: ' write your code here end. Other units should look like this: module <module name> include <include other modules> .******************************************************** (globals): .******************************************************** symbols declarations symbol ... constants declarations const ... variables declarations dim ... procedures prototypes sub procedure procedure name(...) functions prototypes sub function function name(...) .******************************************************** '* Interface


* .******************************************************** implements constants declarations const ... variables declarations dim ... procedures declarations sub procedure procedure name(...) <local declarations> end  sub functions declarations sub function function_ name(...) <local declarations> end  sub end. SCOPE AND VISIBILITY Scope


The scope of identifier is the part of the program in which the identifier can be used to access its object. There are different categories of scope which depend on how and where identifiers are declared: If identifier is declared in the declaration section of a main module, out of any function or procedure, scope extends from the point where it is declared to the end of the current file, including all routines enclosed within that scope. These identifiers have a file scope, and are referred to as globals. If identifier is declared in the function or procedure, scope extends from the point where it is declared to the end of the current routine. These identifiers are referred to as locals. If identifier is declared in the interface section of a module, scope extends the interface section of a module from the point where it is declared to the end of the module, and to any other module or program that uses that module. The only exception are symbols which have scope limited to the file in which they are declared. If identifier is declared in the implementation section of a module, but not within any function or procedure, scope extends from the point where it is declared to the end of the module. The identifier is available to any function or procedure in the module.


Visibility The visibility of an identifier is that region of the program source code from which legal access can be made to the identifier's associated object. Scope and visibility usually coincide, though there are circumstances under which an object becomes temporarily hidden by the appearance of a duplicate identifier: the object still exists but the original identifier cannot be used to access it until the scope of the duplicate identifier is ended. Technically, visibility cannot exceed scope, but scope can exceed visibility.

MODULES In mikroBasic, each project consists of a single project file, and one or more module files. Project file, with extension . pbp contains information about the project, while modules, with extension . pbas, contain the actual source code. Modules allow you to:    break large programs into encapsulated modules that can be edited separately, create libraries that can be used in different projects, distribute libraries to other developers without disclosing the source code.

Each module is stored in its own file and compiled separately; compiled modules are linked to create an application. To build a project, the compiler needs either a source file or a compiled module file for each module Main Module Every project in mikroBasic requires single main module file. Main module is identified by the keyword program at the beginning; it instructs the compiler where to "start". After you have successfully created an empty project with Project Wizard, Code Editor will display a new main module. It contains the bare-bones of a program: program MyProject ' main procedure main: ' Place program code here


end. Other than comments, nothing should precede the keyword program. After the program name, you can optionally place the include clauses. Place all global declarations (constants, variables, labels, routines) before the label main. Note: In mikroBasic, the end. statement (the closing statement of every program) acts as an endless loop.

COMMENT Any text between an apostrophe and the end of the line constitutes a comment. May span one line only. Example: ‘Put your comment here! 'It may span one line only. LITERALS Character Literals Character literal is one character from the extended ASCII character set, enclosed by quotes. Example: "A" // this is character A

KEYWORDS absolute abs and array asm begin boolean case char chr clear const dim div float for function goto gosub if include in int integerstring interrupt is loop label or org print procedure program read select sub step switch then to until Note: User can not use keywords for variable or function names. Keywords are reserved only for making basic language statements.


do double else end exit

mod module new next not

wend while with xor

VARIABLES Syntax: dim identifier list as type Example: dim i, j, k as byte

CONSTANTS Syntax: const constant_name [as type] = value Example: const MAX as longint = 10000 const MIN = 1000 const SWITCH = "n" const MSG = "Hello" compiler will assume word type compiler will assume char type compiler will assume string type

LABELS Syntax: label identifier : statement

Example: loop: Beep goto loop infinite loop ' that calls the Beep procedure


PROCEDURES Syntax: sub procedure procedure_name(parameter_list) [ local declarations ] procedure body end sub Example: sub procedure add(dim byref c as byte, dim a, b as byte) c=a+b end sub

FUNCTIONS Syntax: sub function function_name(parameter_list) [ local declarations ] function body end sub Example: sub function add(dim a, b as ) result = a + b end sub
as ret urn_ type

Note: When we want the parameter to be changed in function or procedure body then we must declare that parameter with dim byref directive instead with dim directive. If declared with dim directive changes to the parameter will take effect only in that function or procedure.



Type byte char word short integer longint

Size 8-bit 8-bit 16-bit 8-bit 16-bit 32-bit

Range 0 .. 255 0 .. 255 0 .. 65535 - 128 .. 127 -32768 .. 32767 -2147483648..2147483647 ±1.17549435082 * 10-38 ±6.80564774407 * 1038



ARRAYS Syntax: type[array_length] Example: dim weekdays as byte[7] dim samples as word[10] now we can access elements of array variables, …. samples[0] =1

if weekdays[1] = 1 then samples[0] = 20 = 10

else samples[3] end if


…… STRINGS Syntax: string[string length] Example: dim msgl dim msg2 msgl = "First message" msg2 = "Second message" msgl = msg2 note: This is ok, but vice versa would be illegal (because length of string msgl is greater then length of string msg2)

POINTERS To declare a pointer data type, add a carat prefix (^) before type. For example, if you are creating a pointer to an integer, you would write:


Example: dim p as ^word p^ = 5 This will assign the pointed memory location value 5.

STRUCTURES Syntax: structure structname dim memberl as typel dim membern as typen end structure Example: structure Dot dim x as float dim y as float end structure



There are four types of operators in mikroBasic:  Arithmetic Operators  Bitwise Operators  Boolean Operators  Relational Operators

Operators Precedence and Associativity: Precedence 4 Operands 1 Operators not * div 2 1 2 2 = mod + <> + / and or < > << xor <= >= >> left-to-right left-to-right Associativity right-to-left Left-to-right



Arithmetic Operators: Operator + * / Operation addition subtraction multiplication division Precedence 2 2 3 3


di v mod

division, rounds down to nearest integer (cannot be used with floating points) returns the remainder of integer division (cannot be used with floating points)



Relational Operators Operator Operation equal <=> > < >= <= not equal greater than less than greater than or equal less than or equal Precedence 1 1 1 1 1 1

Bitwise Operators: Precedence

Operator and or xor

Operation bitwise AND; returns 1 if both bits are 1, otherwise bitwise returns (inclusive) OR; returns 1 if either or both bits

3 2

bitwise exclusive OR (XOR); returns 1 if 2 are 1, otherwise returns 0 the bits are complementary, otherwise 0


not << >>

bitwise complement (unary); inverts each bit bitwise shift left; moves the bits to the left, see below bitwise shift right; moves the bits to the right, see below

4 3 3

Boolean Operators: Operator Operation


logical AND


logical OR


logical exclusive OR


logical negation

These operators conform to standard Boolean logic. If used in conditional expressions they are compared with TRUE or FALSE.

Example: if (%1001 and %0111) = FALSE then LED1 = 1 else LED2 = 1 end if Because expression (%l 001 and %0111 ) gives % 0 001, when compared with FALSE (all zeros) it gives FALSE because they are not equal. It means that else statement will be executed and LED2 will be turned on. If it was written like this: if (%1001 and %0111) then LED1 = 1 else LED2 = 1 end if than expression (%1001 and % 0111) is compared with TRUE (all ones) by default. 61

CONDITIONAL STATEMENTS If Statement: Syntax: if expression then statements [else other statements] end if Example: if movex = 1 then x = x + 20 else y = y - 10 end if

Note: The else keyword with an alternate statement is optional. Select Case Statement Syntax: select case selector case value_1 statements_1 case value_n statements_n [case else default_statements] end select

Example: select case input case 1 LED1 = 1 case 2 LED2 = 1 case 3 LED3 = 1 case else LED7 = 1 end select


Note: This code will turn on LED depending of input value. If the value is different then ones mentioned in value list in case statement then else statement is executed by default.

ITERATION STATEMENTS (LOOPS) For Statement Syntax: for counter = initial_value to final_value [step step] statements next counter Example: s=0 for i = 0 to 4 s = s + 2 next i

While Statement Syntax: while expression statements end


Creating First Project in mikroC compiler for PIC: In this simple tutorial, we will create a new project, write some code and compile it in mikroBasic for PIC and test the results. Our project will make LED diodes blink, so it can be easily tested on PIC microcontrollers.





Interrupts handling in MikroC: Interrupts can be easily handled by means of reserved word interrupt. mikroBasic implictly declares procedure interrupt which cannot be redeclared. Write your own procedure body to handle interrupts in your application. mikroBasic saves the following SFR on stack when entering interrupt and pops them back upon return: PIC12 family: w, STATUS, FSR, PCLATH PIC16 family: w, STATUS, FSR, PCLATH PIC18 family: FSR (fast context is used to save WREG, STATUS, BSR) Note: mikroBasic does not support low priority interrupts; for PIC 18 family, interrupts must be of high priority. Routine Calls from Interrupt Calling functions and procedures from within the interrupt routine is now possible. The compiler takes care about the registers being used, both in "interrupt" and in "main" thread, and performs "smart" context-switching between the two, saving only the registers that have been used in both threads. The functions and procedures that don't have their own frame (no arguments and local variables) can be called both from the interrupt and the "main" thread.

Interrupt Examples: Here is a simple example of handling the interrupts from TMRO (if no other interrupts are allowed): sub procedure interrupt counter = counter + 1 TMRO = 96 INTCON = $20 end sub



1. B.L Theraja, Elecrical Technology 2. Muhammad Ali Maizidi,The 8051 microcontroller & Embeded Systems 3. Thedore F Bogart, Jr. Electric Circuits 4. PIC guide, 5. Adeel Anwar, Basic Electronics 6. Scott Machanzie, The 8051 Microcontroller



1. 2. 3. 4. 5.


To top