summaryrefslogtreecommitdiff
path: root/12key-arduino/ModeKeyboard.h
blob: b17f3f5015c707244f135b92f5818d7e201e23fb (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#pragma once

#include <Arduino.h>
#include <Keyboard.h>
#include "Mode.h"

class ModeKeyboard : public Mode {
	protected:
	byte code;
	bool stroke2;
	bool special;

	bool control_hold;
	bool super_hold;
	bool alt_hold;
	bool shift_hold;

	bool nextReset;

	public:
	ModeKeyboard() {
		reset();
	}

	void reset() {
		stroke2 = false;
		special = false;
		nextReset = false;
		digitalWrite(LED, 1);
	}

	Mode * update(unsigned int keys) {
		digitalWrite(LED, 1);
		if (keys & KEY_STAR) return Mode::modes[0];

		if (keys & KEY_HASH) {
			if (nextReset) {
				/* hash was pressed twice, reset */
				reset();
				return NULL;
			}
			nextReset = true;
			if (!special) {
				special = true;
			}
			return NULL;
		}
		nextReset = false;

		if (special) {
			stroke2 = false;
			special = false;
			handleSpecial(keys);
			return NULL;
		}

		if (!stroke2) {
			digitalWrite(LED, 0);
			code = 10 * keyToNumber(keys);
			stroke2 = true;
		}
		else {
			stroke2 = false;
			code += keyToNumber(keys);
			transmitCode(code);
			if (control_hold) {
				Keyboard.release(KEY_LEFT_CTRL);
				control_hold = false;
			}
			if (alt_hold) {
				Keyboard.release(KEY_LEFT_ALT);
				alt_hold = false;
			}
			if (super_hold) {
				Keyboard.release(KEY_LEFT_GUI);
				super_hold = false;
			}
			if (shift_hold) {
				Keyboard.release(KEY_LEFT_SHIFT);
				shift_hold = false;
			}
		}

		return NULL;
	}


	byte keyToNumber(unsigned int keys) {
		if (keys & KEY_0) return 0;
		if (keys & KEY_1) return 1;
		if (keys & KEY_2) return 2;
		if (keys & KEY_3) return 3;
		if (keys & KEY_4) return 4;
		if (keys & KEY_5) return 5;
		if (keys & KEY_6) return 6;
		if (keys & KEY_7) return 7;
		if (keys & KEY_8) return 8;
		if (keys & KEY_9) return 9;
		return 0;
	}


	void transmitCode(byte code) {
		if      (code == 99) Keyboard.write(KEY_BACKSPACE);
		else if (code == 98) Keyboard.write(KEY_TAB);
		else if (code == 97) Keyboard.write(KEY_ESC);
		else if (code == 96) Keyboard.write(KEY_RETURN);
		else if (code == 95) Keyboard.write(KEY_TAB);
		else Keyboard.write(code + 32);
	}


	void handleSpecial(unsigned int keys) {
		if (keys & KEY_4) {
			Keyboard.press(KEY_LEFT_SHIFT);
			shift_hold = true;
		}
		if (keys & KEY_7) {
			Keyboard.press(KEY_LEFT_CTRL);
			control_hold = true;
		}
		if (keys & KEY_8) {
			Keyboard.press(KEY_LEFT_GUI);
			super_hold = true;
		}
		if (keys & KEY_9) {
			Keyboard.press(KEY_LEFT_ALT);
			alt_hold = true;
		}
	}
};