-
Notifications
You must be signed in to change notification settings - Fork 59
/
usb_keyboard_typer.c
113 lines (100 loc) · 2.73 KB
/
usb_keyboard_typer.c
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
#include <wixel.h>
#include <usb.h>
#include <usb_hid.h>
#include "data.h"
uint8 lastKeyCodeSent = 0;
BIT sending = 0;
char XDATA * nextCharToSend;
BIT started = 0;
void updateLeds()
{
usbShowStatusWithGreenLed();
LED_YELLOW(!sending);
LED_RED(sending);
}
uint8 usbHidModifiersFromAsciiChar(char c)
{
if ( (c >= 0x21 && c <= 0x26) ||
(c >= 0x28 && c <= 0x2B) ||
(c == ':') ||
(c == '<') ||
(c >= 0x3E && c <= 0x5A) ||
(c >= 0x5E && c <= 0x5F) ||
(c == '|') ||
(c == '~')
)
{
return (1<<MODIFIER_SHIFT_LEFT);
}
else
{
return 0;
}
}
// See keyboardService for an example of how to use this function correctly.
// Assumption: usbHidKeyboardInputUpdated == 0. Otherwise, this function
// could clobber a keycode sitting in the buffer that has not been sent to
// the computer yet.
// Assumption: usbHidKeyBoardInput[1 through 5] are all zero.
// Assumption: usbHidKeyboardInput.modifiers is 0.
// NOTE: To send two identical characters, you must send a 0 in between.
void sendKeyCode(uint8 keyCode, uint8 modifiers)
{
lastKeyCodeSent = keyCode;
usbHidKeyboardInput.keyCodes[0] = keyCode;
usbHidKeyboardInput.modifiers = modifiers;
// Tell the HID library to send the new keyboard state to the computer.
usbHidKeyboardInputUpdated = 1;
}
void keyboardService()
{
if (getMs() >= 5000 && !started && !sending)
{
started = 1;
sending = 1;
nextCharToSend = (char XDATA *)payload_data;
}
// Feed data to the HID library, one character at a time.
if (sending && !usbHidKeyboardInputUpdated)
{
uint8 nextChar = *nextCharToSend;
if (nextChar == 0)
{
sending = 0;
}
else
{
uint8 keyCode = usbHidKeyCodeFromAsciiChar(*nextCharToSend);
uint8 nextChar = *nextCharToSend;
if (keyCode != 0 && keyCode == lastKeyCodeSent)
{
// If we need to send the same character twice in a row,
// send a 0 between them so the computer registers it as
// two different separate key strokes.
keyCode = 0;
}
else
{
nextCharToSend++;
}
sendKeyCode(keyCode, usbHidModifiersFromAsciiChar(nextChar));
}
}
// Send a 0 to signal the release of the last key.
if (!sending && lastKeyCodeSent != 0 && !usbHidKeyboardInputUpdated)
{
sendKeyCode(0, 0);
}
}
void main()
{
systemInit();
usbInit();
while(1)
{
updateLeds();
boardService();
usbHidService();
keyboardService();
}
}