Buttons lib

Hi,

On top of the learning examples from Arduino site I'm trying to make helper functions to monitor buttons state. Here is the code:

#define DEBOUNCE 10

struct button
{
  int pin, lastPush, lastState, state;
  boolean pressed, tillNextChange;
};

struct button buttons[] = {
  { 3 },
  { 2 },
};

#define NUM_BUTTONS  (sizeof(buttons)/sizeof(struct button))

boolean buttonPressed(struct button *btn)
{
  if (btn->pressed && !btn->tillNextChange)
  {
    btn->tillNextChange = true;
    return true;
  }
  else if (!btn->pressed)
  {
    btn->tillNextChange = false;
    return false;
  }
}

void buttonsTask(void)
{
  int reading;
  
  for (int i=0; i<NUM_BUTTONS; i++)
  {
    reading = digitalRead(buttons[i].pin);
    if (reading != buttons[i].lastState)
      buttons[i].lastPush = millis();
    if (millis() - buttons[i].lastPush > DEBOUNCE)
    {
      if (buttons[i].state == HIGH && reading == LOW)
      {
        buttons[i].pressed = true;
      }
      else if (buttons[i].state == LOW && reading == HIGH)
      {
        buttons[i].pressed = false;
      }
      buttons[i].state = reading;
    }
    
    buttons[i].lastState = reading;
  }
}

void setup()
{
  Serial.begin(9600);
  
  for (int i=0; i<NUM_BUTTONS; i++) {
    pinMode(buttons[i].pin, INPUT);
    digitalWrite(buttons[i].pin, HIGH);
  }
}

void loop()
{
  buttonsTask();
  
  for (int i=0; i<NUM_BUTTONS;i++)
  {
    if (buttonPressed(&buttons[i]))
      Serial.println(i);
  }
}

buttonPressed function should return a true value when a button input pin goes from HIGH to LOW for single loop call. The problem is that it works for every button except one under index 0 in buttons array. Any clues why does it happen?

When an instance of a structure is created, you need to explicitly value every member of the structure. The compiler does not do it for you.

You are currently only valuing the pin member.

The rest are garbage.

Try initializing all members with valid data.

I have already checked this, still the same.
In loop() i get a single true return value from buttonPressed as I expect it, but when I press 0 indexed one, function fails and returns true all the time. Even with fully initialized structure.

Does it matter what order the instances are in the array? Or, is it that pin 2 has a problem, and whatever is connected to that pin isn't working right?

It turns out that it matters, when I added an extra button to the array the one under pin 2 worked correctly. First I thought I messed up the for loop ranges but everything seems to be ok, all of them start with 0 and end with appropiate value.

Strange .. I'm going to test it out with vanilla gcc compilator to see what happens ..