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