1

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?

danglingpointer
  • 4,708
  • 3
  • 24
  • 42
Mike -- No longer here
  • 2,064
  • 1
  • 15
  • 37
  • 3
    probably, but it fully depends on your hardware. there can't be an universal answer to that – Jean-François Fabre Feb 15 '18 at 07:57
  • 1
    What's the h/w and o/s we're on? – Joe Feb 15 '18 at 07:58
  • 1
    'if it means call a specific address in the system to wait for a clock tick' well, for more accurate timing, it's usually done the other way round - the hardware calls a specific address in the system when an interval has expired. As others have commented, you need to look at your hardware, specifically timers. – Martin James Feb 15 '18 at 08:05
  • 5
    Also, 'simplest, truest' are usually mutually exclusive:( If it were not so, everyone would use that mechanism and there would be no others to consider. – Martin James Feb 15 '18 at 08:06
  • Possible duplicate of [precise timing in C](https://stackoverflow.com/questions/14765301/precise-timing-in-c) – vgru Feb 15 '18 at 08:45
  • Please define "doesn't work". Does it wait for the wrong time (too short, too long, no time at all, forever..) ? – Alnitak Feb 15 '18 at 11:47

1 Answers1

2

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:

  • calibrating a loop (at startup)
  • using this calibration value to achieve desired delay

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.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219