Jerome Carter Jerome Carter - 2 months ago 15
C Question

How to create my own sleep or delay function in c

I'm creating a small kernel in C and I need a function that will take a parameter containing the amount of seconds it should wait for.

I've tried using for loops, but they haven't worked.

I can't use the C standard library and need a way to tell the kernel to wait(in C). How can I do this?

Loop:

int c = 1, d = 1;

for ( c = 1 ; c <= 32767 ; c++ )
for ( d = 1 ; d <= 32767 ; d++ ){}

Answer

Using a loop works, but the time it takes will be highly dependent on the speed of your CPU and any compiler optimisations. It's useful when you know the target hardware (e.g. writing for specific microcontroller).

You should include a NOP in the body of loop. Also check if your compiler supports a #pragma or special comment to disable optimisations on specific blocks of code.

Check your compiler documentation for a definition of NOP. Most compilers define a macro named _nop() or _nop_()

You can define your own using:

#define Nop() {_asm nop _endasm}

Or by writing asm("nop") if your compiler supports inline assembly.