Keyboards-MultipleButtons
Jump to navigation
Jump to search
KEYBOARDS and MULTIPLE BUTTONS
5-Button Keyboard: Uses series resistors and switches to decide a variety of voltages to send to an Arduino Analog Input.
You can use this same technique for multiple buttons you mount in other ways or orientations.
Below: (UPDATED 1/17) Example code of a 5-button keyboard that uses resistors to connect to a single Analog Input Pin:
/* YourDuinoStarter Example: Analog buttons - WHAT IT DOES: Reads Analog Input 0 and decodes which button was pressed - SEE the comments after "//" on each line below - V2.0 01-06-2017 Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ //None /*-----( Declare Constants and Pin Numbers )-----*/ #define LEDPIN 13 #define keyboard_AnalogInput 0 // Analog input 0 used for Keyboard #define btnRIGHT 4 #define btnUP 2 #define btnDOWN 3 #define btnLEFT 1 #define btnENTER 5 #define btnNONE -1 /*---( declare Variables )----*/ int buttonpressed; void setup() /****** SETUP: RUNS ONCE ******/ { pinMode(LEDPIN, OUTPUT); Serial.begin(115200); // Set Serial Monitor lower right to 115200 Serial.println("Testing Analog Buttons "); }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { buttonpressed = read_keyboard(); if (buttonpressed != btnNONE) { Serial.print(" Button Pressed = "); Serial.println(buttonpressed); } }//--(end main loop )--- /*---( User Written Functions )------*/ /*-----------( Read analog values from 4-button keyboard, decode voltages to Buttons )---------------*/ int getButton() { int i, v, button; int sum = 0; for (i = 0; i < 4; i++) { sum += analogRead(keyboard_AnalogInput); } v = sum / 4; if (v > 1000) button = 0; else if (v >= 0 && v < 20) button = 1; //LEFT else if (v > 135 && v < 155) button = 2; //UP else if (v > 315 && v < 335) button = 3; //DOWN else if (v > 495 && v < 515) button = 4; //RIGHT else if (v > 725 && v < 745) button = 5; //ENTER else button = 0; return button; }// END getButton /*-------------------( Debounce keystrokes, translate to buttons )-------------------*/ int old_button = 0; int read_keyboard() { int button, button2, pressed_button; button = getButton(); // Above if (button != old_button) // A new button pressed { delay(50); // debounce button2 = getButton(); if (button == button2) { old_button = button; pressed_button = button; if (button != 0) { //Serial.println(button); if (button == 1) return btnLEFT; if (button == 2) return btnUP; if (button == 3) return btnDOWN; if (button == 4) return btnRIGHT; if (button == 5) return btnENTER; } } } else { return btnNONE; } }// End read_keyboard //*********( THE END )**********