//This define allows the code to be simulated by WOKWI
//Comment out the following line when compiling for the real device
#define SIMULATE
#ifdef SIMULATE
//These values would otherwise be undefined in the simulation (No buttonboard library )
#define KEY_UP_ARROW 'U'
#define KEY_DOWN_ARROW 'D'
#define KEY_LEFT_ARROW 'L'
#define KEY_RIGHT_ARROW 'R'
#else
#include <buttonboard.h> //Including the buttonboard library
#include <Mouse.h> //Including the mouse library
#endif
// Declare a structure to hold information about each button
#define BUTTONS 10 //Number of buttons
struct Info {
int PinNo; //The Arduino Pin Number to which this button is connected
char OutChar; //Data to send for this button
boolean buttonState; //State of the button when last checked
unsigned long startLow; //Time when it last became low (pressed)
unsigned long nextRepeatAt; //Repeat the output character again after this period in Msecs
};
// This structure holds the Pin Numbers and the correspnding output characters plus timing data relating to each button
Info button[BUTTONS] = {
{2, '1', 1, 0, 0},
{3, '2', 1, 0, 0},
{4, '3', 1, 0, 0},
{5, '4', 1, 0, 0},
{6, KEY_UP_ARROW, 1, 0, 0},
{7, KEY_DOWN_ARROW, 1, 0, 0},
{8, KEY_LEFT_ARROW, 1, 0, 0},
{9, KEY_RIGHT_ARROW, 1, 0, 0},
{10, '+', 1, 0, 0},
{16, '-', 1, 0, 0}
};
void setup() {
Serial.begin(115200);
//Set up the buttons and the internal pull-up resistors
for (int i=0;i<BUTTONS;i++){
pinMode(button[i].PinNo, INPUT_PULLUP);
}
}
void loop() {
checkButtons();
}
void checkButtons(){
#define PERIOD 10 //Time in mSecs between checking the buttons
//static variables retain their values between passes through the loop
static unsigned long lastcheck = 0;
static unsigned long now = 0;
//Check all buttons every PERIOD mSecs - simplifies anti-bounce tests
if (millis() - lastcheck < PERIOD ) {
return;
}
//Time to check the buttons again
now = millis();
lastcheck = now;
//Go through checking all the buttons
for (int i=0;i<BUTTONS;i++) {
//Check the state of each button
int newState = digitalRead(button[i].PinNo); // read the state of the button
if (newState == LOW && button[i].buttonState == HIGH) {
output(button[i].OutChar,HIGH);
}
if (newState == HIGH && button[i].buttonState == LOW) {
output(button[i].OutChar,LOW);
}
button[i].buttonState = newState; // update the button state variable
}
}
void output(char OutChar,bool KeyPress){
static int count = 0;
if (KeyPress) {
Serial.print(" Press ");
} else {
Serial.print(" Release ");
}
//Print the selected value to the Serial Port
Serial.println(OutChar);
#ifndef SIMULATE
if (KeyPress) {
Keyboard.press(OutChar); //Send the required character
} else {
Keyboard.release(OutChar);
}
delay(50);
#endif
}