Altera_Forum
Honored Contributor
20 years agoaccurate "sleeping"
Hi All,
This post is more of a 'meditation' than a question, really. It can be very useful for beginners, but experts may also find it interesting. When I want my application to sleep for some time, I have several options: First, I can use 'usleep'. The problem with it is that it isn't very accurate, as it basically just employs a "busy loop". Interrupts can wreak havoc in the accuracy of this function since they delay its execution without it being aware of the delay. In fact, all pure-software solutions suffer from this problem since they're inherently interruptible. Hence, the docs assure that usleep will sleep for 'at least' the time specified, and indeed real-life tests show that it oversleeps quite a bit (it also depends on the interrupt activity in your program). Another option is to use the alarm timer. Setup an alarm for an appropriate amount of time, and then wait on a flag that the alarm's ISR turns on. This is very accurate, because the alarm timer is hardware, and isn't interrupted. The drawback of this approach is, I think, the need to implement an ISR for something so simple. The third option, IMHO, brings us the best of both worlds. We can use a wait loop on a timestamp timer, like this (pseudocode): start timestamp timer m1 = timestamp while (timestamp - m1 < desired time) {} Since the timestamp timer is un-interruptible hardware, this method is completely accurate. It also doesn't require an ISR to be implemented. Can you see any obvious / non-obvious problems with this solution ? Thanks in advance