Very short delays

Greetings all, is there a NOP command in Arduino /C that can be inserted to just waste a few clock cycles and create a very short delay. I just want to stretch pulses a bit when using port manipulation to turn pins on and off rapidly. (in this case too rapidly!) If so could someone please show me an example of it's use. Thanks in advance....leolfs

Try and define a byte variable:-
byte tick = 0;

then increment it
tick++;
that should compile down to one instruction.

You can “waste” one cycle (62.5ns on a 16MHz Arduino) with this inline assembly instruction:

  __asm__("nop\n\t");

Incrementing a dummy variable (which would have the same effect) is not guaranteed to work because the compilers optimizer may remove the added instruction alltogether unless its value is actually used.

Incrementing a dummy variable (which would have the same effect) is not guaranteed to work because the compilers optimizer may remove the added instruction alltogether unless its value is actually used.

Good point - what if you declared it "volatile"?

A lot of people have complicated preconceptions about making volatile variables.

The volatile keyword only guarantees that every time the compiler sees code that reads a variable, it gets it from the allocated memory for the variable instead of from a register that recently held the value.

It does not guarantee that the compiler keeps the variable, or does work on the variable. If the compiler sees no code that reads the value, the variable can be optimized away. Incrementing a variable is reading it while updating it, but you need something that reads it after updating it, to make sure it generates code and storage for it.

But if it were declared with global scope, the compiler couldn't know if the variable was used externally (only the linker could do that) so couldn't optimise it out. Hmm, I feel an experiment coming on...

Speaking of volatile, even the "asm nop" may need a volatile keyword to survive optimization. So should read like this:

__asm__ __volatile__ ("nop\n\t");

Defining nop (no operation) as a macro may help readability:

// add this to the top of your sketch
#define NOP __asm__ __volatile__ ("nop\n\t")

// and then use it in code as follows
  NOP; // delay 62.5ns on a 16MHz AtMega

Halley,
does this mean that x=x+1 will always work? as against x++
leolfs