byte button[] = {30, 26, 28, 32};
byte numberOfButtons = 4;
byte buttonState[numberOfButtons];
byte activeButton[numberOfButtons];
boolean hit;
void setup()
{
for (byte i = 0; i < numberOfButtons; i++)
{
pinMode(button[i], INPUT_PULLUP); //Check for LOW for a button press
}
Serial.begin(115200);
}
void loop()
{
for (byte i = 0; i < numberOfButtons; i++) //read all buttons at beginning of loop()
{
buttonState[i] = !digitalRead(button[i]);
}
for (byte i = 0; i < numberOfButtons; i++)
{
if (buttonState[i] && (!otherButtonPressed(i) || activeButton[i])) //if no other buttons are active or this one is already active
{
activeButton[i] = true;
Serial.print(i+1);
}
else
{
activeButton[i] = false;
}
}
}
boolean otherButtonPressed(byte currentButton)
{
hit = 0;
for (byte i = 0; i < numberOfButtons; i++)
{
if (i == currentButton)
{
continue; // skip test for button passed to function
}
if (activeButton[i] == HIGH) // if any other button is currently the active one
{
hit = true;
}
}
return hit; //Were any other buttons already pressed?
}
Why does he use byte arrays? The first array ,button[] , is a set of integers so shoudnt it be an int array?
The he declares the number of buttons as a byte. Shouldnt it be an integer?
Then buttonState is a byte array but he sets button state to the output of digitalRead. I thought digitalRead returns high or low. Is that a boolean value?
Then the activeButton array is also declared as a byte array . But later in the code he sets it to true or false. Isnt that a boolean?
I am quite confused by the use of byte in the declaration of variables.
And in his main loop he has this statement:
if (buttonState[i] && (!otherButtonPressed(i) || activeButton[i])) //if no other buttons are active or this one is already active
How can he use the value of activeButton[i] before it is ever initialized or set?
Finally, dont I have to worry about 'debouncing' and add delays?
As you might imagine, I am trying to write code to efficiently monitor momentary button presses and happened across this code in my research.
Hello skypickle
Generaly spoken:
Sometimes it is helpful and useful to read, study and understand the Arduino instruction set. Aspecially to have a view to return values given.
eg
A digitalRead() returns an either a HIGH or LOW using the datatype INT.
In this way you can check the complete sketch by yourself.
Have a nice day and enjoy coding in C++.
Дайте миру шанс!