Reputation: 2092
I'm making a microcontroller programmer and for now, I've been using usleep()
to try to introduce appropriate delays.
It seems that sometimes the program works and sometimes it doesn't.
I tried the -O2
flag when compiling my code but I begin to wonder if that's a mistake.
Also, is there a more accurate timing function I can use besides usleep()
that doesn't involve any libraries not included in the standard system? I don't want to use a function that the system caches in the background (and screws up the timing). Heck, if it means to call a specific address in the system to wait for a clock tick, then I'd rather do that.
Any suggestions?
Upvotes: 1
Views: 129
Reputation: 140266
probably, but it fully depends on your hardware.
On some machines you can directly read timer values at some given addresses, but there can't be an universal answer to that. Prepare to use volatile
attribute to read those timers as they change while your program is executing.
On the more portable side, one system call which (if available) is more reliable is nanosleep
if available on your system (How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?).
It works by active/calibrated loops so when you call it, there's no system call involved (at least for small values, probably depends on the implementation).
If you don't have it, well, you could implement it by:
It's best to include this sleep implementation in a part which isn't optimized at all (-O0
). You won't have nanosecond precision with that but for milliseconds you should be okay.
Upvotes: 2