Simple interrupt question

Fluxanode

Well-known member
In the following program
Code:
const int buttonPin = 2;  // Pin for button

void buttonISR() {
    Serial.println("Button Pressed! Sending message...");
    delay(1500);
}

void setup() {
    Serial.begin(9600); // Initialize USB serial for debugging
 
    pinMode(buttonPin,INPUT); // Set pin as input
    attachInterrupt(digitalPinToInterrupt(buttonPin), buttonISR, RISING); // Interrupt on rising edge
}

void loop() {
    // Empty loop since processing is handled in ISR
}

The button pressed message is sent twice with each press of the button. I know about debounce and thought the delay would cover that (it did help a lot) but it seems the ISR is still executed twice?
 
Firstly you shouldn't be calling delay in an ISR, it locks up the processor!

Also its a bad idea to use Serial object in an ISR, serial relies on other interrupts to work.

Secondly the ISR is potentially called on every bounce - you can't stop that, you have to be intelligent in the ISR about whether this call is a bounce or not, and ignore the bounces (use timestamps for this).

If your button is pressed by a human an ISR is overkill, interrupts are for fast things that have to be handled urgently (microseconds), whereas HMI works on timescales of 10's of ms or so.
 
I plan on using it to send a zero totalizer command via modbus to a flow meter using a momentary button switch. Do you have another suggestion to do this on a button press?
 
Normally the Bounce library is used to read pushbuttons and other mechanical switches. It deals with the mechanical chatter that could otherwise give false readings.

Several of the Teensy examples use it. In Arduino, click File > Examples > _Teensy > USB_Keyboard > Buttons to see the basic usage.
 
Back
Top