I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.
As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.
const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
const int LED = 9;
volatile bool lsEngaged = false; // flag for limit switch engaged
void setup() {
pinMode(lsOuterLeftIn, INPUT_PULLUP);
pinMode(LED, OUTPUT);
attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
}
void loop() {
if (lsEngaged) digitalWrite(LED, HIGH);
else digitalWrite(LED, LOW);
}
void ISR1(){
delay(100);
lsEngaged = (digitalRead(lsOuterLeftIn));
}
void ISR2(){
delay(100);
lsEngaged = (digitalRead(lsOuterLeftIn));
}
But, here is my problem. I came upon this Arduino documentation page, and it says
"Since delay() requires interrupts to work, it will not work if called inside an ISR. "
But, I do make use of delay()
inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the delay()
function could malfunction on me as the documentation says?
1 Answer 1
What you can do (and is anyway far better than waiting in interrupt context), is to have a volatile variable, which you set in the interrupt (say to 1) and in the main loop you check it: once it is set, you execute the delay and then read the value.
Alternatively, if you can change the sensor, just trade the mechanical switch for an optical end run sensor. If your moving object has steady movement, you will not get any bounces from the optical coupler. Then you can just poll it.
-
Of course there are much nicer ways to deal with the problem, but they tend to be more complex (you could read about bottom halves, for example) than what you might be willing to spend time on.Igor Stoppa– Igor Stoppa2015年10月27日 12:30:59 +00:00Commented Oct 27, 2015 at 12:30
Explore related questions
See similar questions with these tags.