I have built a basic obstacle avoidance robot. When the sensor senses an obstacle it gives a RISING interrupt to pin 2. At this moment I want the robot to come back for 2 seconds and turn right for 2 seconds.

I have code to turn back and rotate right but I cannot use the delay() function inside the ISR so how do I code this?


An ISR should be kept as short as possible, since while it runs, no other interrupts can be handled (including the one powering the delay() function. Thus you cannot delay that easy inside an ISR and you shouldn't do it either.

Instead you should set a simple flag variable in the ISR and then check this flag inside your loop() function. If the flag is set, you can execute the corresponding code inside the main code instead of inside an ISR.

A typical flag definition is a single byte (since then every read/write action is atomic and cannot be interrupted by an ISR). Be sure to set it volatile, so that the compiler knows, that this variable may change any time.

volatile byte interrupt_flag = 0;

In the ISR you can set this variable to 1 for example and then in your main loop() function:

    // Do whatever you need to do here
    interrupt_flag = 0; // reset the flag variable
  • In that case, the robot won't stop immediately when the interrupt is given, it will run the forward function and when it comes out of that function it will poll for the interrupt flag and then stop. – The White Cloud Jan 13 '20 at 11:04
  • 2
    If your code has to react quickly, you have to speed up loop() and the functions you call there. ISR are NOT intended for this purpose. Probably you do not need an ISR at all. – DataFiddler Jan 13 '20 at 12:56
  • 1
    If you write your code without delays, the time between interrupt trigger and flag polling is so short, that you don't see it. Refer to the BlinkWithoutDelay example to learn the principle of doing timed things without blocking other code with delay. – chrisl Jan 13 '20 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.