arduino-capacitor icon indicating copy to clipboard operation
arduino-capacitor copied to clipboard

u2 > u1 ? u2 - u1 : u1 - u2 ?

Open Ndolam opened this issue 2 years ago • 2 comments

I've been trying to figure out what that is for.

In general, u2 is > u1, and so u2-u1 is the time between the two calls to micros().

The only reason I can see for u2 < u1 is where micros() overflows and wraps around (or a peculiar bug in micros()??).

Is overflow the issue?

If so, I believe that code is wrong (unless the Arduino does something weird with unsigned arithmetic). I don't have an Arduino at hand, but on this amd64 processor, this program

#include    <stdio.h>
#include    <inttypes.h>

int
main()
{
    uint16_t u1, u2, u1_u2, u2_u1;

    u1 = 65530;
    u2 = u1 + 20;
    u1_u2 = u1 - u2;
    u2_u1 = u2 - u1;

    printf("u1 = %u\nu2 = %u\nu1 - u2 = %u\nu2 - u1 = %u\n",
	   u1, u2, u1_u2, u2_u1);

    return 0;
}

outputs this:

u1 = 65530
u2 = 14
u1 - u2 = 65516
u2 - u1 = 20

As you see, since u1 and u2 are unsigned types, u2 - u1 gives the right answer regardless of whether overflow has happened or not.

On the other hand, if that ternary statement (and the u3/u4 one) is not dealing with overflow, the statement is (to me) mysterious, and probably deserves a comment in the code.

In summary, what is that for?

Ndolam avatar Jun 22 '23 02:06 Ndolam

It IS an overflow management. When the timer gets closer to the upper limit(0xFFFFFFFFL us, roughly 70 minutes), there comes a loop with a huge u2 - u1, which is the complement of actual time passed. Then u1 - u2 will give you the actual time passed by modulo calculation

ChitoKim avatar Jul 26 '23 13:07 ChitoKim

It IS an overflow management. When the timer gets closer to the upper limit(0xFFFFFFFFL us, roughly 70 minutes), there comes a loop with a huge u2 - u1, which is the complement of actual time passed. Then u1 - u2 will give you the actual time passed by modulo calculation

Ummm... did you look at the program I put above and its output? That program shows what one gets when calculating u1 - u2 and that is not the desired result.

Do I need to modify that program to use uint32_t values, or can I leave that as an exercise to the diligent reader?

Ndolam avatar Jul 26 '23 14:07 Ndolam