preonic.c 2.2 KB

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