1 #include <avr/interrupt.h>
2 #include <avr/pgmspace.h>
3 #include "usb_keyboard.h"
7 static bool is_sent = false;
9 // which modifier keys are currently pressed
10 // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
11 // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
12 uint8_t keyboard_modifier_keys=0;
14 // which keys are currently pressed, up to 6 keys may be down at once
15 uint8_t keyboard_keys[6]={0,0,0,0,0,0};
17 // protocol setting from the host. We use exactly the same report
18 // either way, so this variable only stores the setting since we
19 // are required to be able to report which setting is in use.
20 uint8_t keyboard_protocol=1;
22 // the idle configuration, how often we send the report to the
23 // host (ms * 4) even when it hasn't changed
24 uint8_t keyboard_idle_config=125;
26 // count until idle timeout
27 uint8_t keyboard_idle_count=0;
29 // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
30 volatile uint8_t keyboard_leds=0;
33 // perform a single keystroke
34 int8_t usb_keyboard_press(uint8_t key, uint8_t modifier)
38 keyboard_modifier_keys = modifier;
39 keyboard_keys[0] = key;
40 r = usb_keyboard_send();
42 keyboard_modifier_keys = 0;
44 return usb_keyboard_send();
47 // send the contents of keyboard_keys and keyboard_modifier_keys
48 int8_t usb_keyboard_send(void)
50 uint8_t i, intr_state, timeout;
52 if (!usb_configured()) return -1;
55 UENUM = KEYBOARD_ENDPOINT;
56 timeout = UDFNUML + 50;
58 // are we ready to transmit?
59 if (UEINTX & (1<<RWAL)) break;
61 // has the USB gone offline?
62 if (!usb_configured()) return -1;
63 // have we waited too long?
64 if (UDFNUML == timeout) return -1;
65 // get ready to try checking again
68 UENUM = KEYBOARD_ENDPOINT;
70 UEDATX = keyboard_modifier_keys;
73 UEDATX = keyboard_keys[i];
76 keyboard_idle_count = 0;
82 void usb_keyboard_init(void) {
87 void usb_keyboard_clear(void) {
88 usb_keyboard_clear_key();
89 usb_keyboard_clear_mod();
92 void usb_keyboard_clear_key(void) {
93 for (int i = 0; i < 6; i++) keyboard_keys[i] = 0;
96 void usb_keyboard_clear_mod(void) {
97 keyboard_modifier_keys = 0;
100 bool usb_keyboard_is_sent(void) {
104 bool usb_keyboard_has_key(void) {
106 for (int i = 0; i < 6; i++) keys |= keyboard_keys[i];
107 return keys ? true : false;
110 bool usb_keyboard_has_mod(void) {
111 return keyboard_modifier_keys ? true : false;
114 void usb_keyboard_print(void) {
116 for (int i = 0; i < 6; i++) { phex(keyboard_keys[i]); print(" "); }
118 print("mods: "); phex(keyboard_modifier_keys); print("\n");