On Jun 26, 7:42=A0pm, John Larkin wrote: [....]
[....]
You can improve things a little if you sample V then A or A then V depending on how you see the phase shifts stack up in your design. The two errors can be made to cancel slightly.
Make your sample rate such that "1024" samples is an integer number of cycles of the 60Hz.
Also try to make it so that this integer is odd. This means that in different cycles you samples land at different points. This removes some of the errors.
Assuming you don't want to keep lots of values around:
Since you are already computing the average, subtract the previously computed average from each value before doing the square but also remember the average of the numbers you are squaring. The previous average may be off a little but it is close enough that the some of squares is kept from growing way too many bits.
The corrected mean square is the mean square minus the square of the mean. The mean in this case is the mean of what you actually squared.
Doing square roots can be a bit tricky and slow in smallish processors. You have a few things working for you. If you are doing:
while not good enough Y =3D 0.5 * (Y + X/Y)
you can start off with the Y value from last time you did the sqrt. This is likely to be close to the right answer so you loop less.
There are methods that compute 1/sqrt(X) that don't divide inside the loop.
There are methods that work from the observation that the sum of the first N odd numbers is always N^2. This in practice is faster than methods involving multiplies or divides on machines that don't natively do those operations.
Since your voltage is nearly a sinewave, you can make a 90 degree phase shifter in software so that you can compute and estimate of the imaginary part of the power. This number can be handy if you want to display the phase angle.
If you have the imaginary part, you have the sign.
arctan is a very nasty function to compute when you are moderately far from zero. A table look up may be the best for this step.