Advertisement
18107

arduino leonardo - one button keyboard

Jul 15th, 2018
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 KB | None | 0 0
  1. //arduino leonardo - one button keyboard
  2. #include "Keyboard.h"
  3. const int button = 4;
  4. const int led = 13;
  5.  
  6. const int debounce = 18;
  7. const long interval = 200;
  8. const long timeout = 5000;
  9.  
  10. bool lastState = HIGH;
  11.  
  12. unsigned long startTime = 0;
  13.  
  14. int currentBit = 7;
  15. int character = 0;
  16. int lastCharacter = 0;
  17. bool repeat = false;
  18.  
  19. void setup() {
  20.   pinMode(button, INPUT_PULLUP);
  21.   pinMode(led, OUTPUT);
  22.   Keyboard.begin();
  23. }
  24.  
  25. void loop() {
  26.   bool state = digitalRead(button);
  27.   if (state != lastState) {
  28.     if (repeat) {
  29.       Keyboard.releaseAll();
  30.       repeat = false;
  31.     }
  32.     delay(debounce);
  33.     lastState = state;
  34.     if (state == LOW) {
  35.       startTime = millis();
  36.       digitalWrite(led, HIGH);
  37.     }
  38.     if (state == HIGH) { //button released
  39.       if (millis() - startTime < interval) { //1
  40.         digitalWrite(led, LOW);
  41.         character |= 1<<currentBit;
  42.         if (character == 255) { //repeat
  43.           currentBit = 8;
  44.           character = 0;
  45.           repeat = true;
  46.           Keyboard.press(lastCharacter);
  47.         }
  48.       }
  49.       currentBit--;
  50.       if (currentBit < 0) { //finished character
  51.         Keyboard.write(character);
  52.         lastCharacter = character;
  53.         currentBit = 7;
  54.         character = 0;
  55.       }
  56.     }
  57.   }
  58.   if (millis() - startTime > interval) {
  59.     digitalWrite(led, LOW);
  60.   }
  61.   if (millis() - startTime > timeout && currentBit != 7) {
  62.     startTime = millis();
  63.     digitalWrite(led, HIGH);
  64.     currentBit = 7;
  65.     character = 0;
  66.   }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement