Page 1 of 1

Delays and interrupts

Posted: Thu Mar 11, 2021 7:14 pm
by alanwms
Does a delay take into account an interrupt? If I had a simple loop flashing an LED using delays - for visual monitoring of a running program, and an interrupt starts, does the delay have an effect on the stack?

Also, if the reverse is true, and a delay is in the interrupt routine, will that mess up the stack? Even if I disable interrupts while performing the interrupt?

Re: Delays and interrupts

Posted: Thu Mar 11, 2021 9:05 pm
by mnfisher
Interrupts can occur while a delay is 'running'

So

Delay 1s
- UART Rx interrupt(s) - add chars to circular buffer....
..
Delay finishes - process input..

The delay does (in effect)
while (ms < 1000) ms = Getms();

On an interrupt - the processor saves the current context - performs the interrupt code - then restores the current context and resumes where it left off. (Note that an interrupt can only occur after an instruction completes - and the 'context' (registers, program counter and flags) are usually stored on the stack..

The opposite is not true - and it is a mistake to have a delay in an interrupt handler. Interrupt handlers should always be as fast as possible - and using code that might rely on interrupts in them (timing or i.o. for example) will result in heartache...

Martin

Re: Delays and interrupts

Posted: Thu Mar 11, 2021 9:36 pm
by kersing
Delay executes a number of ‘no operation’ instructions, an instruction that tells the controller to just wait a for small amount of time. To get the delay correct flowcode calculates the number of these instructions to execute and constructs a loop to call the right number of them.

If an interrupt occurs during the delay the total delay will increase by the amount of time spend in the interrupt routine. If the interrupt takes 1 second (not a good idea, interrupt routines should finish fast) and the delay was 1 second the delay will finish after 2 seconds.

Delay can not correct for time spend in an interrupt routine because most of the controllers do not have a realtime clock providing timing information required for such timing corrections.

Calling any macro (including delay) from an interrupt routine might create issues because some macros are constructed in a way that does not allow it to be called twice in parallel. The PIC compilers will display a warning in cases where this might occur in the code. If such a warning is displayed the code requires restructuring to remove the potential parallel calls.