The solution for anything over three buttons is to start using a struct or class. Below uses a struct.
struct BUTTONACTION
{
byte pin;
char *txt;
bool addNewline;
};
A struct is like a record in a phone book with e.g. first name, last name and phone number. The above links a pin (where the button is connected) to a specific text (that will be 'printed' when the button is pressed). The addNewline allows you to send a new line after the text is 'printed'. Keyboard.println() does not seem to send the cursor to the beginning of a new line).
Next you can declare an array with an entry for each button action.
BUTTONACTION buttonActions[] =
{
{2, "Hello", false}, // pin 2, text to 'print', do not send KEY_RETURN
{3, "World", true}, // pin 3, text to 'print', send KEY_RETURN
// add more here
};
In setup(), you can set all the pins to INPUT_PULLUP.
void setup()
{
// start keyboard functionality
Keyboard.begin();
//setup all button pins for INPUT_PULLUP; buttons need to be wired between pin and ground
for (int cnt = 0; cnt < sizeof(buttonActions) / sizeof(buttonActions[0]); cnt++)
{
pinMode(buttonActions[cnt].pin, INPUT_PULLUP);
}
}
And in loop you can loop through the array
void loop()
{
static int buttonNumber = 0;
if(digitalRead(buttonActions[buttonNumber].pin) == ISPRESSED)
{
Keyboard.print(buttonActions[buttonNumber].txt);
if(buttonActions[buttonNumber].addNewline== true)
{
Keyboard.write(KEY_RETURN);
}
// a crude debounce
delay(100);
// wait for button to be released
while (digitalRead(buttonActions[buttonNumber].pin) == ISPRESSED)
{
// do nothing
}
}
// next button
buttonNumber++;
if(buttonNumber == sizeof(buttonActions) / sizeof(buttonActions[0]))
{
buttonNumber = 0;
}
}
Compiles, not tested.