ISR and variable incrementing

Hello there,

I have trouble using a simple button connected to a NodeMCU and an ISR to increment a simple variable. Here is the relevant code i use:

#define BTN 5

int selectedEffect = 0;

volatile int flag = 0;
int flagValue = 0;



void setup(void) {
 attachInterrupt (digitalPinToInterrupt (BTN), changeEffect, RISING); // pressed
  
}


void loop(void) {
  noInterrupts();
  flagValue = flag;
  interrupts();
   
if (flagValue == 1) {
      flag = 0;
      flagValue = 0;
      selectedEffect++;
      Serial.println(selectedEffect);
   }
   
  if(selectedEffect>18) { 
    selectedEffect=0;
  } 
  
  switch(selectedEffect) {
// CODE
  }
}

ICACHE_RAM_ATTR void changeEffect() {
  flag = 1;
}

Whenever i push the button the variable gets incremented several times.

Any idea?

I guess that that is caused by bounce.

Your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advice on) your project.

First off, suggest you wire switches as S3 is wired below.


Second, switches being monitored by interrupt logic will be a disaster.

Use poling of your switches (say every 50ms) and look for a switch change in state.

My active low state change tutorial may be of interest.

As shown in the tutorial, a 0.1uF ceramic cap across the switch will help to denounce the switch. It the is S3 of the schematic of @LarryD with a cap across the switch.

Hello,

Thanks for your inputs.

I wired by switched with an external pull down (which i forgot to mention). Now i get this is bad :slight_smile:

I'll try using the internal pullup, which i believe can be achived on all inputs but GPIO16 on NodeMCU (GPIO16 is using pulldown). I'll also add a cap and see if thats better.

Thanks

EDIT : i rewired using internal pullup and ceramic cap and modified the code consequently.

When i press the button only one increment, but when i release it i have one or two more increments. Also after a few presses the ESP hangs and resets.

I finally resigned to using a simple polling in the loop function and it works fine for my need.

Thanks a lot

1 Like

Really, using an interrupt for a human interface is not appropriate, anyway. Properly written non-blocking polling code will not miss button presses.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.