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?