So instead of having an empty while loop, you should put __no_operation();
in there (2 underscores, not 1). This takes ~29ns per instruction cycle at 168MHz on my board, and it's inserting intrinsic assembly NOP's directly into the code stream, so it will stand-up against any optimizations.
One last note: your loop-counter is __IO
, meaning that it's volatile. This means the loop-counter will not be put in a CPU register. You can change that once you put the __no_operation();
line in your loop, because it will protect it from being eliminated by the compiler.
You typically should use a timer, but sometimes we all just need a hack-up :)
-Jesse