consider
// check multiple buttons and toggle LEDs
enum { Off = HIGH, On = LOW };
byte pinsLed [] = { 10, 11, 12 };
byte pinsBut [] = { A1, A2, A3 };
#define N_BUT sizeof(pinsBut)
byte butState [N_BUT];
#define MAX_DIGIT 5
byte code [] = { 1, 2, 3, 4 };
#define N_DIGIT sizeof(code)
byte combo [N_DIGIT] = {};
byte digit = 0;
char s [40];
// -----------------------------------------------------------------------------
void
dispCombo (void)
{
for (unsigned n = 0; n < N_DIGIT; n++)
Serial.print (combo [n]);
Serial.println ();
}
// -----------------------------------------------------------------------------
void
jumble (void)
{
for (unsigned n = 0; n < N_DIGIT; n++)
combo [n] = random (0, MAX_DIGIT-1);
dispCombo ();
}
// -----------------------------------------------------------------------------
bool
unlocked (void)
{
for (unsigned n = 0; n < N_DIGIT; n++)
if (code [n] != combo [n])
return false;
return true;
}
// -----------------------------------------------------------------------------
enum {
ButInc,
ButNext,
Door,
ButIncRel = 10 + ButInc,
ButNextRel = 10 + ButNext,
DoorClosed = 10 + Door
};
int
chkButtons ()
{
for (unsigned n = 0; n < sizeof(pinsBut); n++) {
byte but = digitalRead (pinsBut [n]);
if (butState [n] != but) {
butState [n] = but;
delay (10); // debounce
if (On == but)
return n;
else
return 10 + n;
}
}
return -1;
}
// -----------------------------------------------------------------------------
void
loop ()
{
switch (chkButtons ()) {
case DoorClosed:
jumble ();
break;
case Door:
if (unlocked ())
Serial.println ("door");
else
Serial.println ("alarm");
break;
case ButNext:
digit = (digit + 1) % N_DIGIT;
break;
case ButInc:
combo [digit] = (combo [digit] + 1) % MAX_DIGIT;
dispCombo ();
break;
}
}
// -----------------------------------------------------------------------------
void
setup ()
{
Serial.begin (9600);
for (unsigned n = 0; n < sizeof(pinsBut); n++) {
pinMode (pinsBut [n], INPUT_PULLUP);
butState [n] = digitalRead (pinsBut [n]);
}
for (unsigned n = 0; n < sizeof(pinsLed); n++) {
digitalWrite (pinsLed [n], Off);
pinMode (pinsLed [n], OUTPUT);
}
dispCombo ();
}