Example_1_Button_Keyboard.ino
1 // SPDX-FileCopyrightText: 2019 Tony DiCola for Adafruit Industries 2 // 3 // SPDX-License-Identifier: MIT 4 5 // Example of buttons generating keyboard presses 6 // Author: Tony DiCola 7 // License: MIT 8 #include <Keyboard.h> 9 10 11 #define BUTTON1_PIN 10 // Pin connected to button 1. 12 13 #define BUTTON2_PIN 12 // Pin connected to button 2. 14 15 #define BUTTON1_KEY KEY_UP_ARROW // Keyboard key generated by button 1 press. 16 // See all the key values here: 17 // https://www.arduino.cc/en/Reference/KeyboardModifiers 18 19 #define BUTTON2_KEY KEY_DOWN_ARROW // Keyboard key generated by button 2 press. 20 21 22 void setup() { 23 // Configure button inputs with a pullup resistor so they 24 // default to a high level and are pulled down to ground 25 // when pressed. 26 pinMode(BUTTON1_PIN, INPUT_PULLUP); 27 pinMode(BUTTON2_PIN, INPUT_PULLUP); 28 // Initialize keyboard library. 29 Keyboard.begin(); 30 } 31 32 void loop() { 33 // Look for the transition from high to low (button pressed) 34 // or low to high (button released) to press and release keys. 35 // Do this by taking an initial reading, waiting a tiny bit 36 // and then taking another reading. If there's a transition 37 // we can detect the change between readings. This also acts 38 // to 'debouce' and prevent multiple transitions. 39 int button1_first = digitalRead(BUTTON1_PIN); 40 int button2_first = digitalRead(BUTTON2_PIN); 41 delay(10); 42 int button1_second = digitalRead(BUTTON1_PIN); 43 int button2_second = digitalRead(BUTTON2_PIN); 44 // Check for button transitions. 45 if (button1_first == HIGH && button1_second == LOW) { 46 // Button 1 was pressed. 47 Keyboard.press(BUTTON1_KEY); 48 } 49 else if (button1_first == LOW && button1_second == HIGH) { 50 // Button 1 was released. 51 Keyboard.release(BUTTON1_KEY); 52 } 53 if (button2_first == HIGH && button2_second == LOW) { 54 // Button 2 was pressed. 55 Keyboard.press(BUTTON2_KEY); 56 } 57 else if (button2_first == LOW && button2_second == HIGH) { 58 // Button 1 was released. 59 Keyboard.release(BUTTON2_KEY); 60 } 61 } 62