#ifndef delay_h_included
#define delay_h_included

#include <stdint.h>

//one step takes 3 clock cycles (when running from flash with prefetch ON), which is 17.857ns at 168mhz !!!unchecked whether it takes less at lower freq, certainly it would be more with flash prefetch off
//use a fixed register to prevent compiler from using special registers, which might be slower/faster leading to irregular performance of the inlined instantiations
static inline void Delay(uint32_t n_clock3)
{
        asm volatile (
        "\n"
       "\tmov r3, %0\n"
        "Lab%=:" "\n\t"
        "subs r3, r3, 1" "\n\t"
        "bne.n Lab%=" "\n\t"
	:  
	: "r" (n_clock3) 
	: "r3"
        );
        return;
}


#define delay_us(s) Delay((s)*SYSTEM_CLOCK/3/1000000)

#define delay_ms(s) Delay((s)*SYSTEM_CLOCK/3/1000)

#define delay_xs(s) Delay((s)*SYSTEM_CLOCK/3/2000000)


#endif
