Strange behaviour using "attachInterrupt" and a Joystick

Hi all,
I'm want to use a Joystick as input tool to change the application windows, on a display, and to edit the values.
Instead to stay in pollign captuirng the chage status of the Joystick, I want to use interupts to capture axies and buttom status.

The following code is my test, but have a strange bheaviour. The expectation is that each time a push the buttom, the system print the axies values, but i need to push the button 2 o 3 times to becorectly capture the event.

#define button 3
#define joyY A1
#define joyX A2

bool editMode = false;
int xValue = 0;
int yValue = 0;

void setup() {
  Serial.begin(115200);
  pinMode(button,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), re_valueMod, LOW );
}

void loop() {
  if(editMode) {
    xValue = analogRead(joyX);
    yValue = analogRead(joyY); 

    Serial.print(" -- editMode = ");
    Serial.print(editMode);
    Serial.print(" | xValue = ");
    Serial.print(xValue);
    Serial.print(" | yValue = ");
    Serial.println(yValue);

    delay(500);
  }
}

void re_valueMod() {
  editMode = !editMode;
}

What happens if you use FALLING instead of LOW?

should be volatile. In addition to the above poster suggestion you should implement debouncing routine

@anon73444976
If I use FALLING the situation going worse, the synchronization with the push button is bad and it's required to push it many times to catch the interrupt.
@killzone_kid
What is a debouncing routine? Do you have example or link to study?

The previous answer was done without have declared the variable "editMode" volatile. With the declaration and with the removal of the delay seems that the situation is little bit better.
here the updated code:

#define button 2
#define joyY A1
#define joyX A2

volatile bool editMode = false;
int xValue = 0;
int yValue = 0;

void setup() {
  Serial.begin(115200);
  pinMode(button,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(button), re_valueMod, LOW );
}

void loop() {
  if(editMode) {
    xValue = analogRead(joyX);
    yValue = analogRead(joyY); 

    Serial.print(" -- editMode = ");
    Serial.print(editMode);
    Serial.print(" | xValue = ");
    Serial.print(xValue);
    Serial.print(" | yValue = ");
    Serial.println(yValue);

  }
}

void re_valueMod() {
  editMode = !editMode;
}

Since you have to poll editMode in your loop() function anyway, using interrupt gains you nothing when dealing with something that operates at the speed of a human pushing a button. In fact, interrupts are only making you job more complicated. Polling and a properly implemented debounce algorithm would solve all your problems.

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