state change detection of multiple buttons on the same board

hello,
I need to read a bunch of buttons.

I inspired my code from http://arduino.cc/en/Tutorial/ButtonStateChange
But I altered it to use an array.

/*
 Sensor reader firmware
 it reads sensorNumber sensors all plugged from the DIN 0 to n-1
  */

const int ledPin =  13;      // the number of the LED pin
const int sensorNumber = 2; // <<< change it

int sensorState[sensorNumber];
int sensorDetectionCounter[sensorNumber];
int sensorLastState[sensorNumber];


void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);     

  for (int n=0 ; n < sensorNumber ; n++)
  {
    pinMode(n , INPUT);
    sensorState[n] = 0;
    sensorDetectionCounter[n] = 0;
    sensorLastState[n] = 0;
  }  
}

void loop(){

  for (int n=0 ; n < sensorNumber ; n++)
  {
    
    sensorState[n] = digitalRead(n);

    if (sensorState[n] != sensorLastState[n]) {

      if (sensorState[n] == HIGH) {
        sensorDetectionCounter[n]++;
        Serial.println("on");
        Serial.print("number of button pushes:  ");
        Serial.println(sensorDetectionCounter[n], DEC);
      } 
      else {
        Serial.println("off"); 
      }
    }
    sensorLastState[n] = sensorState[n];

    if (sensorDetectionCounter[n] % 4 == 0) {
      digitalWrite(ledPin, HIGH);
    } 
    else {
      digitalWrite(ledPin, LOW);
    }

  }
}

it doesn't seem to work fine (the digital pin 1 seems to flip flop everytime high & low)

do you think I made a logic mistake?
I'd need to know if my error comes from the code or another (weird) thing.

regards,

it doesn't seem to work fine (the digital pin 2 seems to flip flop everytime high & low)

Your code does not do anything with digital pin 2. Pins 0 and 1 are the pins effected by your code.

Which pins did you want to use? 2 and 3?

made a mistake in my post
correcting that

I meant: strange flip flop on the 2nd pin, which is the pin number 1 , indeed...

In this prototype, I use digital pin 0 & 1.

sorry

Um... I'm going to go with the most obvious answer

Did you use a pull-down resistor? (or pull-up, either one would work, they just work opposite of each other)

Pin 0 and 1 are the serial port. The "Serial.print" calls are very likely causing the toggling. If you use Serial, you can't use pins 0 and 1 for input/output.

yes for the pull resistor
ok for the 0 & 1

I forgot about that :frowning:

I'll use them from the 3rd (number 2) to 8th

thanks a lot !!

Oh, didn't catch that >.>