Delay in ISR function

I have an interrupt function that is triggered by a button being pressed
And I want that function to show some data on the lcd display for a specific amount of time (4 seconds for example )
I know I can't use delay and millis, so my question is how to delay a specific amount of seconds with a for loop that runs without instructions?
Example : for(int I=0;I<=some number;I++){nothing} ---> delay 4 seconds

1 Like

You don't. In fact, there's no reason to use an interrupt for a button press.

But, if you insist on doing so (for "learning exercise", etc), then just set a flag in the ISR noting that the button has been pressed. Then pick up (and clear) that flag in your non-ISR main code. Do whatever task time-consuming task is required there.

1 Like

See the blink without delay example in the IDE, without delay.

Your for loop will be optimized away to nothing when the compiler sees that it does nothing.

But you can use delayMicroseconds(). It can only delay up to 65535 microseconds so you have to call it multiple times. Let's do 50 milliseconds (50,000 microseconds, 1/20th of a second) each time to make the calculation easier.

If you want your sketch to freeze for 4 seconds:

  // 4 seconds / 0.050 seconds = 80
  for (int i=0; i < 80; i++)
    delayMicroseconds(50000u); // 50 ms

It will be interesting to see what goes horribly wrong when you keep interrupts disabled that long. :slight_smile:

You should not use delay(), millis(), any sort of I/O that relies on other interrupts, or spend any more time in an interrupt than is necessary. If you are just processing a button press and your code is written properly then you should not need interrupts at all. I have written several rather complex controllers using an Arduino and did not use any interrupts other than those required for the serial interface and libraries I used.

Interrupts should not be used unless you thoroughly understand the hardware and timing requirements of the device as a whole.

Hello inkdomink
Do you have a sketch? If YES, post the current sketch to see how we can help.
Post it well formated, with comments and in so called code tags "</>" and schematic.
Have a nice day and enjoy coding in C++.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.