 # Energy Calculation via time measurement of void loop()

Hey, I want to calculate the energy used by recharging a battery. This is done in a void loop. To get [Ws] in the end in need the time that my program spends in one void loop (to sum up the single energies of each loop). Right now I have this:

In setup() at very beginning: unsigned long progstart = millis();

in void loop() at very beginning: unsigned long currentMillis = millis(); ..... calculations ..... delta_t = (progstart - currentMillis)*0.001; //in seconds //progstart = currentMillis;

But I am not sure about the result, it seems wrong! What is the correct solution?

Thanks for help!

loop() has NO specific run time, it tries to do everything as quick as possible but the more it needs to do the longer it takes. And same for the "energy per loop", that will therefor be a useless unit :)

Your calculation of delta_t is wrong

Current time minus start time gives a result in milliseconds so multiplying by 0.001 does not convert it to seconds

Thanks! Yes sure, I know that the time is variable and as fast as possible. That's why i want to measure how long it stays in the loop(). I assume that every loop is more or less equal (of course i do an error by this but it's ok). I just want to measure how much time it is in the loop! How can i do it?

Just use millis() to time the measurements at a constant interval independently from the repeat frequency for loop(). The demo Several Things at a Time illustrates the use of millis() to manage timing.

...R

thesamy2704: I assume that every loop is more or less equal

Assumption is the mother of all f.... :D

I would not doubt on that. Of course it really depends on what's really in it. In a lot of programs it's normal to time things and only do specific tasks, like printing to an LCD, only when you need to. And printing to an LCD can take easily a hundredfold of time then just checking some buttons for example. So energy per loop doesn't work.

And why do you want to know the time of each loop for a total? they will in the end sum up to (almost) millis() aka the total time. And your program will do nothing outside the loop() except is you use SerialEvent(). Even interrupts will be counted as part of the loop because you have no idea when you leave and enter a loop because of an interrupt.

So the sum of time in the loop is simply millis() - millisAtEndOfSetup :)

And don't try to make it seconds (by multiplying it with 0.001). That is float math. Which is a) slow, b) not precise so will give you an error.