I have written code to execute a special action in the event two buttons become pressed within a defined "tie" parameter (in this case 1 second). Can this be done better?
//TWO BUTTONS - How to define and act upon a Tie
const int button1 = 2;
const int button2 = 3;
const int buttonDelay = 300; // button bounce mitigation
unsigned long buttonTime = 0; // button bounce mitigation
byte button1State = 0; //variable and initial state for Tie
byte button2State = 0;
byte tieState = 0; //variable to trigger Tie action
const int tieDelay = 1000; // button bounce mitigation
unsigned long tieTime = 0; // button bounce mitigation
void setup()
{
pinMode(button1, INPUT_PULLUP); // pushbutton pins are high and use built-in resistor
pinMode(button2, INPUT_PULLUP);
}
void loop()
{
// read buttons and set buttonStates
if (millis() - buttonTime >= buttonDelay) // button bounce mitigation
{
if (digitalRead(button1) == LOW) // button1 is pressed
{
button1State = 1;
}
}
if (millis() - buttonTime >= buttonDelay) // button bounce mitigation
{
if (digitalRead(button2) == LOW) // button2 is pressed
{
button2State = 1;
}
}
if ((button1State == 1) && (button2State == 1))
{
tieState = 1;
}
// action if only button1 pressed after a second
if (millis() - tieTime >= tieDelay) // second to check for tie
{
if (millis() - buttonTime >= buttonDelay) // button bounce mitigation
{
if ((button1State == 1) && (tieState = 0)) // button1 is pressed
{
//Put button1 action here
button1State = 0;
button2State = 0;
tieState = 0;
buttonTime >= buttonDelay;
tieTime >= tieDelay;
}
}
}
// action if only button2 pressed after a second
if (millis() - tieTime >= tieDelay) // second to check for tie
{
if (millis() - buttonTime >= buttonDelay) // button bounce mitigation
{
if ((button2State == 1) && (tieState = 0)) // button2 is pressed
{
//Put button2 action here
button1State = 0;
button2State = 0;
tieState = 0;
buttonTime >= buttonDelay;
tieTime >= tieDelay;
}
}
}
// action in the event of a tie
if (tieState = 1) // tie is recorded
{
//Put tie action here
button1State = 0;
button2State = 0;
tieState = 0;
buttonTime >= buttonDelay;
tieTime >= tieDelay;
}
}