Good day, Im trying to simulate AC Energy consumption. After the Energy adds up to 1024, it stops adding the Energy. On the “Setup” I have stated the from where the Energy should start “finalEnergyValue = 1023.9995;” but, once it adds up to 1024 it just doesn’t add anymore. Below is the code:
float accumulateEnergy = 0;
float finalEnergyValue = 0;
float voltage = 0;
float current = 0;
float power_factor = 0;
float realPower = 0;
void setup() {
Serial.begin(9600);
finalEnergyValue = 1023.9995; // Start with 1023.9995 to count beyond 1024
}
void loop() {
voltage = 237.0;
current = 0.5;
power_factor = 1.0;
realPower = voltage * current * power_factor;
accumulateEnergy = realPower / 3600000.0; // Energy in Watt-Hour
finalEnergyValue = finalEnergyValue + accumulateEnergy;
Serial.println(finalEnergyValue, 4);
delay(977);
}
Float variables can accurately represent values with at most 6 to 7 decimal digits. 1023.9995 has eight.
Instead, use type double on MCUs that support that type (Arduino Uno, Mega and other AVR MCUs do not) and to maintain numerical accuracy, avoid adding very small values to large values.
Thank you very much for the reply, I changed from float to double, but as soon as it reaches 1024 it still doesn’t add from there. Im still new to Arduino, I really appreciate you helping me.
@x365
Where did you get these lines? Are you sure they are correct?
First, the comment in the second line does not correspond to reality, the formula does not give watt-hours, but kilowatt-hours.
And second, the most important thing is that the energy spent can only be calculated from the instantaneous power by integrating over time, which is not in this code
For integration, precise control of time intervals is required, without this, your formulas will give data that is very far from reality
Thanks for the reply, Yes, I should have changed my comment to “kilowatt-hours” it used to be “watt-hours” then I made it “kilowatt-hours” but forgot to change the comment to “kilowatt-hours.” This is only a simulation, just want to know why its not adding after 1024.
Just to update you, after testing your code for some time, I realised that it started counting backwards then I removed this line of code and it is working perfectly.
Removed this line:
finalEnergyDecimal -= (int) finalEnergyDecimal
Another approach is to use 32-bit or 64-bit integers.
Knowing that volts × amps × seconds = joules (1 J = 0.00027777 Wh), you can accumulate the joules and then divide by 3600 or 3,600,000 to obtain the Wh or kWh.