This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Timer, t1-t0, integral promotion

For ARM7, A hardware timer is 32-bits, and unsigned int is 32-bits too;
For a 16-bits MCU, A hardware timer is 16-bits, and unsigned int is 16-bits too;

So,

t0 = timer_val;
while ( ( timer_val - t0 ) < delay_val );

provide a simple and good delay;

Not so sure about, if a cast is needed.

t0 = timer_val;
while ( (unsigned int)( timer_val - t0 ) < delay_val );

Just noticed that, due to the integral promotion,

unsigned short t0, t1;
( t1 - t0 ) is a signed int.

It seems that,

unsigned int t0, t1;
( t1 - t0 ) is still an unsigned int.

I noticed this, because I use unsigned short to present a 16-bits timer_val on my X86-PC for testing/simulating purpose, and the result is not what I expected.

Parents
  • What will happen if the [ticks] parameter happen to be zero [0] or one [1]

    That's not related to the types issue, which my example was designed to clarify. You can easily extend the code to treat corner cases. You'll also note that the 'do-while' is not necessary, a 'while' loop will do.
    By the way, the provided example does a reasonable thing when ticks==0: it returns without waiting. When ticks!=0 you'll probably want to make sure that the delay is at least as long as required, so it would make sense to do the following:

    if (ticks != 0)
        ticks++;
    else
        return;
    

Reply
  • What will happen if the [ticks] parameter happen to be zero [0] or one [1]

    That's not related to the types issue, which my example was designed to clarify. You can easily extend the code to treat corner cases. You'll also note that the 'do-while' is not necessary, a 'while' loop will do.
    By the way, the provided example does a reasonable thing when ticks==0: it returns without waiting. When ticks!=0 you'll probably want to make sure that the delay is at least as long as required, so it would make sense to do the following:

    if (ticks != 0)
        ticks++;
    else
        return;
    

Children
  • For ARM7, A hardware timer is 32-bits, and unsigned int is 32-bits too;
    For a 16-bits MCU, A hardware timer is 16-bits, and unsigned int is 16-bits too;

    this is the usual illusion that embedded code (for sure, the part touching I/O) is portable
    some HW timers count up, some count down, what about tyhat?

    rik