main.c 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /* Name: main.c
  2. * Project: hid-mouse, a very simple HID example
  3. * Author: Christian Starkjohann
  4. * Creation Date: 2008-04-07
  5. * Tabsize: 4
  6. * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
  7. * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
  8. * This Revision: $Id: main.c 790 2010-05-30 21:00:26Z cs $
  9. */
  10. #include <stdint.h>
  11. #include <avr/interrupt.h>
  12. #include <avr/wdt.h>
  13. #include <avr/sleep.h>
  14. #include <util/delay.h>
  15. #include "usbdrv.h"
  16. #include "oddebug.h"
  17. #include "vusb.h"
  18. #include "keyboard.h"
  19. #include "host.h"
  20. #include "timer.h"
  21. #include "uart.h"
  22. #include "debug.h"
  23. #if defined(RGBLIGHT_ENABLE)
  24. # include "rgblight.h"
  25. #endif
  26. #define UART_BAUD_RATE 115200
  27. /* This is from main.c of USBaspLoader */
  28. static void initForUsbConnectivity(void) {
  29. uint8_t i = 0;
  30. usbInit();
  31. /* enforce USB re-enumerate: */
  32. usbDeviceDisconnect(); /* do this while interrupts are disabled */
  33. while (--i) { /* fake USB disconnect for > 250 ms */
  34. wdt_reset();
  35. _delay_ms(1);
  36. }
  37. usbDeviceConnect();
  38. sei();
  39. }
  40. int main(void) {
  41. bool suspended = false;
  42. #if USB_COUNT_SOF
  43. uint16_t last_timer = timer_read();
  44. #endif
  45. #ifdef CLKPR
  46. // avoid unintentional changes of clock frequency in devices that have a
  47. // clock prescaler
  48. CLKPR = 0x80, CLKPR = 0;
  49. #endif
  50. #ifndef NO_UART
  51. uart_init(UART_BAUD_RATE);
  52. #endif
  53. keyboard_setup();
  54. host_set_driver(vusb_driver());
  55. debug("initForUsbConnectivity()\n");
  56. initForUsbConnectivity();
  57. keyboard_init();
  58. debug("main loop\n");
  59. while (1) {
  60. #if USB_COUNT_SOF
  61. if (usbSofCount != 0) {
  62. suspended = false;
  63. usbSofCount = 0;
  64. last_timer = timer_read();
  65. } else {
  66. // Suspend when no SOF in 3ms-10ms(7.1.7.4 Suspending of USB1.1)
  67. if (timer_elapsed(last_timer) > 5) {
  68. suspended = true;
  69. /*
  70. uart_putchar('S');
  71. _delay_ms(1);
  72. cli();
  73. set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  74. sleep_enable();
  75. sleep_bod_disable();
  76. sei();
  77. sleep_cpu();
  78. sleep_disable();
  79. _delay_ms(10);
  80. uart_putchar('W');
  81. */
  82. }
  83. }
  84. #endif
  85. if (!suspended) {
  86. usbPoll();
  87. // TODO: configuration process is incosistent. it sometime fails.
  88. // To prevent failing to configure NOT scan keyboard during configuration
  89. if (usbConfiguration && usbInterruptIsReady()) {
  90. keyboard_task();
  91. }
  92. vusb_transfer_keyboard();
  93. }
  94. }
  95. }