Interrupt Bad practise?

Hey guys, i am writing on an System that goes in the direction of real time system / multithreaded system and i think i am using interrupts wrong/bad and would like to hear your opinion.

The System needs read permanently a few sensors and work with the data.
Additionally i am using an Interrupt that is being triggered when i make an input (key pressed down).
The problem is, that i have to debounce the keys while not being able to add an delay.

For this the code is like this:

#include <Event.h>
#include <Timer.h>

Timer InterruptReenableTimer;


const int InputInterruptPin = 2;  // The Interrupt Pin

const int ButtonDebounceTime = 10;


volatile boolean Input;

void setup() {

  pinMode(InputInterruptPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(InputInterruptPin), inputDetectedKeyDown, LOW);
}

void loop() {
  
  // read the analog in value:


  handleInput();

  // Write the Input of the sensors into an Array

  // I Array is full, analyse the data of sensor1
  // analyse the data of sensor2
  handleInput();
  // analyse the data of sensor3

  InterruptReenableTimer.update();
  
  // Delay for about 5 ms
}



void inputDetectedKeyDown() {
  Input = true;
  detachInterrupt(digitalPinToInterrupt(InputInterruptPin));
  InterruptReenableTimer.after(ButtonDebounceTime, enableInputDetectedKeyUp);
}

void inputDetectedKeyUp() {
  detachInterrupt(digitalPinToInterrupt(InputInterruptPin));
  InterruptReenableTimer.after(ButtonDebounceTime, enableInputDetectedKeyDown);
}

void handleInput() {
  if (not Input) {
    return;
  }

  
  Input = 0;
  if (digitalRead(LED_BUILTIN) == HIGH) {
    digitalWrite(LED_BUILTIN, LOW);
  }
  else {
    digitalWrite(LED_BUILTIN, HIGH);
  }
}

void enableInputDetectedKeyUp() {
  attachInterrupt(digitalPinToInterrupt(InputInterruptPin), inputDetectedKeyUp, HIGH);
}

void enableInputDetectedKeyDown() {
  attachInterrupt(digitalPinToInterrupt(InputInterruptPin), inputDetectedKeyDown, LOW);
}

I am enabling and disabling Interrupts while being in the ISR. This should not be done (the arduino reference links to this page Gammon Forum : Electronics : Microprocessors : Interrupts). Is this really that critical?

By the way: How long does it take to enable and dissable interrupts?
greetings

X-Ray

I am enabling and disabling Interrupts while being in the ISR.

Interrupts do not happen while your ISR is running, so disabling interrupts is unnecessary. Re-enabling interrupts before the end of the ISR is NOT something you should be doing, unless you REALLY know what you are doing. Re-enabling them at the end of the ISR is unnecessary, since that will happen automatically when your ISR ends.

However, that is NOT what you are doing. You are detaching and reattaching your interrupt handler.

That is NOT the way to debounce your switch. What you should do is, when the ISR is called, capture the current time (using millis()) and compare that to the previous time the ISR was called. If the times are too close together, just return (that is, ignore the interrupt). If they are far enough apart (that is, if this is actually a meaningful event), do whatever needs doing.

Dealing with switch presses should NOT require interrupts.

The crux of the whole input/debounce/interrupt thing is that you write your code to be "non-blocking", that way it runs through the loop rapidly such that event changes (keypress etc) arent missed.

Theres a few tricks/tips, which essentially boil down to;

  • Dont use "delay(xx)". Delays block, instead you can use timers (look at the blink without delay examples
  • DO use 'state machines' to track the status of things (this can be as simple as "boolean buttonPress=true")
  • DO understand the underlying timing of things, eg your debounce of 10mS is rather low

There are libraries around to do timing, button management and state machines, some of them are excellent. Personally Ive started doing more of this myself directly, since I want to understand whats going on (and Im still learning).

As for interrupts, they can have a place for button management, but in general its best to handle buttons via the above techniques.

All that said, what sort of sensors are you running and how often do you really need to act upon their output?

Have a look at several things at a time - no interrupts required.

...R

Thank you very much, now i am using millis and comparing the times.... I have no idea why i did not come to this idea myself....

I have always done this by setting up 1kHz or whatever timer. Then in the ISR have it update a global variable, something like 'ms'.

When ever a button is pressed make sure it is reading consistently for like 5ms or something.

millis() also delays the code. Timer interrupts are the best way of doing this.

tonyd5:
millis() also delays the code.

Do explain ...

...R

It is NEVER necessary to use interrupts for buttons pressed by humans. It's like using chemistry lab equipment to measure a glass of beer. Just pour the damn beer in the glass and skip the complex equipment.

Well, i am not quite sure how long the loop will need, but i think it could take longer then the press of a button. I analyse and filter data in it coming from about 6 sensors and filling nearly the whole RAM of the mega.
And if i am not using the interrupt, the problem with debouncing without delaying also present.
By the way: I am not using an interrupt per key, but one to indicate that any key was pressed.

Does anybody know how long it takes to read millis and how long to disable and enable an interrupt tho?

X-Ray-H3:
Well, i am not quite sure how long the loop will need, but i think it could take longer then the press of a button.

Then the code probably needs a re-write. You should plan on loop() repeating 100s or 1000s of times per second.

These are irrelevant questions

Does anybody know how long it takes to read millis and how long to disable and enable an interrupt tho?

they are so fast that their time does not matter unless you need to do something with microsecond precision.

I don't understand what you had in mind when you wrote this

And if i am not using the interrupt, the problem with debouncing without delaying also present.

The processes of avoiding switch bounce and/or detecting the change of state of a switch will be much the same with or without an interrupt. Switch bounce is avoided by leaving a short interval between successive reads (actually easier WITHOUT and interrupt) and state change is just a matter of recording the previous state and comparing it with the present state.

...R

Well, even with rewrite i can't speed things up. Normally, the loop needs about 7ms but when the buffer is full (after about 4 seconds), i have to analyse the data, and that means iterating through all arrays, maybe even sort them and calculate stuff. The most time should be consumed by the iteration through the array, what can't be improved i would say.

The questions about the length of the interrupt: I am planning to leave this device on 24/7 and for a long long time where it need the current time. While being in the ISR the time counters wont increase and so (without using a RTC module) there is a timedrift that could be minimized by using the one over tho other. In this application it is not super critical, but in others it might, so take that question as a general one.

The "normal" software debouncing technique i learned back in school was wait for a change, delay, look if the change i there again and then decide.

While bouncing, the interrupt will be triggered not only 2 times (in case it is a on change interrupt) but several times. Jumping into an interrupt is not that fast compared with just running the next command so i would like to minimize that. With my, rather ugly solution there are 2 interrupts per input, with the other solution there are at least 2, probably many more triggered interrupts per keypress so it is probably not that efficient.

because i really don't want to check after every few lines of code if a key is pressed, the interrupt is the way to go (in my case).

Some possibilities ...
Hardware debouncing.
Use the main loop itself to iterate through time consuming tasks.

yeah, i also took a look at that, but i am a bit skeptical. Is it really that simple and reliably?

It's as simple and reliable as you make it.

Another thing to think about...

First, check reaction time to pressing a button here.

  • Get to know your functions or blocks of code and how long it takes to execute.
  • Break up slow functions into several faster functions if necessary.
  • Shoot for checking button status at slowest every 80ms, then no key presses should be missed.

dlloyd:
Use the main loop itself to iterate through time consuming tasks.

+1

...R

X-Ray-H3:
The questions about the length of the interrupt: I am planning to leave this device on 24/7 and for a long long time where it need the current time. While being in the ISR the time counters wont increase and so (without using a RTC module) there is a timedrift that could be minimized by using the one over tho other. In this application it is not super critical, but in others it might, so take that question as a general one.

Not true. millis() will increment just fine if you are inside or outside an interrupt. The only problem is if you kill interrupts for more than 128 milliseconds, then it will skip by that amount. That's why interrupts must generally be kept short: a few microseconds to tens of milliseconds.

You can't expect to keep anywhere close to the current time for more than a day running on the internal oscillator. It simply isn't accurate enough to keep time like that. If you need current wall-clock time then you need an RTC or a GPS. There's no shortcut.

X-Ray-H3:
because i really don't want to check after every few lines of code if a key is pressed, the interrupt is the way to go (in my case).

You don't have to check every few lines of code if a button is pressed. This is how you can break a time-consuming task

/*
  sum elements in an array with positive values
  in:
    pointer to array
    number of elements
  returns:
    -1 while calculation is in progress, else calculated sum
*/
long calcSum(byte *data, int len)
{
  // index into array
  static int index = 0;

  // sum
  static long sum = 0;

  // at start, reset sum to 0
  if(index == 0)
  {
    sum = 0;
  }

  // if not all elements done
  if(index < len)
  {
    sum += data[index++];
    // indicate summing in progress
    return -1;
  }
  else
  {
    index = 0;
    // indicate summing finished
    return sum;
  }
}

And in e.g. loop()

byte data[1000];

void setup()
{
  Serial.begin(115200);
}

void loop()
{
  long x = calcSum(data, 1000);
  if(x >= 0)
  {
    Serial.printl(x);
  }
}

Each time that you go through loop, you call calcSum; calcSum in turns adds one single element of the array to the sum at a time and goes back to loop() (this will take a few microseconds (2 or maybe 3), I suspect). If calcSum returns a negative value, it indicates that summing is still in progress (-1 is used in this case as the sum of positive values can't be negative). If calcSum returns a value greater than or equal to 0, the sum process has completed and the result can be printed.

Obviously you might need a slightly different approach if the sum can be negative.

It might be clear that you have plenty time to debounce a button using millis(), flash a led using millis() and read your sensor array (maybe one at a time using a similar principle).

Hope this helps; again, check out Robin2's article (linked earlier in reply #3).