interrupt with delay in main loop

Thread Starter

denison

Joined Oct 13, 2018
283
Just wondering in Arduino programming. If you have a 5 second delay in the main loop does an interrupt still work? Should think it would but not sure. Does anybody know for sure?
 

Ian0

Joined Aug 7, 2020
4,906
If the delay is simply executing NOP instuctions, then the interrupt should work. The 5 second delay will then be extended by the length of time it takes to execute the interrupt.
If the delay is created by a counter, then the main loop will be just checking the counter for completion over and over again, and the interrupt should work, but the delay will remain at 5 seconds.
 

John P

Joined Oct 14, 2008
1,971
An interrupt should work. But I suggest that a delay as long as 5 seconds is a bad idea. It's time when your processor will be doing nothing, and you'd be giving up the opportunity to do anything else. I'd be happier with a regular interrupt at (let's say) 1000 times a second, and if you want a delay, increment a counter to reach it. Like:
Code:
  five_sec_counter = 5000;       // This line is in main(); five_sec_counter is a global variable

// Do this in the interrupt
  if (five_sec_counter != 0)
  {
    if (--five_sec_counter == 0)
       ;      // Action when the delay ends. It could be setting a flag which is periodically checked in main()
  }
 

dl324

Joined Mar 30, 2015
14,357
If you have a 5 second delay in the main loop does an interrupt still work? Should think it would but not sure. Does anybody know for sure?
As long as you're not disabling interrupts.

Using delays is usually a bad idea. Setting up ISR's is usually the way to go.
 

djsfantasi

Joined Apr 11, 2010
8,263
An ISR should do one simple task and then return. That’s it.

It shouldn’t be used to perform tasks asynchronously. It CAN set a flag and the main loop can execute process a more complex task when it has the time.

An example. An ISR reads a character from a serial device and adds it to a string or char array. Return. The main loop determines if all data is received and processed it if ready.

A bad example. Read a character. Check if all data is received. If so process the data. Otherwise, add the character to a string or char array. Return. The main loop does none of these tasks.

The worst, absolute worst, thing you can do is add a delay to your ISR. For at least one very good reason.

ISRs should disable interrupts. Otherwise, you’re inviting data corruption when an interrupt occurs during an interrupt. But if interrupts are disabled and contains a delay - you will (I almost said might) lose data and the execution of your code will become erratic.

The use of interrupts is very powerful… if used correctly.
 
Top