For all tasks, the running time t of the task should be less than the time interval under any circumstances. That is, if a task cannot be completed within a specified period of time, the task will be aborted, especially for interrupt programs running in query mode.
For example, such code is unreliable:
// Wait until the adswitch ends (check adci)
While (adcon & adci) = 0 );
In some cases, the system may be suspended due to the following reasons:
A. If the initialization of the ADC is incorrect, it cannot be determined that the ADC will be executed.
B. If the input voltage of the ADC is too high, it may not run at all.
C. If the variable adcon or adci is not correctly initialized, it may not run as required
If the system is required to be reliable, it must be able to ensure that no function will be suspended like this. Loop timeout provides a simple and effective way to ensure this.
Loop timeout is easy to create. The code structure is based on the software latency:
UINT16 Timeout_loop = 0;
...
while(((ADCON & ADCI) == 0) || (++Timeout_loop == 0));
Or
UINT16 Timeout_loop = 1;
...
while(((ADCON & ADCI) == 0) || (Timeout_loop == 0))
{
Timeout_loop++;
}
The advantage of the latter is that it is very convenient to comment out the loop timeout. If the above error occurs again, at least the program will not stay here and continue to execute, of course, there should be corresponding methods to handle such errors.
Note:
This loop timeout is implemented by software delay, so it is not easy to control the delay time accurately, and there is no good portability. You can use a hardware timer instead.
For example, if the 8051 timer 1 is enabled and the timer is set to 10 ms
while((ADCON & ADCI) == 0) || ! TF0);