July
1998, Issue 96
A
PIC-Based AC Power Meter
MEASUREMENT
CONSIDERATIONS
The raw value
from the ADC is read at a 100-Hz rate or every 10 ms
and is in the 0127 range. This value indicates
a 10-W increment of power (so, 12 means 120 W). Lets
refer to this raw A/D value as having the unit of a
ten-watt (i.e., 10 W).
To display
a power reading, the main loop reads the current value
of power that the ISR writes to, multiplies this value
by 10, converts this result to a five-digit BCD word,
and then displays the four least significant digits
of the result. The multiply requires 16-bit math because
10 × 127 equals 1270, which doesnt fit into 8
bits.
I found the
16-bit math and BCD conversion routines on the Microchip
BBS. The routines are fairly compact in size and require
approximately 300 cycles (300 ms at 4 MHz) for an unsigned
multiply or divide.
Since the
16-bit values need to be converted to BCD prior to display,
and the BCD routines return a five-digit result, a divide
by 10 is done just by displaying the upper four digits
instead of the lower four digits. This fact is taken
into account when designing scaling algorithms.
For energy
consumption, a 24-bit accumulator is required to capture
a reasonably large amount of energy consumption, given
the 100-Hz accumulation rate. To keep the non-reentrant
math routines out of the timer ISR, the timer ISR accumulates
the power value (0127) into an intermediate 16-bit
accumulator, S. The main-loop routine adds S
to the master 24-bit accumulator, E, when the
1_sec_ elapsed flag is set.
The S
value is in units of tenwatt-seconds. To accumulate
a wide range of energy consumption, the 24-bit E
accumulator is in units of milliwatt-hours. This allows
a maximum value of 224 1 = 16,777,215 mWh or
16.77 kWh.
The conversion
from tenwatt-seconds to milliwatt hours is:

However, since
the S accumulator represents 100 samples over
a 1-s period, we must divide S by 100 before
this conversion. So, the S-to-E accumulation
calculation (performed only once per second) is:

in milliwatt-hours.
Note that this conveniently reduces a multiply and divide
operation to a single divide.
To filter
transients in power-measurement mode, a 500-ms moving
average is implemented. The S accumulator is
restarted every second as part of the energy-consumption
function. At 500 ms after restart, a power value is
calculated by:

At 1 s after
restart, a power value is calculated by:

To ensure
that no-load situations read zero and that noise does
not cause false readings, hysteresis is added to cause
readings less than 2 (20-W reading) to be treated as
zero. This also helps in setting the zero trim pot.