Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
Valued Contributor III
728 Views

accurate "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&#39;t require an ISR to be implemented. 

 

Can you see any obvious / non-obvious problems with this solution ? 

 

Thanks in advance
0 Kudos
2 Replies
Highlighted
Valued Contributor III
4 Views

I think that for sure using the third solution (the timestamp) should work fine.  

 

The only drawback is the same as usleep: the system cannot perform other activities while sleeping. 

 

If you are developing a really simple application, that could be a good solution. 

 

On the other hand, if the application starts to be complex, I would suggest using an RTOS task for each job to be performed, and each task could be woken up by appropriate alarms. 

 

Paolo
0 Kudos
Highlighted
Valued Contributor III
4 Views

Fourth option would be to write your own peripheral in VHDL/Verilog. Seems a terrible waste to not use some of the programmable logic that the processor&#39;s buried in.....

0 Kudos