Hello,

I have a simple code to measure power usage using the ACS current sensor.
This works fine for both voltage, current, power however the energy goes into negative after a while for some reason.
Here are some example inputs producing a negative value:

Voltage: 19.35 V
Current: 1.56 A
Power: 30.17 W
Energy: -12059.03

Here is the relevant code:

``````float sample1=0;
float sample2=0;
float voltage=0.0;
float val;
float actualval;
float amps=0.0;
float totamps=0.0;
float avgamps=0.0;
float amphr=0.0;
float watt=0.0;
float energy=0.0;
long milisec;
long stime;

..

milisec = millis();
stime=milisec/1000;

for(int i=0;i<150;i++)
{
delay(2);
}
sample1=sample1/150;
sample2=sample2/150;

voltage=12*2*sample1/1000;

int mVperAmp = 100;
int ACSoffset = 2500;

actualval = (sample2 / 1024.0) * 5000;
amps = ((actualval - ACSoffset) / mVperAmp);

totamps=totamps+amps;
avgamps=totamps/stime;
amphr=(avgamps*stime);
watt=voltage*amps;
energy=(watt*stime)/3600; // Wh
``````

Any idea what is causing this? Thanks.

Probably the time is going negative - millis() returns unsigned, and it will wrap round back to zero
regularly too. Your code is probably ignoring both these points?

Perhaps you should be integrating to sum the total energy, not extrapolating from the current
value of power?

Ok I think you just highlighted the problem millis variable should be declared as unsigned long instead of just long.

Still it does not explain why for example the power which uses the same millis calculation never goes into negative.

Anyway I will give it a shot see if it fixes it on the long run.

it does not explain why for example the power which uses the same millis calculation never goes into negative

Perhaps because W = V.I = ||V|| * ||I|| * Cos Phase Angle.

All of which are real and positive.