summaryrefslogtreecommitdiff
path: root/vim-clutch.ino
blob: 8c23b8393be832852b80ecf7b3d6ae7b607c39ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <Keyboard.h>

#define KEYCODE_PRESS KEY_F11
#define KEYCODE_RELEASE KEY_F12
#define LED_PIN 17
#define SWITCH_PIN 2
#define DEBOUNCE_MS 25
#define POLL_MS 5
#define COUNTER_RESET (DEBOUNCE_MS / POLL_MS)

#define DEBUG_MARK_BEGIN   (digitalWrite(LED_PIN, LOW))
#define DEBUG_MARK_END     (digitalWrite(LED_PIN, HIGH))

void setup() {
  pinMode(SWITCH_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  static long last_poll = millis();
  static bool debounced = LOW;
  static bool raw = LOW;
  static int counter = COUNTER_RESET;

  if (millis() >= last_poll + POLL_MS) {
    last_poll = millis();
    DEBUG_MARK_BEGIN;
    raw = digitalRead(SWITCH_PIN);
    if (raw == debounced) {
      counter = COUNTER_RESET;
    } else {
      if (--counter == 0) {
        debounced = raw;
        if (debounced) {
          // Key was just released
          Keyboard.press(KEYCODE_RELEASE);
          Keyboard.release(KEYCODE_RELEASE);
        } else {
          // Key was just pressed
          Keyboard.press(KEYCODE_PRESS);
          Keyboard.release(KEYCODE_PRESS);
        }
        counter = COUNTER_RESET;
      }
    }
    DEBUG_MARK_END;
  }
}