How does __delay_cycles work?
From the MSP430 Optimizing C/C++ Compiler v 3.1 User's Guide (SLAU132c.pdf) pp. 109:
The __delay_cycles intrinsic inserts code to consume precisely the number of specified cycles with no side effects. The number of cycles delayed must be a compile-time constant.
It is a intrinsic function, specifically designed to use up cycles. It should be good for at least that number of cycles. You can change 1000 to something else (it must be a constant, can't be a variable). Both the for loop and the function call will add to the delay.
Additionally:
yes with the code there will be a small "offset" and "gain" error in the actual delay you get. The code is good to guarantee a certain minimum delay, with a very small error into the positive direction. That's why the delay inside the loop was chosen rather large ("ms"). If you need a dead-on delay, the best way would be using a timer. But if you for some reason still want to use SW delays, I would recommend coding a function in assembler rather than measuring the C function. You could compensate in the function itself for the "offset" and "gain" errors of the call and loop overhead. Also, our IDEs have cycle counter functions that you could use to analyze the delay function. But for SW delays, be aware that interrupts could kick in (if enabled) and change your resulting observable delay.
TI Employees on their support forums.
Look at the dissassembly of the code, remember the for loop adds some instructions which take a few cycles. With a 5000 loop, these extra cycles will add up. Also, how delay_cycles()
is implemented can make a big difference.
You can count the cycles for each loop in the simulator, do the math and compensate for the added cycles by passing the appropriate value.
Of course, the best way to get accurate timing is to use interrupts, but you say you want to avoid those for now.