4 Copyright (c) 2016 Fred Sundvik
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25 #include "lcd_backlight.h"
31 #define CHANNEL_RED FTM0->CHANNEL[0]
32 #define CHANNEL_GREEN FTM0->CHANNEL[1]
33 #define CHANNEL_BLUE FTM0->CHANNEL[2]
35 #define RGB_PORT PORTC
36 #define RGB_PORT_GPIO GPIOC
38 // Base FTM clock selection (72 MHz system clock)
39 // @ 0xFFFF period, 72 MHz / (0xFFFF * 2) = Actual period
40 // Higher pre-scalar will use the most power (also look the best)
41 // Pre-scalar calculations
42 // 0 - 72 MHz -> 549 Hz
43 // 1 - 36 MHz -> 275 Hz
44 // 2 - 18 MHz -> 137 Hz
45 // 3 - 9 MHz -> 69 Hz (Slightly visible flicker)
46 // 4 - 4 500 kHz -> 34 Hz (Visible flickering)
47 // 5 - 2 250 kHz -> 17 Hz
48 // 6 - 1 125 kHz -> 9 Hz
49 // 7 - 562 500 Hz -> 4 Hz
50 // Using a higher pre-scalar without flicker is possible but FTM0_MOD will need to be reduced
51 // Which will reduce the brightness range
52 #define PRESCALAR_DEFINE 0
54 void lcd_backlight_hal_init(void) {
56 SIM->SCGC6 |= SIM_SCGC6_FTM0;
57 FTM0->CNT = 0; // Reset counter
63 // Set FTM to PWM output - Edge Aligned, Low-true pulses
64 #define CNSC_MODE FTM_SC_CPWMS | FTM_SC_PS(4) | FTM_SC_CLKS(0)
65 CHANNEL_RED.CnSC = CNSC_MODE;
66 CHANNEL_GREEN.CnSC = CNSC_MODE;
67 CHANNEL_BLUE.CnSC = CNSC_MODE;
69 // System clock, /w prescalar setting
70 FTM0->SC = FTM_SC_CLKS(1) | FTM_SC_PS(PRESCALAR_DEFINE);
73 CHANNEL_GREEN.CnV = 0;
76 RGB_PORT_GPIO->PDDR |= (1 << RED_PIN);
77 RGB_PORT_GPIO->PDDR |= (1 << GREEN_PIN);
78 RGB_PORT_GPIO->PDDR |= (1 << BLUE_PIN);
80 #define RGB_MODE PORTx_PCRn_SRE | PORTx_PCRn_DSE | PORTx_PCRn_MUX(4)
81 RGB_PORT->PCR[RED_PIN] = RGB_MODE;
82 RGB_PORT->PCR[GREEN_PIN] = RGB_MODE;
83 RGB_PORT->PCR[BLUE_PIN] = RGB_MODE;
86 void lcd_backlight_hal_color(uint16_t r, uint16_t g, uint16_t b) {
88 CHANNEL_GREEN.CnV = g;