]> git.donarmstrong.com Git - qmk_firmware.git/blob - keyboards/infinity_ergodox/infinity_ergodox.c
87ed40fabf20e321718416097608d99720b033a6
[qmk_firmware.git] / keyboards / infinity_ergodox / infinity_ergodox.c
1 #include "infinity_ergodox.h"
2 #include "ch.h"
3 #include "hal.h"
4 #include "serial_link/system/serial_link.h"
5 #include "lcd_backlight.h"
6
7 void init_serial_link_hal(void) {
8     PORTA->PCR[1] = PORTx_PCRn_PE | PORTx_PCRn_PS | PORTx_PCRn_PFE | PORTx_PCRn_MUX(2);
9     PORTA->PCR[2] = PORTx_PCRn_DSE | PORTx_PCRn_SRE | PORTx_PCRn_MUX(2);
10     PORTE->PCR[0] = PORTx_PCRn_PE | PORTx_PCRn_PS | PORTx_PCRn_PFE | PORTx_PCRn_MUX(3);
11     PORTE->PCR[1] = PORTx_PCRn_DSE | PORTx_PCRn_SRE | PORTx_PCRn_MUX(3);
12 }
13
14 #define RED_PIN 1
15 #define GREEN_PIN 2
16 #define BLUE_PIN 3
17 #define CHANNEL_RED FTM0->CHANNEL[0]
18 #define CHANNEL_GREEN FTM0->CHANNEL[1]
19 #define CHANNEL_BLUE FTM0->CHANNEL[2]
20
21 #define RGB_PORT PORTC
22 #define RGB_PORT_GPIO GPIOC
23
24 // Base FTM clock selection (72 MHz system clock)
25 // @ 0xFFFF period, 72 MHz / (0xFFFF * 2) = Actual period
26 // Higher pre-scalar will use the most power (also look the best)
27 // Pre-scalar calculations
28 // 0 -      72 MHz -> 549 Hz
29 // 1 -      36 MHz -> 275 Hz
30 // 2 -      18 MHz -> 137 Hz
31 // 3 -       9 MHz ->  69 Hz (Slightly visible flicker)
32 // 4 -   4 500 kHz ->  34 Hz (Visible flickering)
33 // 5 -   2 250 kHz ->  17 Hz
34 // 6 -   1 125 kHz ->   9 Hz
35 // 7 - 562 500  Hz ->   4 Hz
36 // Using a higher pre-scalar without flicker is possible but FTM0_MOD will need to be reduced
37 // Which will reduce the brightness range
38 #define PRESCALAR_DEFINE 0
39
40 void lcd_backlight_hal_init(void) {
41         // Setup Backlight
42     SIM->SCGC6 |= SIM_SCGC6_FTM0;
43     FTM0->CNT = 0; // Reset counter
44
45         // PWM Period
46         // 16-bit maximum
47         FTM0->MOD = 0xFFFF;
48
49         // Set FTM to PWM output - Edge Aligned, Low-true pulses
50 #define CNSC_MODE FTM_SC_CPWMS | FTM_SC_PS(4) | FTM_SC_CLKS(0)
51         CHANNEL_RED.CnSC = CNSC_MODE;
52         CHANNEL_GREEN.CnSC = CNSC_MODE;
53         CHANNEL_BLUE.CnSC = CNSC_MODE;
54
55         // System clock, /w prescalar setting
56         FTM0->SC = FTM_SC_CLKS(1) | FTM_SC_PS(PRESCALAR_DEFINE);
57
58         CHANNEL_RED.CnV = 0;
59         CHANNEL_GREEN.CnV = 0;
60         CHANNEL_BLUE.CnV = 0;
61
62         RGB_PORT_GPIO->PDDR |= (1 << RED_PIN);
63         RGB_PORT_GPIO->PDDR |= (1 << GREEN_PIN);
64         RGB_PORT_GPIO->PDDR |= (1 << BLUE_PIN);
65
66 #define RGB_MODE PORTx_PCRn_SRE | PORTx_PCRn_DSE | PORTx_PCRn_MUX(4)
67     RGB_PORT->PCR[RED_PIN] = RGB_MODE;
68     RGB_PORT->PCR[GREEN_PIN] = RGB_MODE;
69     RGB_PORT->PCR[BLUE_PIN] = RGB_MODE;
70 }
71
72 void lcd_backlight_hal_color(uint16_t r, uint16_t g, uint16_t b) {
73         CHANNEL_RED.CnV = r;
74         CHANNEL_GREEN.CnV = g;
75         CHANNEL_BLUE.CnV = b;
76 }