preonic.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include "preonic.h"
  2. __attribute__ ((weak))
  3. void matrix_init_user(void) {
  4. };
  5. __attribute__ ((weak))
  6. void matrix_scan_user(void) {
  7. };
  8. __attribute__ ((weak))
  9. void process_action_user(keyrecord_t *record) {
  10. };
  11. void matrix_init_kb(void) {
  12. #ifdef BACKLIGHT_ENABLE
  13. backlight_init_ports();
  14. #endif
  15. #ifdef RGBLIGHT_ENABLE
  16. rgblight_init();
  17. #endif
  18. // Turn status LED on
  19. DDRE |= (1<<6);
  20. PORTE |= (1<<6);
  21. matrix_init_user();
  22. };
  23. void matrix_scan_kb(void) {
  24. matrix_scan_user();
  25. };
  26. void process_action_kb(keyrecord_t *record) {
  27. process_action_user(record);
  28. }
  29. #ifdef BACKLIGHT_ENABLE
  30. #define CHANNEL OCR1C
  31. void backlight_init_ports()
  32. {
  33. // Setup PB7 as output and output low.
  34. DDRB |= (1<<7);
  35. PORTB &= ~(1<<7);
  36. // Use full 16-bit resolution.
  37. ICR1 = 0xFFFF;
  38. // I could write a wall of text here to explain... but TL;DW
  39. // Go read the ATmega32u4 datasheet.
  40. // And this: http://blog.saikoled.com/post/43165849837/secret-konami-cheat-code-to-high-resolution-pwm-on
  41. // Pin PB7 = OCR1C (Timer 1, Channel C)
  42. // Compare Output Mode = Clear on compare match, Channel C = COM1C1=1 COM1C0=0
  43. // (i.e. start high, go low when counter matches.)
  44. // WGM Mode 14 (Fast PWM) = WGM13=1 WGM12=1 WGM11=1 WGM10=0
  45. // Clock Select = clk/1 (no prescaling) = CS12=0 CS11=0 CS10=1
  46. TCCR1A = _BV(COM1C1) | _BV(WGM11); // = 0b00001010;
  47. TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // = 0b00011001;
  48. backlight_init();
  49. }
  50. void backlight_set(uint8_t level)
  51. {
  52. if ( level == 0 )
  53. {
  54. // Turn off PWM control on PB7, revert to output low.
  55. TCCR1A &= ~(_BV(COM1C1));
  56. CHANNEL = 0x0;
  57. // Prevent backlight blink on lowest level
  58. PORTB &= ~(_BV(PORTB7));
  59. }
  60. else if ( level == BACKLIGHT_LEVELS )
  61. {
  62. // Prevent backlight blink on lowest level
  63. PORTB &= ~(_BV(PORTB7));
  64. // Turn on PWM control of PB7
  65. TCCR1A |= _BV(COM1C1);
  66. // Set the brightness
  67. CHANNEL = 0xFFFF;
  68. }
  69. else
  70. {
  71. // Prevent backlight blink on lowest level
  72. PORTB &= ~(_BV(PORTB7));
  73. // Turn on PWM control of PB7
  74. TCCR1A |= _BV(COM1C1);
  75. // Set the brightness
  76. CHANNEL = 0xFFFF >> ((BACKLIGHT_LEVELS - level) * ((BACKLIGHT_LEVELS + 1) / 2));
  77. }
  78. }
  79. #endif