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++)
{
sample1+=analogRead(VOLTAGE);
sample2+=analogRead(CURRENT);
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.