Keyboard firmwares for Atmel AVR and Cortex-M
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

usb_keyboard.c 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <avr/interrupt.h>
  2. #include <avr/pgmspace.h>
  3. #include "usb_keyboard.h"
  4. // which modifier keys are currently pressed
  5. // 1=left ctrl, 2=left shift, 4=left alt, 8=left gui
  6. // 16=right ctrl, 32=right shift, 64=right alt, 128=right gui
  7. uint8_t keyboard_modifier_keys=0;
  8. // which keys are currently pressed, up to 6 keys may be down at once
  9. uint8_t keyboard_keys[6]={0,0,0,0,0,0};
  10. // protocol setting from the host. We use exactly the same report
  11. // either way, so this variable only stores the setting since we
  12. // are required to be able to report which setting is in use.
  13. uint8_t keyboard_protocol=1;
  14. // the idle configuration, how often we send the report to the
  15. // host (ms * 4) even when it hasn't changed
  16. uint8_t keyboard_idle_config=125;
  17. // count until idle timeout
  18. uint8_t keyboard_idle_count=0;
  19. // 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
  20. volatile uint8_t keyboard_leds=0;
  21. // perform a single keystroke
  22. int8_t usb_keyboard_press(uint8_t key, uint8_t modifier)
  23. {
  24. int8_t r;
  25. keyboard_modifier_keys = modifier;
  26. keyboard_keys[0] = key;
  27. r = usb_keyboard_send();
  28. if (r) return r;
  29. keyboard_modifier_keys = 0;
  30. keyboard_keys[0] = 0;
  31. return usb_keyboard_send();
  32. }
  33. // send the contents of keyboard_keys and keyboard_modifier_keys
  34. int8_t usb_keyboard_send(void)
  35. {
  36. uint8_t i, intr_state, timeout;
  37. if (!usb_configured()) return -1;
  38. intr_state = SREG;
  39. cli();
  40. UENUM = KEYBOARD_ENDPOINT;
  41. timeout = UDFNUML + 50;
  42. while (1) {
  43. // are we ready to transmit?
  44. if (UEINTX & (1<<RWAL)) break;
  45. SREG = intr_state;
  46. // has the USB gone offline?
  47. if (!usb_configured()) return -1;
  48. // have we waited too long?
  49. if (UDFNUML == timeout) return -1;
  50. // get ready to try checking again
  51. intr_state = SREG;
  52. cli();
  53. UENUM = KEYBOARD_ENDPOINT;
  54. }
  55. UEDATX = keyboard_modifier_keys;
  56. UEDATX = 0;
  57. for (i=0; i<6; i++) {
  58. UEDATX = keyboard_keys[i];
  59. }
  60. UEINTX = 0x3A;
  61. keyboard_idle_count = 0;
  62. SREG = intr_state;
  63. return 0;
  64. }