Single Phase Energy Meter using XMEGA A

APPLICATION NOTE
Atmel AVR1631: Single Phase Energy Meter using
XMEGA A
8-bit Atmel Microcontroller
Features
•
•
•
•
•
•
•
•
•
•
Low-cost, Class 1 single-phase energy meter solution
Low and cost effective capacitive power supply
External low frequency crystal for RTC
Battery backup for internal RTC
LCD interface through GPIO
Multiple tamper detection
Multiple measurement parameters
One-time, quick, and accurate digital calibration gives added benefits
Internal EEPROM to store calibration parameters, tamper info, etc.
External EEPROM interface
Figure 1.
Energy meter hardware.
42039A−AVR−11/2012
Table of contents
2. Specification ......................................................................................... 3 3. Energy meter ....................................................................................... 4 3.1 Overview ........................................................................................................... 4 3.2 Power supply..................................................................................................... 5 3.3 Analog front end ................................................................................................ 6 3.4 Signal conditioning (anti-alias filter)................................................................... 6 3.5 Analog to Digital Conversion (ADC) .................................................................. 7 3.6 Cross talk/noise elimination .............................................................................. 7 3.7 Microcontroller................................................................................................... 7 3.8 Principles of measurements .............................................................................. 8 3.8.1 AveragePower calculation .................................................................. 8 3.8.2 Energy calculation .............................................................................. 8 3.8.3 Voltage and current calculation ........................................................... 8 3.8.4 ApparentPower and PowerFactor calculation ..................................... 9 4. Atmel AVR1631 ................................................................................. 10 4.1 Overview ......................................................................................................... 10 4.2 Hardware ........................................................................................................ 10 4.2.1 Capacitive power supply ................................................................... 11 4.2.1.1 Theory ............................................................................. 11 4.2.1.2 Surge protection.............................................................. 11 4.2.2 Analog front end ............................................................................... 12 4.2.3 Voltage front end .............................................................................. 12 4.2.4 Current front end ............................................................................... 13 4.2.5 Microcontroller .................................................................................. 13 4.2.6 LCD driver interface .......................................................................... 14 4.2.7 Signal LED’s ..................................................................................... 15 4.2.8 Programming and debugging interface (PDI).................................... 15 4.2.9 Serial communication interface ......................................................... 16 4.2.10 Battery backup interface ................................................................... 16 4.3 Firmware architecture ..................................................................................... 17 4.3.2 System initialization .......................................................................... 18 4.3.3 ADC sampling ................................................................................... 21 4.3.4 Multiply-accumulate of samples ........................................................ 21 4.3.5 Basic energy and instantaneous parameters calculation .................. 25 4.3.6 Calibration pulse output generation .................................................. 26 4.3.7 Line frequency calculation ................................................................ 27 4.3.8 LCD display ...................................................................................... 27 4.3.9 Tamper detection logics .................................................................... 28 4.3.10 Low-power mode implementation ..................................................... 30 4.4 Calibration procedure ...................................................................................... 31 Appendix A. LCD timing diagram ....................................................... 36 Appendix B. Revision history ............................................................. 38 Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
2
1.
Description
This application note describes single-phase electronic energy meter with tamper detection logic. The reference design
developed with Atmel® AVR® ATxmega32A4U microcontroller designed to support the following specification.
2.
Specification
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Design meets Class 1 accuracy as per Iec/Is standard
Nominal voltage: 240V (Vref)
Nominal current: 5A (Ibasic)
Maximum current: 40A (Imax)
The operating range of voltage 0.6Vref to 1.2Vref
Easy change of meter constant through firmware as per requirement
Power frequency range: 45Hz to 65Hz
Power factor: 0 lag to unity to 0 lead
Running with no load and (-)70% to 120% voltage: No creeping
Starting current at which meter shall run and continue to run: 0.4% of Ib.
Sensor: Primary side shunt for measurement and secondary side Ct
Accurate even under rapid current fluctuation
Tamper proof design
Meter records correct energy with same accuracy under reverse current connection
Earth load tamper detection
Reverse current detection and logging
Magnetic tamper proof and logging
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
3
3.
Energy meter
3.1
Overview
An energy meter measures the amount of electrical energy supplied to a residential or commercial building. The most
common unit of measurement made by a meter is the kilowatt hour, which is equal to the amount of energy used by a
load of one kilowatt in one hour. Figure 3-1 shows a system block diagram for a single-phase energy meter.
As shown the energy meter hardware includes a power supply, an analog front end, a microcontroller section, and an
interface section. The analog front end is the part that interfaces to the high voltage lines. It converts high voltages and
high currents to voltages sufficiently small to be measured directly by the ADC (Analog/Digital Converter) of the
microcontroller. The amount of amplification required depends on the ADC resolution as well as the Class accuracy
required for a single-phase meter.
The heart of the meter is the MCU, which calculates active, reactive and apparent energy based on voltage and current
measurement. The ADC samples the analog input voltage, current signals and converts into digital form. The digital
samples are given to MCU for calculating energy. The MCU accumulates the products of voltage and current samples
over a time. The active power is calculated by dividing this accumulated value by the number of samples. Multiplying
the active power by time gives the active energy consumed.
The MCU will update the LCD driver to display the calculated the energy in LCD display for the billing purpose. The
readings can also be transmitted to remote places through electrically connected medium like RS232/RS485 or through
optically isolated medium. This will enable the remote billing.
The MCU will also generate the pulse output proportional to the measured active energy with the rate of imp/kWh. This
pulse output can be used to measure the accuracy of the measured energy by comparing with the reference meter at
short interval of time.
The typical energy meter also requires a Real Time Clock (RTC) for tariff information. The RTC for metering application
should be very accurate. This involves dividing the day, month and year into tariff slots (Time of Day). Higher rates are
applied at peak load periods and lower tariff rates at off-peak load periods.
The energy meter needs to be calibrated before it can be used and that is done in a digital domain for an electronic
energy meter. Digital calibration is fast, efficient and can be automated, removing the time-consuming manual trimming
required in traditional, electromechanical meters. Calibration coefficients are safely stored in an EEPROM.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
4
Figure 3-1. Block diagram of single-phase energy meter.
3.2
Power supply
There are several ways to convert an AC voltage into the DC voltage required by a microcontroller. Traditionally, this
has been done with a transformer and rectifier circuit. There are also switching power supply solutions. Electronic
energy meter application involves providing DC voltage to only the microcontroller and a few other low-current devices.
Transformer-based or switcher-based power supplies may not be cost effective.
The transformers in transformer-based solutions and the inductor/MOSFET/controller in switch-based solutions are
expensive and take up a considerable amount of space. The cost and size of the components surrounding the power
supply may be significantly less than the cost of the power supply alone in a meter. Hence care must be taken while
choosing the power supply.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
5
3.3
Analog front end
Figure 3-2.
Analog front end.
There are various methods for sensing current and voltage, each with their own tradeoffs. The voltage is scaled down to
the range of the ADC by resistor dividers. The current is measured by current transducer. The current transducer Shunt
or CT both have their own advantages and disadvantages.
The voltage drop across the shunt in proportional to the current being drawn by the load. This voltage drop is taken as a
current input signal. As the shunt is in series with the load, it should be in µΩ. The shunt resistor gives the voltage drop
in milli-Volts. In a noisy environment it requires precision filtering and amplification circuitry prior to delivery to the ADC
to measure accurately.
Current can also be measured by Current Transformers (CT). CT can also provide galvanic isolation from the primary.
Current transformers are based on magnetic cores that can saturate and exhibit a nonlinear phase response. This can
cause power or energy measurement errors at low currents and large power factors. This requires corresponding
phase-correction functionality in the downstream signal chain.
3.4
Signal conditioning (anti-alias filter)
As per Nyquist sampling theorem the maximum frequency of the input signal should be less than or equal to half of the
sampling rate. Input signal may pickup stray signals (such as the power line frequency) could contain frequencies
higher than the Nyquist frequency. These frequencies may then alias into the appropriate frequency range and thus
give erroneous results.
To be sure that the frequency content of the input signal is limited, an anti-aliasing filter (a filter that passes low
frequencies but attenuates the high frequencies) is added before the ADC.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
6
3.5
Analog to Digital Conversion (ADC)
The electronic energy meter relies on an analog-to-digital conversion. This is done by Analog to Digital Converter
(ADC). The ADC takes samples or “snap shots” of the analog signals at discrete instances of time. These “snap shots”
or discrete time signals are in turn converted to numeric values by the ADC as shown in Figure 3-3.
Figure 3-3. Analog to digital conversion.
The ADC requirements for energy metering are:
3.6
•
The relatively wide dynamic range and the accuracy requirements of the application, the resolution of the ADC
needs to be high resolution
•
A Sampling rate of at least 2 to 4kSPS (kilo Samples Per Second) is required. A basic rule of sampling theory
states that the rate (frequency) of sampling must be at least twice the highest frequency content of the signal.
This is called the Nyquist rate. Energy metering specifications call for accurate measurement of frequency
content up to the 20th harmonic which is 1kHz or 1.2kHz depending on the line frequency
•
•
Low cost. The solution must be low cost because the energy metering application is particularly cost sensitive
The ADC must not consume excessive power. One of the challenging aspects of solid state meter design is
the design of the power supply unit
Cross talk/noise elimination
Voltage front end handles voltages of considerable amplitude, which makes it a potential source of noise. Disturbances
are readily emitted into current measurement circuitry, where it will interfere with the actual signal to be measured.
Typically, this shows as a non-linear error at small signal amplitudes and non-unity power factors. At unity power factor,
voltage and current signals are in phase and crosstalk between voltage and current channels merely appears as a gain
error, which can be calibrated. When voltage and current are not in phase crosstalk will have a non-linear effect on the
measurements, which cannot be calibrated. Current signals with low amplitude are amplified before being sampled and
processed, which means any noise in the signal will be enlarged.
Crosstalk and noise can be minimized by means of good PCB planning and the proper use of filter components.
3.7
Microcontroller
The microcontroller serves all the required energy measurement tasks and interacting with the other components;
EEPROM, the display and the serial communication interface. Besides low cost, the basic microcontroller requirements
are sufficient I/O to drive the external LED’s, built-in serial interface to external LCD driver/EEPROM and timers and
external interrupts. As an added feature, a serial interface should be there to communicate with a host system for
remote/automated metering. Also, either an external or internal clock could be used to implement multi-rate metering.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
7
3.8
Principles of measurements
3.8.1
AveragePower calculation
Figure 3-4. AveragePower / Energy in digital domain.
Electrical power is the product of voltage and current. The ADC gives the voltage and current analog signal inputs in the
form of digital samples. The accumulation of voltage (V[n]) and current (I[n]) samples products over a time and then
dividing the total accumulated value by the number of samples (N) gives average power.
N −1
Equation 3.1.
AveragePower =
∑ (V [n] * I [n])
n =0
N
For alternating current, average power must also account for power factor, which is the phase relationship between
voltage and current. Active AC power is V * I* cosθ, where V and I are voltage and current RMS, and θ is the phase
angle between the two. The value of the phase angle is essentially embedded in the voltage and current samples.
Hence, the actual phase angle calculation may only be required for the purpose of calculating and displaying the power
factor.
3.8.2
Energy calculation
It is required to make frequent measurements to get an accurate value of energy consumption of an AC system. The
sampling rate Fs should be many times that of the supply frequency. If N is total samples in N/Fs seconds, Energy in
terms of watt seconds can be obtained by multiplying N/Fs with the average power.
N −1
Equation 3.2.
3.8.3
Energy =
∑ (V [n] * I [n])
n=0
Fs
Voltage and current calculation
An RMS value is defined as the square root of the mean value of the squares of the instantaneous values of a
periodically varying quantity, averaged over one complete cycle. The discrete time equation for calculating Vrms is as per
Equation 3.3.
N −1
Equation 3.3.
Vrms =
∑ (V [n] *V [n])
n=0
N
Irms is calculated using the same equation by substituting current samples, I[n] instead V[n].
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
8
3.8.4
ApparentPower and PowerFactor calculation
ApparentPower can be calculated by multiplying the instantaneous voltage and instantaneous current as per Equation
3.4.
Equation 3.4.
ApparentPower = Vrms * I rms
PowerFactor can be derived from Active/AveragePower and the ApparentPower.
Equation 3.5.
PowerFactor =
AveragePower
ApparentPower
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
9
4.
Atmel AVR1631
4.1
Overview
AVR1631 single-phase energy meter design is based on the Atmel XMEGA® A4U microcontroller. This design is a lowcost solution considering the entire requirement for low-cost energy meter discussed in the previous sections. The block
diagram of the AVR1631 single-phase energy meter is shown in Figure 4-1.
Referring to Section 3.5 for the ADC requirements for energy meter, ADC should be low cost, capable of sampling at
faster rate, measures relatively wide dynamic range and low current consumption. The design uses the internal 12-bit
ADC and flexible gain stages to measure wide range of currents from 0.4% of basic current (Ibasic) to maximum current
(Imax). The ADC is capable of converting up to two million samples per second. Differential measurement with gain stage
is available inside to XMEGA A4U microcontroller which increases the dynamic range. Hence external gain amplifier
and level shifter for negative signal is not required. This will reduce the product cost.
This design uses two current measuring elements to measure active power in both forward and return paths of current.
This enables the meter to detect, indicate, and continue to measure reliably even when subject to external attempts of
tampering. The meter is easily configured to fit any other voltage and current settings. The design is tested for the
accuracy with wide range of voltages, frequencies and power factor.
Automated digital calibration is implemented in this design. The internal EEPROM of XMEGA A4U is used to store
calibration coefficients and other logging data. This will avoid the requirement of external EEPROM.
The brain of the meter is the firmware, which is provided open source. Although it includes all the functionality required
for a single-phase meter, it can be modified and updated at any time. The firmware is entirely written in C, which makes
modifications easy to implement. Integrity and intellectual property are yet easy to secure using Lock Bits of the AVR
microcontroller.
4.2
Hardware
AVR1631 includes cost effective regulated capacitive power supply, XMEGA-A4U MCU, analogue front end (AFE),
signal conditioning for line voltage and current measurement, human-machine interface (LCD, user pushbuttons), AMR
communication interfaces including RS-232 interface and energy LED’s pulse output interface. Metering board also
includes external tamper detection circuits.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
10
Figure 4-1. Block diagram of the Atmel AVR1631 single-phase energy meter.
4.2.1
Capacitive power supply
This design explains a cost effective capacitive power supply solution. Transformer less power supplies provide a lowcost alternative to transformer-based or switcher-based power supplies. The low cost, lesser board space and immune
to the external magnetic field capacitive power supply is being implemented in this reference design. The design will
also meet the metering standard requirement for power consumption.
4.2.1.1 Theory
The capacitive power supply circuit shown in Figure 4-2 is being implemented in this reference design. The circuit works
of both positive and negative half cycle of the AC input and thus offers a balanced load to the AC source. The principle
of the low-current power supply is that it uses the same current to charge several capacitors at the same time. This
method results in higher energy storage and efficiency, lower input current for the same load, reduction of the input
capacitor value and immediate cost savings.
4.2.1.2 Surge protection
Some care must be taken to avoid high voltage on the capacitors: There is no component that would limit the charging
voltage of the capacitors, so in order to avoid capacitor damage due to high-voltage surges on the mains input, it is
recommend the use of a bipolar TVS, AC Zener diode, or MOV across the LINE and NEUTRAL nets after the highvoltage capacitor as shown in Figure 4-2. In addition, a 100Ω resistor (R1) should be placed on the high-voltage side to
provide a way to drop surge voltage for the TVS, Zener diode, or MOV.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
11
Figure 4-2. Capacitive power supply circuit.
4.2.2
Analog front end
This energy metering reference design uses current sensing shunt for measuring phase current with anti-aliasing filter
and current transformer for measuring neutral current. The conversion of analog input signal to digital is done by the
ADC of the microcontroller. As internal gain amplifier is present in the Atmel XMEGA-A4U, this design does not require
any external gain amplifier for the amplification of voltage drop across the shunt.
4.2.3
Voltage front end
Line voltage is first downsized using a resistor ladder, then DC-filtered as shown in Figure 4-3.
Note:
The component numbers are not the same as in the full schematic of this design.
Figure 4-3.
Voltage front end.
Resistors R1, R2, R3 and R4 values should be selected in such a way that the peak-to-peak voltage should not go
above the ADC reference voltage for 120% of nominal voltage.
Equation 4.1.
Vmax =
Vnom *1.2 * R 4
( R1 + R 2 + R3 + R 4)
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
12
4.2.4
Current front end
Line current typically ranges from some milli-amperes to tens of amperes. In order to achieve 1% measurement
accuracy over such a wide range, the ADC would need to have a resolution of around 16 bits. Since the target device
includes only a 12-bit A/D-converter the front end must amplify small-scale signals. The target device has in-built
differential gain amplifier stages not requiring external gain amplifier. The Figure 4-4 shows the current front end used in
phase and neutral for current measurement. The anti-aliasing filter acts as a low pass filter to remove the high
frequency noises.
Shunt resistor Rshunt and the current transformer are scaled such that a voltage signal of no more than 1V peak-to-peak
is present at the input of ADC. For example, using a 500µΩ shunt resistor and setting internal gain amplifier as x32 the
voltage at the output of gain stage for Imax = 30A current input as follows:
Equation 4.2.
Vmax = I max * Rshunt * Gain
Vmax = 30 2 * 500μΩ * 32 = 678.8mV (Vp )
The burden value for the current transformer can be calculated from the Equation 4.3. For example, using a 8Ω burden
resistor, setting programmable gain amplifier as x2 for 1:1000 turns CT the voltage at the output of PGA for Imax= 30A
current input as follows:
Equation 4.3.
Vmax = I max * Rburden * Gain * TurnsRatio
Vmax =
30 2 * 8Ω * 2
= 678.8mV (Vp )
1000
Figure 4-4. Current front end.
4.2.5
Microcontroller
The microcontroller section includes the XMEGA-A4U and all other digital input and output circuitry. The block diagram
of XMEGA-A4U MCU is shown in Figure 4-5. The detailed explanation of each block is available in the datasheet.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
13
Figure 4-5. Block diagram of the Atmel XMEGA-A4U MCU.
4.2.6
LCD driver interface
LCD’s are widely used as data display devices in embedded systems. Among the features that have made LCD’s
popular are low price, low power dissipation, lightweight, durability, reliability and broad support by dedicated ICs for
communication with microcontrollers. This design uses LCD for displaying consumed energy for billing purpose. Since
LCD driver is not in-built in the XMEGA A4U device external LCD driver is used in this application. The interfacing of
LCD driver and XMEGA device is done through four GPIO pins.
Note:
Pin number 8, 9 shown in Table 4-1 is connected to LCD backlight. Appendix A gives detailed timing diagrams to
communicate with the LCD driver for different modes from MCU.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
14
Figure 4-6. LCD display.
Table 4-1.
4.2.7
LCD driver connector.
Pin
Name
Direction
Description
1
CS
Out
Chip select
2
RD
Out
Read clock
3
WR
Out
Write clock
4
DATA
In/Out
Serial data in/out
5
GND
N/A
Ground
6
VCC
N/A
Supply
7
NC
N/A
Not connected
8
LED-
Out
LCD backlit
9
LED+
Out
LCD backlit
Signal LED’s
In order to keep power consumption low all LED’s are of low-current type. The LED’s have a forward voltage of about
2V and using a series resistor of 1.8kΩ will therefore limit the current to about 1mA per LED. The resulting LED
brightness is good for most applications.
4.2.8
Programming and debugging interface (PDI)
The Program and Debug Interface (PDI) is an Atmel proprietary interface for external programming and on-chip
debugging of a device. The PDI supports fast programming of nonvolatile memory (NVM) spaces; flash, EEPOM, fuses,
lock bits and the user signature row. This is a two-pin interface that uses the reset pin for the clock input (PDI_CLK) and
one other dedicated pin for data input and output (PDI_DATA). PDI connector pin configuration is shown in Table 4-2.
Table 4-2.
PDI connector.
Pin
Name
Description
Description
1
PDI_DATA
In/Out
Data input and output
2
VCC
N/A
Supply voltage
3
NC
N/A
Pin is left free
4
NC
N/A
Pin is left free
5
PDI_CLK
In
PDI clock
6
GND
N/A
Ground
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
15
Figure 4-7. PDI interface.
4.2.9
Serial communication interface
This reference design uses the universal synchronous and asynchronous serial receiver and transmitter (USART) for
data transfer between the meter and PC. The USART supports full-duplex communication and asynchronous and
synchronous operation. Any terminal software can be used for sending commands to the meter and for receiving the
data. The signal pins (Rx/Tx) shown in Table 4-3 cannot be directly connected to the serial port of a computer hence
requires the RS-232 level converter. This design uses Max3232 RS-232 level converter for such purpose.
Table 4-3.
Serial connector.
Pin
Name
Description
Description
1
Tx
Out
Serial data output
2
Rx
In
Serial data input
3
GND
N/A
Ground
4.2.10 Battery backup interface
The Real-Time-Clock (RTC) of Energy meter should be running even with no main VCC hence needs the battery backup
feature. External crystal clock frequency is used as RTC clock source for better accuracy. A dynamic power switch
shown in Figure 4-8 is used to switch from the VCC domain to the VBAT domain if VCC falls below the operating voltage level
for the device. When the VCC voltage is restored, the power is switched back to VCC. This dynamic power switch can be
triggered by firmware or by hardware. Switching delay need to be taken care to avoid RTC reset.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
16
Figure 4-8. Battery switching circuit.
4.3
Firmware architecture
The firmware is organized in tasks that is executed in a round-robin fashion and interrupts. The firmware implements
the measure and display of kWh, RMS voltage, current and other basic parameters on LCD. Besides basic energy
measurement, this design also includes features that many electric utilities are very interested in rolling out on a wider
basis.
An on-board RTC provides a time source for calculating and tracking current and historical peak demand. All metered
data is securely stored in internal nonvolatile memory. The basic flow of the energy metering firmware is shown
in Figure 4-9.
Figure 4-9. Energy metering firmware basic flow.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
17
4.3.2
System initialization
The firmware initializes all required registers before entering the main infinite loop. Measurement variables and Tamper
flags are cleared and the timers are reset. The peripherals like LCD, GPIO Ports and UART are getting initialized by
calling respective initialization functions.
ADC initialization of CH0, CH1, CH2 input signals for phase current, voltage and neutral current is done. All the three
inputs are measured in differential mode of the ADC and not requiring the external level shifter. The internal reference
voltage of 1V is being used as reference to ADC. The equations (4.1, 4.2 and 4.3) can be used to calculate the
hardware components values to limit the voltage input to the ADC to 1V. The Internal differential gain amplifier is used
for input current signal measurements.
The ADC production calibration constant is loaded to the ADC registers from fixed Flash locations. Calibration
Constants are taken from the internal EEPROM and stored in the local RAM variables for the energy calculation.
RTC is initialized for generating Interrupt for every 1sec. This RTC interrupt is used to calculate basic parameters,
energy calculation and LCD refresh. Timer TCC1 registers is initialized as per required sampling rate of 4 kHz to start
ADC conversion. The required TCC1 register values are calculated from the Sampling Rate Equation 4.4. The interrupt
is enabled at sampling time to trigger the ADC conversion.
The built-in Digital Frequency Locked Loops (DFLLs) is used to improve the accuracy of the 32MHz internal oscillator.
The DFLL compares the oscillator frequency with a more accurate 32.768kHz crystal oscillator connected to the TOSC
pins to do automatic run-time calibration of the oscillator. DFLL controls the ratio between the 32.768kHz crystal
oscillator frequency and the 32MHz internal oscillator frequency. If the internal oscillator runs too fast or too slow, the
DFLL will decrement or increment its calibration register value by one to adjust the oscillator frequency.
The main loop is responsible for updating the kWh register, maintaining the visual display shown on the LCD, periodic
check for tamper presence and calculating the maximum demand for particular integration period. All the above
operations are done in active mode.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
18
Figure 4-10. System initialization.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
19
Figure 4-11. Main loop.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
20
4.3.3
ADC sampling
The ADC has four conversion channels with individual input selection, result registers, and conversion start control. This
design uses three conversion channels for the sampling analog inputs of voltage, phase current and neutral current.
Timer TCC1 will trigger the ADC to start the conversion at sampling rate (Fs). The sampling rate (Fs) is calculated as per
the Equation 4.4. This design uses 4kHz as the sampling rate.
Equation 4.4.
Fs =
Ftimer
( PER + 1)
where PER is timer period register value, Ftimer is timer frequency.
4.3.4
Multiply-accumulate of samples
Timer TCC1 ISR is being generated for every sampling time. ADC Conversion start for CH0 is triggered in Timer TCC1
ISR. Phase current sample is read from CH0 result register at ADC conversion complete interrupt service routine. CH1
conversion is also triggered in the ISR. At the CH1 ISR the voltage sample is read and triggers CH2. After reading all
the three ADC-CH register values the sample multiply and accumulate operation is being done for each sample.
Dynamic DC offsets of each signal are subtracted from the respective samples. Voltage sample is squared and added
with the previous squared value for the calculation of Vrms similarly current sample for Irms. The buffer required for storing
the samples is eliminated as multiply and accumulate operation is done on each and every sample as and when it is
read from the result registers.
Each voltage and current sample is multiplied to get the active power. Before that voltage signal is delayed / advanced
with the help of Zero’th order FIR filter to compensate for the phase angle delay on current sample due the ADC
measurement or anti-aliasing filter as explained below.
A fractional delay introduced in voltage sample by the use of single zero-FIR filter is:
Equation 4.5.
y[ n ] = x[ n ] + β x[ n − 1]
Here x is input voltage sample, y is delayed output voltage sample, n is sampling sequence, and β is delay gain.
Equation 4.5 in Z domain:
Equation 4.6.
Y ( z ) = X ( z ) + β z −1 X ( z )
Equation 4.7.
H (z ) =
Equation 4.8.
H e jω = 1 + β cos ω − jβ sin ω
Y (z )
= 1 + β z −1
X (z )
( )
Amplitude and phase characteristics could be analyzed with respect to the following expressions:
Equation 4.9.
Equation 4.10.
A(ω ) = 1 + 2β cos ω + β 2
θ (ω ) = arctg
β sin ω
1 + β cos ω
where ω is angular frequency,
Equation 4.11.
ω=
2πf
fs
Group delay can be calculated according to the following relation:
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
21
Equation 4.12.
τg = −
β (β + cos ω )
dθ (ω )
=
1 + β 2 + 2β cos ω
dω
Equalizing the filter group delay with the inherent phase shift of the current transformer, the parameters for filter
realization according to expression are obtained:
(1 − 2τ )cos ω ± [(1 − τ ) cos
β =−
2(1 − τ )
2
Equation 4.13.
g
g
2
]
ω + 4τ g (1 − τ g )
1
2
g
In order to compensate for the digital filter amplification, the output i.e. y[n] should be multiplied by inverse filter
amplification A-1. This parameter is calculated following the next expression:
Equation 4.14.
(
A−1 = 1 + 2β cos ω + β 2
)
−1
2
The filter coefficients β and A-1 are calculated during the phase angle correction calibration.
Figure 4-12. ADC sampling and accumulation.
The discrete sample and accumulation for voltage RMS calculation can be written as:
Equation 4.15.
V ' [ n ] = V "[ n ] − VDCoffset
Equation 4.16.
V [n] = A−1 * (V '[n] + β *V [n − 1])
Equation 4.17.
VsqSum = ∑ (V [ n] * V [ n])
N −1
n =0
Where A-1 and β are the filter coefficients used to compensate the phase delay between voltage and current require for
energy calculation.
Similarly for current RMS calculation can be written as:
Equation 4.18.
I [ n ] = I "[ n ] − IDCoffset
Equation 4.19.
IsqSum = ∑ ( I [n] * I [n])
N −1
n =0
For active power calculation:
N −1
Equation 4.20.
PowerSum = ∑ [( K v * V [ n])( K I * I [ n])]
n =0
Where Kv and KI are calibration constants to correct the measured values in order to get the Class 1 accuracy.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
22
Figure 4-13. Timer ISR.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
23
Figure 4-14. ADC ISR.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
24
4.3.5
Basic energy and instantaneous parameters calculation
An interrupt for every 1sec from RTC will set the flag to indicate the MCU to do the energy measurement using the
accumulated active power and all other instantaneous parameters. The active energy is the measure of active power
accumulated over a period of time. The accumulated active power for 1sec is multiplied with 1sec to get the active
energy for 1sec. This watt-sec value is converted to kWh to get the basic measure of active energy. The kWh for every
1sec is being accumulated with the previous value to get the cumulated kWh. Other instantaneous parameters like
voltage RMS, current RMS, active power (kW), apparent power (kVA) and power factor also calculated from the
sampled and accumulated values from the below equations. The flow of basic parameters calculation is shown in Figure
4-15 and Figure 4-16.
The power averaged over the integration period is called demand. The present demand is compared with the previous
integration period demand stored in EEPROM and updates the value if this demand is greater. This provides a record
for tracking peak demand for one month. The default value for the integration period is 30 minutes.
Figure 4-15. Basic parameters calculation.
VsqSum
N
Equation 4.21.
Vrms = K v *
Equation 4.22.
⎡ IsqSum⎤
Irms = K I * ⎢
− I Offset
⎣ N ⎥⎦
Equation 4.23.
⎧⎡ PowerSum ⎤
⎫
ActivePower = K w * ⎨⎢
− POffset ⎬
⎥
N
⎦
⎩⎣
⎭
Equation 4.24.
ApparentPower = Vrms * Irms
Equation 4.25.
⎡ ActivePower ⎤
PowerFactor = ⎢
⎥
⎣ ApparentPower ⎦
Kv, KI and Kw are the voltage, current and power calibration constants to correct the measured values in order to get the
Class 1 accuracy.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
25
Figure 4-16. Basic parameters calculation.
4.3.6
Calibration pulse output generation
In order to generate the pulse proportional to the consumed energy the Timer TCC1 interrupt is used. The energy
equivalent to one sample time derived from 1sec energy. In Timer TCC1 ISR One Sample energy is accumulated and
compared with One Pulse energy which is derived from meter constant from the Equation 4.26. If the accumulated
sample energy is reached one pulse energy then pulse LED is switched ON for the time (approximately 30ms) to enable
the standard meter to sense for the calibration. Figure 4-13 describes the flow of calibration pulse generation.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
26
Equation 4.26.
OnePulseEnergy =
1
MeterConstant
The frequency of the energy pulse and the amount of active power measured are related as follows:
Equation 4.27.
Fpulse =
ActivePowe r * MeterConst ant
3600 * 1000
Taking into account the system clock, FCLK, and the timer/counter prescaler, the energy pulse interval (Tpulse) is derived
as follows:
4.3.7
Equation 4.28.
Ftimer =
FCLK
prescaler
Equation 4.29.
T pulse =
Ftimer * 3600 * 1000
Fpulse
Line frequency calculation
The zero cross detection of line voltage will enable the TCE0 timer for line frequency measurement. While taking the
voltage sample from the ADC-CH1 result register, the comparison of sign change of the value is done. When the
negative to positive sign change is detected the TCE0 timer counter value is reset. For the next negative to positive sign
change the timer count value is read from TCE0.CNT register. The line frequency is calculated from Equation 4.30 and
Equation 4.31 after taking the average of accumulation values.
4.3.8
Equation 4.30.
Ftimer =
FCLK
prescaler
Equation 4.31.
Freq =
Ftimer
TCE 0.CNT
LCD display
LCD is used to display the measured parameters sequentially. The displayed parameters can be changed by pressing
the switch. External push button switch is connected to the I/O port pin is enabled as an external interrupt. When the
button is pressed the external interrupt will trigger the MCU. The sequence number of display is changed in PushButton
ISR as shown in Figure 4-17. The change of sequence number is indicated by LCD refresh flag to the LCD driver
routine. LCD driver routine will take the parameter as per the changed sequence number. All the basic parameters can
be displayed sequentially for each switch press.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
27
Figure 4-17. External interrupt ISR for push button.
4.3.9
Tamper detection logics
Apart from the basic parameter, the meter also analyses the electrical parameters and their relationships to make a
judgment whether this is a situation which may happen due to normal load condition or is artificially caused. This is
called as tamper detection. Earth Load Tamper, Current Reversal, Magnetic tamper, Case Open are the few tampers
implemented in this application note.
Earth Load Tamper is checked periodically by comparing the neutral Irms current with the Phase Irms and if it is greater
than the ELT tamper, meter declares as ELT tamper detected. The Earth LED is being switched ON to indicate the
presence of tamper and the Earth Tamper flag is also set. Reverse tamper detection is based on the sign of the active
power, if it is negative then reverse tamper is being indicated by switching ON the reverse LED. This is being shown in
Tamper Check Loop Figure 4-18.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
28
The magnetic tamper and Case open tamper is based on the change in the external input signal connected to the MCU.
For the Magnetic tamper the output from an external Hall Effect sensor is connected to the external interrupt pin of
MCU. When there is a change in the signal from high to low the tamper is detected and being displayed in LCD. The
case tamper is detected through the change in state of external normally open switch. When the switch is released the
MCU will see the change in state and detect as Case Open Tamper and will be indicated in the LCD display.
Figure 4-18. Tamper check loop.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
29
Figure 4-19. External interrupt ISR for tamper.
4.3.10 Low-power mode implementation
In order to reduce the average current consumption by the meter, meter is put to idle mode after doing all the basic
calculation, tamper check etc., The periodic timer TCC1 interrupt used for starting the ADC conversion for every sample
time will wake up the MCU from idle mode and after taking the samples again the MCU is put into sleep. The external
interrupts can also wake up the controller from idle mode.
In case of mains power is switched OFF the power fail is detected by triggering the external interrupt. In the power fail
ISR is being shown in Figure 4-20. The battery is getting connected by enabling transistor switch and hence RTC will be
running even with the power outage. The MCU will switch off all the power consuming peripherals like ADC, LCD driver
and then MCU is put into power save mode. In power save mode only the BOD and RTC will be running. RTC calendar
updating is done periodically by waking the MCU from power save/idle mode.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
30
Figure 4-20. Power fail interrupt ISR.
4.4
Calibration procedure
Calibration of each meter is required to compensate the variation in the component’s values. As the voltage and current
are the inputs, it is required to do the calibration of both. The calibration flow diagram of Figure 4-21 and equations
describe the calibration procedure. The following calibration routines are described in this section:
•
•
•
•
Current RMS and Voltage RMS Calibration (KI and Kv)
Current and Watt Offset Calibration (IOffset and POffset)
Active Power Calibration (Kw)
Current Phase angle Calibration (A-1 and β)
These calibrations are done by supplying specific voltage and currents at specific phase angles to the meter. The
internal calculation procedure for RMS and active power calibration is the same. The procedure is to accumulate the
data for some time and take the average of the accumulated data. The calibration constant is calculated as the
reference input value is divided by the average accumulated data as shown in Equation 4.32.
Equation 4.32.
CalibrationConst =
AccumulationCycles
× InputRefValue
AccumulatedData
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
31
The voltage RMS is calibrated at single point at reference voltage but the current RMS is calibrated at multiple points.
Accuracy within Class 1 is required for 5% of basic current to 900% of basic current and also required to start
measurement from 0.2% of basic current. This requires at least 16-bit resolution of ADC to get the accuracy for over a
wide range of current. This can be achieved by 12-bit internal ADC with two gain stages. The range of current is divided
into different regions and required calibration at individual regions.
The current phase angle correction is done for the phase delay caused by the ADC measurement. 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 not possible. In order to compensate this delay Zero’th order FIR filter is introduced
in the voltage signal. So the calibration for phase angle correction is calculating the filter coefficients β and A-1. This is
done at 0.5 lag power factor and at multiple current regions.
Calibration is initiated by sending command from a serial terminal. The connection requirement is 38400 baud rate,
data bits of 8, parity of none and flow control as none. The switch sw1 needs to be pressed to enable calibration
mode. Table 4-4 shows the command used to call various calibration functions. The calibration procedure can also be
automated by making custom PC based software to reduce the production time. The calibration commands are shown
in Table 4-4.
Table 4-4.
Calibration command.
Command
Calibration function
Format
T
Time and date
DD-MM-YYY HH:MM:SS
V
Voltage
eg: 240.00
N
No load for calculating offset
y Æ ready n Æ cancel
I
Used to calibrate the current
eg: 01.00
W
Used to calibrate kW
eg: 0100
C
Used to calibrate phase
eg: 01.00
On reception of a command, the meter will prompt the user to enter the required data.
Voltage RMS is calibrated at reference voltage and at single point. The current channel has to be calibrated at 0.250A,
1A, 2A, 3A, 5A, 9A and 22A similarly the active power (W) has to be calibrated at 30W, 120W, 240W, 360W, 600W,
1080W and 2640W; where the voltage should be kept at 240V and PF at unity. For calculating the phase angle
correction filter coefficients the test points are 0.250A, 1A, 2A, 3A, 5A, 9A and 22A at 240V, 0.5Lag PF.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
32
Figure 4-21. Calibration loop.
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
33
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
34
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
35
Appendix A.
LCD timing diagram
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
36
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
37
Appendix B.
Revision history
Doc. Rev.
Date
Comments
42039A
11/2012
Initial document release
Atmel AVR1631: Single Phase Energy Meter using XMEGA A [APPLICATION NOTE]
42039A−AVR−11/2012
38
Atmel Corporation
Atmel Asia Limited
Atmel Munich GmbH
Atmel Japan G.K.
2325 Orchard Parkway
Unit 01-5 & 16, 19F
Business Campus
16F Shin-Osaki Kangyo Building
San Jose, CA 95131
BEA Tower, Millennium City 5
Parkring 4
1-6-4 Osaki
USA
418 Kwun Tong Road
D-85748 Garching b. Munich
Shinagawa-ku, Tokyo 141-0032
Tel: (+1)(408) 441-0311
Kwun Tong, Kowloon
GERMANY
JAPAN
Fax: (+1)(408) 487-2600
HONG KONG
Tel: (+49) 89-31970-0
Tel: (+81)(3) 6417-0300
www.atmel.com
Tel: (+852) 2245-6100
Fax: (+49) 89-3194621
Fax: (+81)(3) 6417-0370
Fax: (+852) 2722-1369
© 2012 Atmel Corporation. All rights reserved. / Rev.: 42039A−AVR−10/2012
Atmel®, Atmel logo and combinations thereof, AVR®, Enabling Unlimited Possibilities®, XMEGA®, and others are registered trademarks or trademarks of Atmel
Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this
document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES
NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF
INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no
representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time
without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in,
automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.