AN939 Designing Energy Meters with the PIC16F873A Author: Sandip Chattopadhyay Microchip Technology Inc. INTRODUCTION The deployment of electronic energy meters has gained a great deal of momentum over the past several years. This is due to their two main advantages over the traditional electromechanical designs: improved accuracy and an expanded set of features. Current microcontroller technology allows designers to build meters that are competitive in price with traditional devices, while maintaining the required IEC 1036 Class 1 accuracy of ±1% for domestic applications. Microcontrollers also allow the easy incorporation of added features, such as rms voltage and current and peak demand metering, as local electric utility companies desire to implement them. In this application note, we will discuss the implementation of a basic watthour meter using PICmicro® Flash microcontrollers. In the process, we will show how one ADC with a single sample-and-hold circuit can effectively measure both voltage and load current and maintain Class 1 accuracy. The firmware discussed measures and displays rms voltage and current, as well as kWh, presented in a clear digital format on an LCD. Besides basic energy measurement, this design also includes features that many electric utilities are very interested in rolling out on a wider basis. Dual-channel measurement provides a simple method for monitoring for tamper conditions. An on-board RTC provides a time source for calculating and tracking current and historical peak demand. All metered data is securely stored as it is updated in nonvolatile memory. The design discussed here uses the PIC16F873A and two Current Transformers (CTs) for current sensing. It can be implemented just as easily with the pin compatible PIC18F2320. Current measurement using a shunt may also be used in this design, with little or no change to the current amplifier design. © 2005 Microchip Technology Inc. PRINCIPLES OF MEASUREMENT Basically, a watthour meter is designed to measure energy or power consumed over time. In simple terms, electrical power is the product of voltage and current. If we make repeated measurements of both instantaneous voltage and current, or Vi and Ii, we can keep a running total of their products over time. By dividing the total accumulated energy over the number of samples, we have the average power (the first expression in Equation 1). Multiplying the average power by time gives the total energy consumed. EQUATION 1: CALCULATING AVERAGE ENERGY AND CONSUMED POWER ⎛ N ⎞ ⎜ Vi • Ii ⎟ Average Power ⎝ k = 1 k k⎠ = (watts) N Σ ⎛ N ⎞ ⎜ Vi • Ii ⎟ Energy Consumed ⎝ k = 1 k k⎠ (wattseconds) = Fs Σ For alternating current, such as that from the mains, average power also must account for power factor, which is the phase relationship between voltage and current. In simple terms, average AC power is V I cosθ, where V and I are average rms voltage and current, and θ is the phase angle between the two. Instantaneous sampling does not directly use power factor; the value of the phase angle is essentially embedded in the instantaneous current measurement. Recovering the actual phase angle for the purpose of calculating and displaying the power factor can be done separately and is very calculation intensive. If we are just measuring energy consumption, it is not necessary. DS00939A-page 1 AN939 To get an accurate picture of power consumption for an AC system, we need to make frequent measurements, preferably many times that of the supply frequency. In this application, we use a sampling rate of 400 Hz, which provides 8 samples per full cycle of the line frequency (for AC supply frequency of 50 Hz). For a sampling rate Fs, we get N samples in N/Fs seconds. By multiplying this expression for time by average power, we obtain an expression for energy consumed in terms of wattseconds (the second expression in Equation 1). From here, we can use simple math to calculate kilowatthours. Of course, it is difficult for a microcontroller to make direct measurements when the supply voltage is coming straight off the mains: say, 230V at up to 50A. This makes it necessary to indirectly measure line voltage and current at a level consistent with a microcontroller, then rescale these measurements to arrive at the original value. The best way to do this is to reduce the voltage to a level and dynamic range that is compatible with digital circuitry. (Measuring current here is essentially the same as measuring voltage, in that we will use a transducer that generates a voltage proportional to the load current.) The actual voltage and current readings can then be derived. For this application, the derived voltage reading, Vd, is related to the actual instantaneous line voltage Vi by the expression, Vd = Vi Kd/Kv or Vi = Vd Kv/Kd, where Kd is the digitization constant for the ADC in this application and Kv is the voltage proportionality constant for the circuit design. For this particular application, Kd is 204.6, the digital value from the ADC that represents 1V. Kv is the factor by which the input line voltage is reduced by a voltage divider; in our design, it is 300. Similarly, the derived current reading, Id, is related to Ii by the expression, Id = Ii Kd/Ki or Ii = Id Ki/Kd, where Ki is the current proportionality constant specific to this design; it is calculated by dividing the CT turn ratio by the product of the current amplifier gain and the input burden resistance. For this application, based on a 5000-turn CT, the value of Ki works out to be approximately 8.7. Kd is the same as before. Note: The calculation of Ki when using a shunt is somewhat different. The actual circuit design for current measurement, and the design considerations for using a shunt, are discussed in more detail in “Hardware Design”, starting on page 10. EQUATION 2: CALCULATING CONSUMED ENERGY FROM INDIRECT MEASUREMENTS ⎛ N ⎞ ⎜ Vd • Id ⎟ • (Kv • Ki) Energy Consumed ⎝ k = 1 k k⎠ (wattseconds) = Fs • Kd2 Σ We could accumulate a running total indefinitely and directly interpret it for energy consumed over time. However, it’s more practical to accumulate up to some fixed amount, then increment a counter to indicate energy consumption. For our application, we will accumulate 10 Wh (0.01 kWh) before incrementing the counter. This value represents the resolution limit of the meter. It is equivalent to 36,000 wattseconds (10 Wh x 60 x 60); this means that we increment the counter every time that the right side of Equation 2 reaches 36,000. We can also rearrange Equation 2 to define the power consumed entirely in terms of Vd and Id. Since we have already defined Fs, Kv, Ki and Kd in constant terms, we can give the whole quotient on the right side of the equation a constant value, D (Equation 3). EQUATION 3: REDEFINING POWER IN TERMS OF Vd AND Id ONLY When 0.01 kWh is consumed: N Σ V k=1 d • Id k k = 3600 • Fs • Kd2 =D Kv • Ki In simple terms, any time that the accumulated sum of the voltage and current products equals or exceeds D, we increment the kWh counter. We also save any remainder in excess of D to be used in the next round of accumulation. Note that anything which might influence the value of the constants may also affect the value of D and requires changes to the amplifier design. This includes the use of a shunt instead of a CT, or even changing the CT turn ratio, both of which may change Ki. By substituting the attenuated values of Vd and Id for the Vi and Ii in the original power measurement equation, we get an expression that relates the consumed power directly to the indirect voltage and current measurements, as shown in Equation 2. DS00939A-page 2 © 2005 Microchip Technology Inc. AN939 Sampling Voltage and Current Calibration Calculating power assumes that the voltage and current are sampled exactly the same time. Obviously, using a single ADC with one sample-and-hold circuit makes this impossible. We can do the next best thing, however, by using an interpolated voltage value that very closely approximates what the voltage would be when the current is sampled. The principle is graphically represented in Figure 1. Although current is shown here as a regular sine wave and in phase with voltage, this is not a requirement; current can have any waveform and phase relationship. To compensate for errors introduced by passive components, we need to individually calibrate the meter. We will discuss two varieties here: In this method, we assume that it takes some time t to sample an analog voltage and convert it to a digital value. If t is sufficiently small, we can use linear approximation to calculate the value exactly in the middle of an interval of 2t. We will work on the assumption that a segment of sine curve spanning 2° can be thought of as linear. For AC power in many countries, the frequency is 50 Hz; 2° represents an interval of about 111 μs. If we assume a practical conversion time of 35 μs, the time between voltage measurements would be 70 μs. This is about 1.26°, well within our margin for linearity. To calculate the voltage for a particular current measurement: 1. 2. Measure the first voltage sample at time t0. After an interval of t, measure the current (time t1). After another interval of t, measure the voltage again (time t2). Calculate the voltage at t1 as (Vdt0 + Vdt2)/2. 3. 4. The actual shape of the current waveform does not affect this calculation. FIGURE 1: INTERPOLATING VOLTAGE FOR A CURRENT SAMPLE V, I • Gain calibration, to compensate for gain errors (in Kv and Ki) introduced by normal variations in the values of different resistors, CT ratios and so on. • Phase calibration, to compensate for extraneous phase shifts introduced by the current measurement technique (from the CT, from the small but unwelcome inductance generated by a shunt and so on). GAIN ERROR CALIBRATION In theory, the proportionality and digitization constants should adequately calibrate the meter. In practice, individual component variations may cause differences between calculated and actual energy consumption. To account for this, we introduce a gain calibration factor, Cg, to Equation 3. This constant acts to adjust for changes in both Kv and Ki. The accumulated voltage/current sum is then compared to D, also adjusted by the calibration constant C (Equation 4). In theory, C and Cg are the same value. For practical applications, the two constants will have different values to reflect the actual calibration. This is discussed in more detail in “Firmware” (page 5). The value of Ki may also be slightly different at the extremes of the current measurement range. To account for this, we need two different gain calibration constants: one for the low end of the dynamic range and one for the upper end. In practice, this is done for each current measurement channel, for a total of four different values of Cg. The meter firmware chooses the appropriate value to use when a measurement is taken. EQUATION 4: GAIN CALIBRATION CONSTANT V Value for voltage here is calculated for the current sampling time Voltage is sampled at these points N ΣV k=1 Cg • d k • Id = C • D k Current is sampled halfway between voltages I 0° Interval of 2° or less © 2005 Microchip Technology Inc. 90° DS00939A-page 3 AN939 PHASE ERROR CALIBRATION Ideally, the relative size of measurement error should be fairly constant at various PFs, assuming that there is no phase error. In reality, the CTs introduce a small phase error that is generally constant in the amount of current lead or lag they create. The relative size the of measurement error can vary significantly with the power factor, however. If we calculate the percentage of error as ((cosθ) – PF)/PF) × 100), where θ is the angular difference between the theoretical phase difference and the error introduced by the CT, we can see that measurement error from a constant phase error is much greater at a 0.5 PF (lag) than at UPF. To show this, assume that a CT introduces a constant phase error of about 1°, regardless of the power factor. At UPF, the error is extremely small, on the order of -0.015% ((cos(1° – 0) – 1.0)/1.0). At 0.5 PF with a 60° lag, however, the error is significantly larger; as high as +3% ((cos(60° – 1°) – 0.5)/0.5). This is illustrated in Figure 2. To correct for this type of error, we can individually measure error at UPF and 0.5 PF to come up with a typical error for the entire range; this can be converted back to a fixed angular phase error and corrected by altering the time between the current sample and the next voltage sample. FIGURE 2: As an example, assume that a meter is found to have an error of +0.2% at UPF and +0.7% at 0.5 PF (current lag). The difference between the errors is +0.5%. From our previous equation, the angle x of the phase error at 0.5 PF would be: (cos(x) – 0.5)/0.5 = 0.005 cos(x) = 0.5025 or x is approximately 59.83°. This requires an additional lead of 0.17° to get to the desired phase angle of 60°, which translates to approximately 10 μs for a 50 Hz waveform. In practical terms, this means delaying the voltage measurement at t2 by 10 μs. If we assume that the time between individual conversions is 35 μs, this means that t2 is actually sampled at 45 μs. Note: If errors at UPF and 0.5 PF are equal in magnitude, phase error correction is not necessary. Using a CT by itself normally introduces a current lag, typically observed at between 2° to 3°. Introducing a capacitor across the CT, as was done in this design, provides a current lead that is correctable with timing adjustment. It is not necessary to quantify the amount of lead; as long as it is present, it can be measured indirectly through meter error and compensated. COMPARING MEASUREMENT ERRORS FOR A CONSTANT PHASE ERROR AT DIFFERENT POWER FACTORS At UPF: At 0.5 PF (lag): I I Current Lead introduced by Capacitor Measurement Error Phase Error V V Phase Error Actual Lag from Phase Error Voltage and Current in Phase DS00939A-page 4 Measurement Error Predicted Phase Lag at arccos (0.5) (60°) © 2005 Microchip Technology Inc. AN939 FIRMWARE A high-level overview of the energy metering firmware is shown in Figures 3 through 6. Before entering the main metering routine, the firmware initializes itself. Measurement buffers and Fault flags are cleared and the timers for the measurement routines are reset. If a calibration signal is present (done by setting a jumper), the firmware waits for calibration data on the serial port. If the signal is absent or no data is received, the data EEPROM is interrogated for a calibration flag. If this flag is set, the calibration data stored there is loaded for the firmware’s use. If no calibration data is present, default values in the firmware are used instead. Initialization also gives users the opportunity to perform a calibration routine, which downloads data from an external meter calibration utility through a serial connection. Details are provided in “Calibrating the Meter” (page 11). The main loop is responsible for updating the kWh counter and maintaining the visual display shown on the LCD. The kWh counter is incremented on the basis of a status flag, set in an interrupt driven power measurement routine, discussed below. A separate display timer is used to determine how long each measured value is displayed before rolling over to the next value. The default value for this application is 6.26s. An interrupt signal from an external RTC causes the firmware to compare the total energy consumed since the last interrupt to the value stored in data EEPROM and update the value if the consumed power is greater. This provides a record for tracking peak demand for one month. The default value for the interval is 30 minutes. Voltage and current measurement are performed during an interrupt service routine triggered by the Timer0 interrupt. Measurements are performed in a specific sequence, with the entire sequence being repeated every 2.5 ms. The measurement routine is an Interrupt Service Routine triggered by the Timer0 interrupt. Interleaving samples of voltage and current are taken, with the simultaneous voltage values for the current measurements being interpolated by the application. Calibrations for phase error are included in this calculation by using a delay counter to adjust the voltage readings; in this application, each increment of the counter delays the voltage reading by 1.4 μs (assuming a 20 MHz clock). The entire sequence of five measurements and their corresponding conversions takes much less time than the interval between sequences, typically less than 300 μs. To provide an added measure of accuracy, the offset voltage is periodically monitored to check for a stable baseline. This is done much less frequently than other measurements, approximately once every 1.25 seconds. Adjustments to the offset value, subtracted from voltage and current measurements, are made as needed. © 2005 Microchip Technology Inc. A single sampling sequence is taken during every interrupt routine. The accumulated energy to that point, adjusted by Cg, is compared with the values for D x C, as well as a fraction of the D xC equivalent to 1/3200 kWh. Prior to calibration, the application uses a value of 200 for both C and Cg. After calibration, Cg may change to compensate for gain inaccuracies; C remains at 200. An increment or decrement of one in Cg can be used to compensate for a deviation of ±0.5%. Increasing Cg compensates for negative deviations, while decreasing it compensates for positive deviations. In practical terms, the adjustment range possible runs from -25 to +100%. If the accumulated value exceeds 1/3200 kWh, an external signal is generated for calibration purposes. If the energy equals or exceeds the adjusted value of D, the kWh flag is set; this will cause the kWh counter to be incremented by one during the next execution of the main loop. For amounts exceeding D, the difference between the energy buffer and D is saved and added to the next round of accumulation. The ISR executes a housekeeping routine once every 20 interrupts to monitor for other conditions that may affect the energy reading. These include current channel amplifier gain, ground Faults, negative accumulated value and noise. Because of the large dynamic range for load current, a selectable gain amplifier is used to match the current range to the range of the ADC. The gain is controlled by summing the current for 2½ cycles of the supply frequency. If the value exceeds an equivalent of 3A, the amplifier’s gain is switched to low. If the value falls below an equivalent of 2.8A, the gain is switched to high. The small overlap between switching thresholds provides a built-in hysteresis, which prevents constant switching between gain states. The same summed values are also compared for differences. If the line current exceeds the neutral current by 8% or more, a ground Fault is indicated. When this happens, the meter switches from metering on the neutral current (the default) to the line current. An external signal is also sent to indicate a possible tamper condition. Also included in the measurement routine is logic to handle reverse-current conditions. Although the energy calculations involve signed operations, the result of the calculation after 2½ cycles should always be positive. This assumes that the current sensors are connected to produce voltage and current signals in phase (or nearly so) at Unity Power Factor (UPF). If this is properly done, the accumulated energy will always be positive, even across a PF range from 0.5 lag to 0.8 lead. Nevertheless, a reverse-current condition, where voltage and current are 180° out of phase, will still produce a negative accumulated energy result. If this happens, a flag is set to permit the energy algorithm to produce a correct (positive) result from the next cycle onward. DS00939A-page 5 AN939 The algorithm also examines the contents of the intermediate results buffers and clears them if the values fall below a certain value. This prevents line and circuit noise from being mistakenly interpreted as actual power consumption. FIGURE 3: ENERGY METER FIRMWARE (INITIALIZATION ROUTINE) START Initialize System Detail Initialize System Initialize RAM (Calibration Routine) Calibrate now? Y A Initialize ADC and I/O Ports N Y Is system calibrated? Load Calibration Data from Data EEPROM Initialize Interrupts N Load Default Calibration from Program Memory Set RTC for 30 Minute Alarm Clear SAMPLE and OFFSET_CNT Buffers Initialize GAIN, EARTH, REVERSE and OFFSET Flags Initialize LCD to Display Power-on Values from EEPROM Start Timer0 B DS00939A-page 6 (Main Program Loop) © 2005 Microchip Technology Inc. AN939 FIGURE 4: ENERGY METER FIRMWARE (MAIN PROGRAM LOOP AND CALIBRATION ROUTINE) Main Loop Calibration routine B A Is kWh flag true? N Initialize USART Y Increment kWh Counter and Store in EEPROM Send Calibration Request to GUI Receive Calibration Data from GUI N Has display counter elapsed? Y Display Next Parameter on LCD N Store Calibration in Data EEPROM Has demand timer elapsed? Y Compute Maximum Demand and Store in Data EEPROM All data received? N Y Disable USART RETURN © 2005 Microchip Technology Inc. DS00939A-page 7 AN939 FIGURE 5: ENERGY METER FIRMWARE (ENERGY MEASUREMENT INTERRUPT ROUTINE) Sample Voltage and Current Timer0 Interrupt Read Voltage at Time 1 (V1) Is OFFSET true? Y Read OFFSET from ADC, Set OFFSET to False N Sample Voltage Read Phase Current (CP) and Current Read Voltage at Time 2 (V2) Calculate Power Read Neutral Current (CN) (Gain and Fault Handling) Have 20 samples been taken? Y C Read Voltage at Time 3 (V3) N Calculate Power Is Total ≥ 1/3200 kWh? Y Toggle Calibration Pulse and LED Calculate VP and VN from V1, V2 and V3 N Is Y Total ≥ 0.01 kWh? Set kWh Flag to True N Adjust for Gain and Calibration Values Increment OFFSET_CNT Is OFFSET_CNT = 65536? Calculate Signed Values for Voltage and Current Accumulate CN and CP in CACCN and CACCP Buffers Y Set OFFSET to True Integrate Energy according to EARTH and REVERSE Flags N Return from Interrupt DS00939A-page 8 Store Energy Value in DECISION and TOTAL Buffers © 2005 Microchip Technology Inc. AN939 FIGURE 6: ENERGY METER FIRMWARE (GAIN AND FAULT HANDLING ROUTINE) C Are CN and CP unequal? Y Set EARTH Flag to True Y Toggle REVERSE Flag Y Set Amplifier Gain to Low Y Set Amplifier Gain to High N Set EARTH Flag to False Is sign of DECISION negative? N Does current exceed high limit? N Is current below low limit? N Is Y integrated energy very low? Clear Buffer N Clear DECISION and Current Buffers Return to ISR © 2005 Microchip Technology Inc. DS00939A-page 9 AN939 HARDWARE DESIGN The conceptual design for the energy meter is shown in Figure 7; a more detailed schematic is presented in Appendix A: “Schematics”. As previously noted, this design was prototyped using the PIC16F873A. Users may also implement this design without modification using the pin-compatible PIC18F2320, if desired. Line voltage and current are sampled sequentially at regular intervals, with voltage and current being presented to different analog input channels. To measure voltage, the AC line is sampled across a potential divider, R19 and R20, which divides the input voltage by about 300. For current measurement, two current transformers create voltage signals across burden resistors (R8 and R9) that are proportional to the load current. As the core design of the energy meter will accommodate different types of transducers, the CTs themselves are not shown on the schematic. Regardless of the sensor used, current is measured sequentially on both line and neutral, alternating with voltage measurements. Measuring both currents is necessary for detecting ground Faults and error conditions. An analog switch selects between the appropriate channels and ground. A fixed offset of approximately 2V is added to both the current and voltage signals. This maintains the signal well above VSS, which is an operating requirement of the microcontroller’s ADC. By itself, the ADC does not have the dynamic range or resolution to perform the necessary measurements. For the current signal, an amplifier with two selectable gain stages follows the analog switches; it is used to compensate for the wider dynamic range of the current sample. The application firmware senses if the amplified current signal is above or below the ADC’s capabilities and automatically adjusts the gain accordingly. Single stage FIGURE 7: gain is set by the values of R5, R6 and R7; together with the turn ratio of the CT and the value of the burden resistors, these determine the value of the current proportionality constant, Ki. (For reference, the formula is Ki = ((CT Ratio)((R5 + R6)/R7)/(R8 or R9).) The microcontroller controls the amplifier gain through an analog switch. Energy consumption is calculated as previously described in the “Firmware” section. Whenever the energy is incremented by ten counts (i.e., 0.1 kWh), the value is also stored in EEPROM as well. In the event of a power failure and subsequent recovery, the previously accumulated energy is retrieved and accumulation resumes from that value. An external Real-Time Clock (RTC) is used to generate an interrupt signal every 30 minutes. This is the external timing source for peak demand period calculations discussed previously. The RTC can also be used to implement other time/date functions. Information on energy consumption is sent over a 4-wire interface to an external LCD with integrated controller. The current version of the application firmware displays cumulative energy use to date, as well as several other parameters, in a continuous rollover fashion. Four indicator LEDs are provided to indicate Fault and calibration states. The kWh LED flashes each time that 1/3200 kWh (0.3125 Wh) is consumed, producing an optical signal that test equipment can use for meter calibration. The other LEDs indicate normal operation, reverse-current operation and ground Fault (tamper) conditions. The core hardware design also includes a serial (RS-232) interface for calibration. The data lines are electrically isolated from the rest of the meter circuitry to reduce the risk of damage to external equipment. CONCEPTUAL BLOCK DIAGRAM OF THE ENERGY METER Communication/Control PIC16F873A PIC18F2320 Measurement 4 AC Fail Numeric LCD with Controller Attenuation 3 Voltage ADC Transistor Switch Selectable Gain Amplifier 2 LEDs RTC Line Current Neutral Current Calibration 2 Control from Firmware Serial Port Calibration Jumper DS00939A-page 10 © 2005 Microchip Technology Inc. AN939 Design Considerations with Shunt Measurement When substituting a shunt for current measurement, the value of Ki is calculated as the reciprocal of the product of the shunt resistance and the amplifier gain. For example, a shunt of 0.005 ohm used with the same amplifier circuit will also produce approximately the same value of Ki (around 9.3). However, IEC specifications call for a power loss of less than 2W in the measurement circuit. At the design voltage and current, this would mean using a shunt smaller than 0.0001 ohm. To compensate, the amplifier gain would have to be increased by reducing R7, which would create different gain requirements for the CT and shunt circuits. Since a single amplifier is used for both current channels, combining shunt and CT measurement may not be possible in this design. Tamper Proofing and Current Measurement As already noted, the energy meter design measures both the phase and neutral currents. Measuring two current channels allows for tamper Fault detection. If tampering is indicated, the meter will automatically measure and calculate usage from the leg with the higher load current. The threshold for detection is set in the firmware at an 8% difference between the two channels. It is possible to configure the meter to use only one CT and a single current measurement channel. Doing this will disable tamper detection. Provisions are made in the firmware to bypass the tamper detection feature. If a shunt is used for current measurement, only one current measurement channel is available. As before, doing this disables tamper protection. CALIBRATING THE METER The firmware contains a default set of values for the meter calibration constants. These values assume the use of CTs to measure current and are based on the prototype design. Using different current sensors (shunts or Hall sensors), in addition to component variations in individual devices, may require individual meter calibration to account for intolerance variations and phase error from sensors. To perform calibration, it will be necessary to use the Meter Calibration Software provided with the firmware. Users must also have access to a watthour meter test stand, or other system that can provide power at fixed current levels and power factors. The calibration software uses inputs provided by the user to calculate the gain calibration constant, Ki, for both current channels, for both low-gain and high-gain settings of the current amplifier. In addition, it calculates the phase error and required timing correction from the same inputs. The calibration data is then downloaded to the meter through a serial (RS-232) interface. The software is designed to run on desktop or laptop computers under any 32-bit version of Microsoft® Windows® operating system. The computer must also have an available serial port. FIGURE 8: CALIBRATION SCREEN FOR THE METER CALIBRATION SOFTWARE © 2005 Microchip Technology Inc. DS00939A-page 11 AN939 To calibrate the meter: 1. 2. 3. 4. 5. Connect the meter to a test stand or other system, following the equipment manufacturer’s directions. Measure and record the signed error between the meter and the test equipment on both current channels (CT1 and CT2) for each of these parameters: • 1A supply at UPF • 10A supply at UPF • 10A supply at a power factor with 0.5 lag (60 degree current lag) Launch the Meter Calibration Software. At the main screen, click on Calibration. The Calibration window appears (Figure 8). Enter the six error measurements in the places indicated. Click on the Process button. The software will automatically calculate and display the proper calibration values. At this point, you should also set the meter serial number and date and time to be downloaded, as well as the serial port to be used. Disconnect the meter from the test stand. Connect it to a power source and to the computer using a standard DB9 serial cable. Note: 6. 7. 8. While the meter’s serial data port is isolated from the rest of the meter circuitry, the meter ground is not. This poses a potential risk to the computer and the user. When performing any calibration, always run the computer on a power source that does not share a ground with the meter. The best option is to run the computer from a battery. Place a jumper across JP1 to enable calibration. Click on the Connect button. The software automatically connects to the meter, which downloads the calibration data and stores it in data EEPROM. The progress of the data connection and download is displayed in the lower right-hand corner of the window. When complete, the software displays “Calibration Complete”. Remove the calibration jumper. Disconnect the serial cable. DS00939A-page 12 RESOURCE USAGE Although the energy meter design provides both basic and additional special features, other features may be required by a particular customer. This implementation provides additional room, both in terms of memory and hardware resources, to expand the application to the customer’s needs. A summary of the resources used for the basic PIC16F873A device-based design is provided in Table 1. TABLE 1: RESOURCES USED BY ENERGY METER FIRMWARE (PIC16F873A VERSION) Resource Used by Application Program Memory (words) 3.5K RAM (bytes) 190 Data EEPROM (bytes) 78 I/O Pins 22 Timer Resources ADC Channels 1 (Timer0) 2 CONCLUSION Implementing a electronic watthour meter with a microcontroller should be a straightforward exercise in design. The PIC16F873A and PIC18F2320 microcontrollers provide a cost-effective way to implement a metering solution with a low part count. Simple current and voltage sampling techniques yield a design that meets Class 1 accuracy for residential metering requirements, while delivering additional features, such as peak demand tracking and tamper detection. All of this can be achieved without sacrificing cost competitiveness. © 2005 Microchip Technology Inc. AN939 APPENDIX A: ENERGY METER, SCHEMATIC, PART 1 (MICROCONTROLLER, RTC, LCD INTERFACE AND LEDs) PIC16F873A VSS 33 pF .01 μF VCC 10K VCC VSS VCC VCC VCC VCC VCC VCC .01 μF VDD VSS 33 pF 32 kHz 33 pF C8 VCC FIGURE A-1: SCHEMATICS © 2005 Microchip Technology Inc. DS00939A-page 13 AN939 8 9 10 13 12 C D 7 6 5 B A 2 1 4 VCC- 8 6 3 7 680 pF VCC 12 33 pF 11 13 1 A C A C B B 2 10 4 B 5 3 AC VCC .01 μF VCC 6 8 2 C A VCC B 5 9 VCC VCC 3 14 ENERGY METER SCHEMATIC, PART 2 (CURRENT AND VOLTAGE SAMPLING, OFFSET GENERATION, GAIN AMPLIFIER AND SERIAL CALIBRATION INTERFACE) 1 FIGURE A-2: DS00939A-page 14 © 2005 Microchip Technology Inc. AN939 ENERGY METER SCHEMATIC, PART 3 (POWER SUPPLY) 230V, 50 Hz AC 1 μF OPTIONAL 22 nF VCC- 1000 μF .1 μF 1 μF .1 μF VCC 1000 μF FIGURE A-3: © 2005 Microchip Technology Inc. DS00939A-page 15 AN939 APPENDIX B: SOFTWARE DISCUSSED IN THIS APPLICATION NOTE For the sake of brevity, a complete listing of the energy meter firmware discussed in this document is not provided here. The complete application, along with the accompanying Meter Calibration utility software, may be downloaded from the Microchip corporate web site at: www.microchip.com DS00939A-page 16 © 2005 Microchip Technology Inc. Note the following details of the code protection feature on Microchip devices: • Microchip products meet the specification contained in their particular Microchip Data Sheet. • Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions. • There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchip’s Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property. • Microchip is willing to work with the customer who is concerned about the integrity of their code. • Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as “unbreakable.” Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our products. Attempts to break Microchip’s code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act. Information contained in this publication regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip’s products as critical components in life support systems is not authorized except with express written approval by Microchip. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights. Trademarks The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KEELOQ, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC, and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, Migratable Memory, MXDEV, MXLAB, PICMASTER, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, MPASM, MPLIB, MPLINK, MPSIM, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel and Total Endurance are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. © 2005, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved. Printed on recycled paper. Microchip received ISO/TS-16949:2002 quality system certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona and Mountain View, California in October 2003. The Company’s quality system processes and procedures are for its PICmicro® 8-bit MCUs, KEELOQ® code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchip’s quality system for the design and manufacture of development systems is ISO 9001:2000 certified. © 2005 Microchip Technology Inc. DS00939A-page 17 WORLDWIDE SALES AND SERVICE AMERICAS ASIA/PACIFIC ASIA/PACIFIC EUROPE Corporate Office 2355 West Chandler Blvd. Chandler, AZ 85224-6199 Tel: 480-792-7200 Fax: 480-792-7277 Technical Support: http://support.microchip.com Web Address: www.microchip.com Australia - Sydney Tel: 61-2-9868-6733 Fax: 61-2-9868-6755 India - Bangalore Tel: 91-80-2229-0061 Fax: 91-80-2229-0062 China - Beijing Tel: 86-10-8528-2100 Fax: 86-10-8528-2104 India - New Delhi Tel: 91-11-5160-8631 Fax: 91-11-5160-8632 Austria - Weis Tel: 43-7242-2244-399 Fax: 43-7242-2244-393 Denmark - Ballerup Tel: 45-4450-2828 Fax: 45-4485-2829 China - Chengdu Tel: 86-28-8676-6200 Fax: 86-28-8676-6599 Japan - Kanagawa Tel: 81-45-471- 6166 Fax: 81-45-471-6122 France - Massy Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79 China - Fuzhou Tel: 86-591-8750-3506 Fax: 86-591-8750-3521 Korea - Seoul Tel: 82-2-554-7200 Fax: 82-2-558-5932 or 82-2-558-5934 Germany - Ismaning Tel: 49-89-627-144-0 Fax: 49-89-627-144-44 Atlanta Alpharetta, GA Tel: 770-640-0034 Fax: 770-640-0307 Boston Westford, MA Tel: 978-692-3848 Fax: 978-692-3821 Chicago Itasca, IL Tel: 630-285-0071 Fax: 630-285-0075 Dallas Addison, TX Tel: 972-818-7423 Fax: 972-818-2924 Detroit Farmington Hills, MI Tel: 248-538-2250 Fax: 248-538-2260 Kokomo Kokomo, IN Tel: 765-864-8360 Fax: 765-864-8387 China - Hong Kong SAR Tel: 852-2401-1200 Fax: 852-2401-3431 China - Shanghai Tel: 86-21-5407-5533 Fax: 86-21-5407-5066 China - Shenyang Tel: 86-24-2334-2829 Fax: 86-24-2334-2393 China - Shenzhen Tel: 86-755-8203-2660 Fax: 86-755-8203-1760 China - Shunde Tel: 86-757-2839-5507 Fax: 86-757-2839-5571 Singapore Tel: 65-6334-8870 Fax: 65-6334-8850 Taiwan - Kaohsiung Tel: 886-7-536-4818 Fax: 886-7-536-4803 Taiwan - Taipei Tel: 886-2-2500-6610 Fax: 886-2-2508-0102 Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781 Netherlands - Drunen Tel: 31-416-690399 Fax: 31-416-690340 England - Berkshire Tel: 44-118-921-5869 Fax: 44-118-921-5820 Taiwan - Hsinchu Tel: 886-3-572-9526 Fax: 886-3-572-6459 China - Qingdao Tel: 86-532-502-7355 Fax: 86-532-502-7205 Los Angeles Mission Viejo, CA Tel: 949-462-9523 Fax: 949-462-9608 San Jose Mountain View, CA Tel: 650-215-1444 Fax: 650-961-0286 Toronto Mississauga, Ontario, Canada Tel: 905-673-0699 Fax: 905-673-6509 10/20/04 DS00939A-page 18 © 2005 Microchip Technology Inc.