Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to add delay/do nothing for n cpu cycles

I need to add a delay into my code of n CPU cycles (~30). My current solution is the one below, which works but isn't very elegant.

Also, the delay has to be known at compile time. I can work with this, but it would be ideal if I could change the delay at runtime. (It is OK if there is some overhead, but I need the 1 cycle resolution.)

I do not have any peripheral timers left, that I could use, so it needs to be a software solution.

do_something();
#define NUMBER_OF_NOPS   (SOME_DELAY + 3)
#include "nops.h"
#undef NUMBER_OF_NOPS
do_the_next_thing();

nops.h:

#if NUMBER_OF_NOPS > 0
    __ASM volatile ("nop");
#endif
#if NUMBER_OF_NOPS > 1
    __ASM volatile ("nop");
#endif
#if NUMBER_OF_NOPS > 2
    __ASM volatile ("nop");
#endif
...
like image 283
gugelhüpf Avatar asked Nov 07 '22 20:11

gugelhüpf


1 Answers

In the cortex devices NOP is something which literally means nothing. There is no guarantee that the NOP will consume any time.They are used for padding only. I you will have several consecutive NOPs they will just be flushed from the pipeline.

For more information refer to the Cortex-M0 documentation. http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0497a/CHDJJGFB.html

software delays are quite tricky in the Cortex devices and you should use other instructions + possibly barrier instructions instead.

use ISB instructions 4 clocks + flash access time which depend what speed the core is running. For very precise delays place this part of code in the SRAM

like image 90
0___________ Avatar answered Nov 15 '22 04:11

0___________