Skip to content
Advertisement

How to achieve accurate timer in linux kernel

When i write a infrared remote control driver, I have to control delay accurate time during enabling and disabling PWM.

At first i used udelay() function in kernel, but i found it’s not accurate at all as i said in another post

AFAIK, other timeout functions provided by kernel can’t provide accurate time because of scheduler, when timeout, kernel still need some time to switch to my process.

What function should i use for this purpose?

Advertisement

Answer

In the post you reference above, the issue there was a rounding error in ndelay, an error which you had greatly multiplied by calling the function with a large argument (10000 nanoseconds) and then further by calling it 400 times. As I pointed out, the rounding error with udelay was actually quite small.

Either you need microsecond resolution, in which case, udelay would seem to be fine. Or you need nanosecond resolution, in which case, don’t use it to wait 4 million nanoseconds and you won’t have that level of error. (I have a difficult time conceiving of a device that requires you to wait for millions of nanoseconds [or even tens of thousands] but then expects you to react within a few nanoseconds.)

As you are evidently expecting to poll without allowing a task switch, another option is to use ktime_get to obtain a monotonically increasing nanosecond resolution time with carefully maintained correction. You can then do your own difference calculation to determine when you have waited long enough.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement