it suffered from the same problem: it performs a subtraction before it performs a test. So a '0' is essentially passed to the call as -1, which is 64k-1, as the argument is cast to unsigned int.
Your choice is to change the code, or recast it to your own version:
#define mydelayMicroseconds(us) do {if (us) delayMicroseconds(us);} while (0)
And change all calls to delayMicroseconds to mydelayMicroseconds.
You could use a macro and be done with it.
You don't even have to change the name.
i.e.
#define delayMicroseconds(us) do { if(us) delayMicroseconds(us);} while(0)
This will work fine. It does add a slight overhead of a runtime check if us is a variable and not a constant
but then any solution that does a run time check on the delay value will have this.
The real question is if you want a delay of 1us when the delay you are asking for is 0?
And my question of curiosity is why are you asking for a delay of zero?
Is this caused by some sort calculation that results in truncation?
PeterH:
Just out of curiosity, what is the purpose of the do/while here?
It is a way to define a multi statement macro that works regardless of whether used
along side or inside other constructs such an if statement regardless of whether
braces are used.
if(xxx)
delayMicroseconds(delay);
else
foo(); // do other work
If you expand that out it becomes:
if(xxx)
if (delay) delayMicroseconds(delay);
else
foo(); // do other work
This silently/unexpectedly changes what the author wanted
in that now foo(); is called if delay is zero
vs if xxx is zero, and when xxx is zero nothing happens.
For readibility here is the resulting code re-formatted
if(xxx)
if (delay)
delayMicroseconds(delay);
else
foo(); // do other work
This change would not have happened if the original code used brackets
if(xxx)
{
delayMicroseconds(delay);
}
else
{
foo(); // do other work
}
But since using brackets is not mandatory for simple statements, the
macro should still work as expected when brackets are not used since it appears to be a simple function.
The do/while essentially turns the multi-statement macro back into a simple/single statement that can work
correctly when braces are not used.
KeithRB:
Don't you need a colon in there to complete the ternary operator '?' ?
the colon is for false statement, isn't it optional?
I think a ternary can have an empty expression 1 but must have an expression 2 (the "else" part after the colon)
To flip it, remove the semi colon, and ensure the ternary expression is fully evaluated before the ! (not) in case they pass
in more than a simple variable or constant you could do
Works, but I bet it isn't as obvious to most as the do/while(0) loop.
do/while(0) is also much more flexible for future modifications.
But we still need to hear from k7michal as all his examples were attempting
to replace a zero delay with a one Us delay to see if that is really a requirement
and why a zero is being passed in to begin with .