split_util.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <avr/io.h>
  2. #include <avr/wdt.h>
  3. #include <avr/power.h>
  4. #include <avr/interrupt.h>
  5. #include <util/delay.h>
  6. #include <avr/eeprom.h>
  7. #include "split_util.h"
  8. #include "matrix.h"
  9. #include "keyboard.h"
  10. #include "wait.h"
  11. #ifdef USE_MATRIX_I2C
  12. # include "i2c.h"
  13. #else
  14. # include "split_scomm.h"
  15. #endif
  16. #ifndef SPLIT_USB_TIMEOUT
  17. # define SPLIT_USB_TIMEOUT 2500
  18. #endif
  19. volatile bool isLeftHand = true;
  20. bool waitForUsb(void) {
  21. for (uint8_t i = 0; i < (SPLIT_USB_TIMEOUT / 100); i++) {
  22. // This will return true of a USB connection has been established
  23. if (UDADDR & _BV(ADDEN)) {
  24. return true;
  25. }
  26. wait_ms(100);
  27. }
  28. // Avoid NO_USB_STARTUP_CHECK - Disable USB as the previous checks seem to enable it somehow
  29. (USBCON &= ~(_BV(USBE) | _BV(OTGPADE)));
  30. return false;
  31. }
  32. __attribute__((weak)) bool is_keyboard_left(void) {
  33. #if defined(SPLIT_HAND_PIN)
  34. // Test pin SPLIT_HAND_PIN for High/Low, if low it's right hand
  35. setPinInput(SPLIT_HAND_PIN);
  36. return readPin(SPLIT_HAND_PIN);
  37. #elif defined(EE_HANDS)
  38. return eeconfig_read_handedness();
  39. #elif defined(MASTER_RIGHT)
  40. return !has_usb();
  41. #endif
  42. return has_usb();
  43. }
  44. __attribute__((weak)) bool has_usb(void) {
  45. static enum { UNKNOWN, MASTER, SLAVE } usbstate = UNKNOWN;
  46. // only check once, as this is called often
  47. if (usbstate == UNKNOWN) {
  48. #if defined(SPLIT_USB_DETECT)
  49. usbstate = waitForUsb() ? MASTER : SLAVE;
  50. #elif defined(__AVR__)
  51. USBCON |= (1 << OTGPADE); // enables VBUS pad
  52. wait_us(5);
  53. usbstate = (USBSTA & (1 << VBUS)) ? MASTER : SLAVE; // checks state of VBUS
  54. #else
  55. usbstate = MASTER;
  56. #endif
  57. }
  58. return (usbstate == MASTER);
  59. }
  60. static void keyboard_master_setup(void) {
  61. #ifdef USE_MATRIX_I2C
  62. i2c_master_init();
  63. #else
  64. serial_master_init();
  65. #endif
  66. }
  67. static void keyboard_slave_setup(void) {
  68. #ifdef USE_MATRIX_I2C
  69. i2c_slave_init(SLAVE_I2C_ADDRESS);
  70. #else
  71. serial_slave_init();
  72. #endif
  73. }
  74. void split_keyboard_setup(void) {
  75. isLeftHand = is_keyboard_left();
  76. if (has_usb()) {
  77. keyboard_master_setup();
  78. } else {
  79. keyboard_slave_setup();
  80. }
  81. sei();
  82. }