Develobeer
Develobeer

Reputation: 435

How to implement delay time (microsec order) on system call in C

How can I implement a delay time on system call in C? I'm using a stm32f429 and hc-sr04 sensor. I need to give a trigger pulse of 10 microseconds. I tried with:

gpio_set_value(TRIG, 1 );
for(k=0;k<16;k++)
asm("nop");
gpio_set_value(TRIG, 0 );

but I think that asm("nop") is inaccurate for delay. What is the best way in terms of accuracy to implement a delay of order of microsecond into a system call? Another small question: about asm("nop"), knowing that the ARM processor of my device has frequency 180MHz, how can I calculate the corresponding delay time of single asm("nop")? Thank you!

Upvotes: 0

Views: 1713

Answers (1)

askb
askb

Reputation: 6768

For short delays, use the kernel functions:

udelay(unsigned long usecs) - microsec delay
mdelay(unsigned long msecs) - millisec delay

These are timed loops implemented in an arch independent manner and are much better than below approach:

for (i = 0; i < 1000000; i++)
        ;

which is CPU speed dependent.

Note: Putting a very large value (15000 mili sec) then its possible the kernel will give a soft-lockup. This is a hardcoded value when the signal must give a soft-lockup. Also using udelay() or mdelay() is not interruptible during the wait, therefore as alternatively, you may want to consider using kernel timers.

Upvotes: 2

Related Questions