multiple buttons

Hi,

I am working on a project with 11 buttons.
What i want is to detect which buttons has been pressed and start a function accordingly. But nothing should happen when 2 buttons are pressed at the same time or when a function is still running.

Kind regards,

Erik

Does it matter how many pins are used? You could use individual digital pins, or you could use a few analog pins. Will you be connecting other devices to the Arduino?

Hi,

I am using the arduino mega. So pins enough.
I am connecting also analog input devices. Also a couple of digital outputs and three communication devices.

Below a piece of code I Wrote to test with two buttons:

// button test

int buttonPins[] = { 2, 3, 4, 5, 6, 7, 8, 12 };
int pressed = 0;
int which = -1;

void setup() {
  for (int i=0; i < 8; i++) {
    pinMode(buttonPins[i], INPUT);
  }
  
  Serial.begin(9600);
}

void loop() {
  which = -1;
  for (int j = 0; j < 8; j++) {
    pressed = digitalRead(buttonPins[j]);
    
    if (pressed == LOW) {
      which = j;
      //Serial.println(j);
     // break;
    }
  }
  actie(which);
}


void actie(int i) {
  switch (which) {
    case 0:
    Serial.println("A");
    break;
    case 1:
    Serial.println("B");
    break;
    
  }
}

This code tells me which buttons has been pressed. Also when button 'B' is pressed it will not process the press of button A. The otherway around; when I press button A it will also process the press of button B.

This kinda confusses me

Kind regards,
Erik

The loop function is called endlessly, potentially millions of times per second. The last button pressed in any pass will be the one whose action is invoked.

If you press the button attached to pin 2, only, all 8 pins are read. Only pin 2 is low, so which will be 0 when the for loop ends, so actie will be called with a value of 0.

If you press the button attached to pin 3, only, all 8 pins are read. Only pin 3 is low, so which will be 1 when the for loop ends, so actie will be called with a value of 1.

If you press both buttons, all 8 pins are read. Pins 2 and 3 will be low, so which will be 1 when actie is called.

If you want to call actie when only one button is pushed, you will need to count the number of LOW readings, as well as recording (in which) which button was pressed.

You may need to deal with switch bounce, depending on the buttons you use - an easy way to do this is to read the inputs every few milliseconds and take no action until successive loops read the same input - thus switch-bounce glitches don't cause ill effects.

Dear PaulS & MarkT,

Thank you both for the quick replys.
I have implemented a presscount. This works fine for me.

As to the switch debounce: I will take this into consideration. For now the debouncing is dealt with by the processing programm I am using to play audio en movie.

Erik