]> git.donarmstrong.com Git - qmk_firmware.git/blob - quantum/backlight/backlight_avr.c
ARM - Initial backlight support (#6487)
[qmk_firmware.git] / quantum / backlight / backlight_avr.c
1 #include "quantum.h"
2 #include "backlight.h"
3 #include "debug.h"
4
5 #if defined(BACKLIGHT_ENABLE) && (defined(BACKLIGHT_PIN) || defined(BACKLIGHT_PINS))
6
7 // This logic is a bit complex, we support 3 setups:
8 //
9 //   1. Hardware PWM when backlight is wired to a PWM pin.
10 //      Depending on this pin, we use a different output compare unit.
11 //   2. Software PWM with hardware timers, but the used timer
12 //      depends on the Audio setup (Audio wins over Backlight).
13 //   3. Full software PWM, driven by the matrix scan, if both timers are used by Audio.
14
15 #    if (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__) || defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__) || defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)) && (BACKLIGHT_PIN == B5 || BACKLIGHT_PIN == B6 || BACKLIGHT_PIN == B7)
16 #        define HARDWARE_PWM
17 #        define ICRx ICR1
18 #        define TCCRxA TCCR1A
19 #        define TCCRxB TCCR1B
20 #        define TIMERx_OVF_vect TIMER1_OVF_vect
21 #        define TIMSKx TIMSK1
22 #        define TOIEx TOIE1
23
24 #        if BACKLIGHT_PIN == B5
25 #            define COMxx1 COM1A1
26 #            define OCRxx OCR1A
27 #        elif BACKLIGHT_PIN == B6
28 #            define COMxx1 COM1B1
29 #            define OCRxx OCR1B
30 #        elif BACKLIGHT_PIN == B7
31 #            define COMxx1 COM1C1
32 #            define OCRxx OCR1C
33 #        endif
34 #    elif (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB647__) || defined(__AVR_AT90USB1286__) || defined(__AVR_AT90USB1287__) || defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)) && (BACKLIGHT_PIN == C4 || BACKLIGHT_PIN == C5 || BACKLIGHT_PIN == C6)
35 #        define HARDWARE_PWM
36 #        define ICRx ICR3
37 #        define TCCRxA TCCR3A
38 #        define TCCRxB TCCR3B
39 #        define TIMERx_OVF_vect TIMER3_OVF_vect
40 #        define TIMSKx TIMSK3
41 #        define TOIEx TOIE3
42
43 #        if BACKLIGHT_PIN == C4
44 #            if (defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__))
45 #                error This MCU has no C4 pin!
46 #            else
47 #                define COMxx1 COM3C1
48 #                define OCRxx OCR3C
49 #            endif
50 #        elif BACKLIGHT_PIN == C5
51 #            if (defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__))
52 #                error This MCU has no C5 pin!
53 #            else
54 #                define COMxx1 COM3B1
55 #                define OCRxx OCR3B
56 #            endif
57 #        elif BACKLIGHT_PIN == C6
58 #            define COMxx1 COM3A1
59 #            define OCRxx OCR3A
60 #        endif
61 #    elif (defined(__AVR_ATmega16U2__) || defined(__AVR_ATmega32U2__)) && (BACKLIGHT_PIN == B7 || BACKLIGHT_PIN == C5 || BACKLIGHT_PIN == C6)
62 #        define HARDWARE_PWM
63 #        define ICRx ICR1
64 #        define TCCRxA TCCR1A
65 #        define TCCRxB TCCR1B
66 #        define TIMERx_OVF_vect TIMER1_OVF_vect
67 #        define TIMSKx TIMSK1
68 #        define TOIEx TOIE1
69
70 #        if BACKLIGHT_PIN == B7
71 #            define COMxx1 COM1C1
72 #            define OCRxx OCR1C
73 #        elif BACKLIGHT_PIN == C5
74 #            define COMxx1 COM1B1
75 #            define OCRxx OCR1B
76 #        elif BACKLIGHT_PIN == C6
77 #            define COMxx1 COM1A1
78 #            define OCRxx OCR1A
79 #        endif
80 #    elif defined(__AVR_ATmega32A__) && (BACKLIGHT_PIN == D4 || BACKLIGHT_PIN == D5)
81 #        define HARDWARE_PWM
82 #        define ICRx ICR1
83 #        define TCCRxA TCCR1A
84 #        define TCCRxB TCCR1B
85 #        define TIMERx_OVF_vect TIMER1_OVF_vect
86 #        define TIMSKx TIMSK
87 #        define TOIEx TOIE1
88
89 #        if BACKLIGHT_PIN == D4
90 #            define COMxx1 COM1B1
91 #            define OCRxx OCR1B
92 #        elif BACKLIGHT_PIN == D5
93 #            define COMxx1 COM1A1
94 #            define OCRxx OCR1A
95 #        endif
96 #    elif defined(__AVR_ATmega328P__) && (BACKLIGHT_PIN == B1 || BACKLIGHT_PIN == B2)
97 #        define HARDWARE_PWM
98 #        define ICRx ICR1
99 #        define TCCRxA TCCR1A
100 #        define TCCRxB TCCR1B
101 #        define TIMERx_OVF_vect TIMER1_OVF_vect
102 #        define TIMSKx TIMSK1
103 #        define TOIEx TOIE1
104
105 #        if BACKLIGHT_PIN == B1
106 #            define COMxx1 COM1A1
107 #            define OCRxx OCR1A
108 #        elif BACKLIGHT_PIN == B2
109 #            define COMxx1 COM1B1
110 #            define OCRxx OCR1B
111 #        endif
112 #    else
113 #        if !defined(BACKLIGHT_CUSTOM_DRIVER)
114 #            if !defined(B5_AUDIO) && !defined(B6_AUDIO) && !defined(B7_AUDIO)
115 // Timer 1 is not in use by Audio feature, Backlight can use it
116 #                pragma message "Using hardware timer 1 with software PWM"
117 #                define HARDWARE_PWM
118 #                define BACKLIGHT_PWM_TIMER
119 #                define ICRx ICR1
120 #                define TCCRxA TCCR1A
121 #                define TCCRxB TCCR1B
122 #                define TIMERx_COMPA_vect TIMER1_COMPA_vect
123 #                define TIMERx_OVF_vect TIMER1_OVF_vect
124 #                if defined(__AVR_ATmega32A__)  // This MCU has only one TIMSK register
125 #                    define TIMSKx TIMSK
126 #                else
127 #                    define TIMSKx TIMSK1
128 #                endif
129 #                define TOIEx TOIE1
130
131 #                define OCIExA OCIE1A
132 #                define OCRxx OCR1A
133 #            elif !defined(C6_AUDIO) && !defined(C5_AUDIO) && !defined(C4_AUDIO)
134 #                pragma message "Using hardware timer 3 with software PWM"
135 // Timer 3 is not in use by Audio feature, Backlight can use it
136 #                define HARDWARE_PWM
137 #                define BACKLIGHT_PWM_TIMER
138 #                define ICRx ICR1
139 #                define TCCRxA TCCR3A
140 #                define TCCRxB TCCR3B
141 #                define TIMERx_COMPA_vect TIMER3_COMPA_vect
142 #                define TIMERx_OVF_vect TIMER3_OVF_vect
143 #                define TIMSKx TIMSK3
144 #                define TOIEx TOIE3
145
146 #                define OCIExA OCIE3A
147 #                define OCRxx OCR3A
148 #            else
149 #                pragma message "Audio in use - using pure software PWM"
150 #                define NO_HARDWARE_PWM
151 #            endif
152 #        else
153 #            pragma message "Custom driver defined - using pure software PWM"
154 #            define NO_HARDWARE_PWM
155 #        endif
156 #    endif
157
158 #    ifndef BACKLIGHT_ON_STATE
159 #        define BACKLIGHT_ON_STATE 0
160 #    endif
161
162 void backlight_on(uint8_t backlight_pin) {
163 #    if BACKLIGHT_ON_STATE == 0
164     writePinLow(backlight_pin);
165 #    else
166     writePinHigh(backlight_pin);
167 #    endif
168 }
169
170 void backlight_off(uint8_t backlight_pin) {
171 #    if BACKLIGHT_ON_STATE == 0
172     writePinHigh(backlight_pin);
173 #    else
174     writePinLow(backlight_pin);
175 #    endif
176 }
177
178 #    if defined(NO_HARDWARE_PWM) || defined(BACKLIGHT_PWM_TIMER)  // pwm through software
179
180 // we support multiple backlight pins
181 #        ifndef BACKLIGHT_LED_COUNT
182 #            define BACKLIGHT_LED_COUNT 1
183 #        endif
184
185 #        if BACKLIGHT_LED_COUNT == 1
186 #            define BACKLIGHT_PIN_INIT \
187                 { BACKLIGHT_PIN }
188 #        else
189 #            define BACKLIGHT_PIN_INIT BACKLIGHT_PINS
190 #        endif
191
192 #        define FOR_EACH_LED(x)                                 \
193             for (uint8_t i = 0; i < BACKLIGHT_LED_COUNT; i++) { \
194                 uint8_t backlight_pin = backlight_pins[i];      \
195                 { x }                                           \
196             }
197
198 static const uint8_t backlight_pins[BACKLIGHT_LED_COUNT] = BACKLIGHT_PIN_INIT;
199
200 #    else  // full hardware PWM
201
202 // we support only one backlight pin
203 static const uint8_t backlight_pin = BACKLIGHT_PIN;
204 #        define FOR_EACH_LED(x) x
205
206 #    endif
207
208 #    ifdef NO_HARDWARE_PWM
209 __attribute__((weak)) void backlight_init_ports(void) {
210     // Setup backlight pin as output and output to on state.
211     FOR_EACH_LED(setPinOutput(backlight_pin); backlight_on(backlight_pin);)
212
213 #        ifdef BACKLIGHT_BREATHING
214     if (is_backlight_breathing()) {
215         breathing_enable();
216     }
217 #        endif
218 }
219
220 __attribute__((weak)) void backlight_set(uint8_t level) {}
221
222 uint8_t backlight_tick = 0;
223
224 #        ifndef BACKLIGHT_CUSTOM_DRIVER
225 void backlight_task(void) {
226     if ((0xFFFF >> ((BACKLIGHT_LEVELS - get_backlight_level()) * ((BACKLIGHT_LEVELS + 1) / 2))) & (1 << backlight_tick)) {
227         FOR_EACH_LED(backlight_on(backlight_pin);)
228     } else {
229         FOR_EACH_LED(backlight_off(backlight_pin);)
230     }
231     backlight_tick = (backlight_tick + 1) % 16;
232 }
233 #        endif
234
235 #        ifdef BACKLIGHT_BREATHING
236 #            ifndef BACKLIGHT_CUSTOM_DRIVER
237 #                error "Backlight breathing only available with hardware PWM. Please disable."
238 #            endif
239 #        endif
240
241 #    else  // hardware pwm through timer
242
243 #        ifdef BACKLIGHT_PWM_TIMER
244
245 // The idea of software PWM assisted by hardware timers is the following
246 // we use the hardware timer in fast PWM mode like for hardware PWM, but
247 // instead of letting the Output Match Comparator control the led pin
248 // (which is not possible since the backlight is not wired to PWM pins on the
249 // CPU), we do the LED on/off by oursleves.
250 // The timer is setup to count up to 0xFFFF, and we set the Output Compare
251 // register to the current 16bits backlight level (after CIE correction).
252 // This means the CPU will trigger a compare match interrupt when the counter
253 // reaches the backlight level, where we turn off the LEDs,
254 // but also an overflow interrupt when the counter rolls back to 0,
255 // in which we're going to turn on the LEDs.
256 // The LED will then be on for OCRxx/0xFFFF time, adjusted every 244Hz.
257
258 // Triggered when the counter reaches the OCRx value
259 ISR(TIMERx_COMPA_vect) { FOR_EACH_LED(backlight_off(backlight_pin);) }
260
261 // Triggered when the counter reaches the TOP value
262 // this one triggers at F_CPU/65536 =~ 244 Hz
263 ISR(TIMERx_OVF_vect) {
264 #            ifdef BACKLIGHT_BREATHING
265     if (is_breathing()) {
266         breathing_task();
267     }
268 #            endif
269     // for very small values of OCRxx (or backlight level)
270     // we can't guarantee this whole code won't execute
271     // at the same time as the compare match interrupt
272     // which means that we might turn on the leds while
273     // trying to turn them off, leading to flickering
274     // artifacts (especially while breathing, because breathing_task
275     // takes many computation cycles).
276     // so better not turn them on while the counter TOP is very low.
277     if (OCRxx > 256) {
278         FOR_EACH_LED(backlight_on(backlight_pin);)
279     }
280 }
281
282 #        endif
283
284 #        define TIMER_TOP 0xFFFFU
285
286 // See http://jared.geek.nz/2013/feb/linear-led-pwm
287 static uint16_t cie_lightness(uint16_t v) {
288     if (v <= 5243)     // if below 8% of max
289         return v / 9;  // same as dividing by 900%
290     else {
291         uint32_t y = (((uint32_t)v + 10486) << 8) / (10486 + 0xFFFFUL);  // add 16% of max and compare
292         // to get a useful result with integer division, we shift left in the expression above
293         // and revert what we've done again after squaring.
294         y = y * y * y >> 8;
295         if (y > 0xFFFFUL)  // prevent overflow
296             return 0xFFFFU;
297         else
298             return (uint16_t)y;
299     }
300 }
301
302 // range for val is [0..TIMER_TOP]. PWM pin is high while the timer count is below val.
303 static inline void set_pwm(uint16_t val) { OCRxx = val; }
304
305 #        ifndef BACKLIGHT_CUSTOM_DRIVER
306 __attribute__((weak)) void backlight_set(uint8_t level) {
307     if (level > BACKLIGHT_LEVELS) level = BACKLIGHT_LEVELS;
308
309     if (level == 0) {
310 #            ifdef BACKLIGHT_PWM_TIMER
311         if (OCRxx) {
312             TIMSKx &= ~(_BV(OCIExA));
313             TIMSKx &= ~(_BV(TOIEx));
314             FOR_EACH_LED(backlight_off(backlight_pin);)
315         }
316 #            else
317         // Turn off PWM control on backlight pin
318         TCCRxA &= ~(_BV(COMxx1));
319 #            endif
320     } else {
321 #            ifdef BACKLIGHT_PWM_TIMER
322         if (!OCRxx) {
323             TIMSKx |= _BV(OCIExA);
324             TIMSKx |= _BV(TOIEx);
325         }
326 #            else
327         // Turn on PWM control of backlight pin
328         TCCRxA |= _BV(COMxx1);
329 #            endif
330     }
331     // Set the brightness
332     set_pwm(cie_lightness(TIMER_TOP * (uint32_t)level / BACKLIGHT_LEVELS));
333 }
334
335 void backlight_task(void) {}
336 #        endif  // BACKLIGHT_CUSTOM_DRIVER
337
338 #        ifdef BACKLIGHT_BREATHING
339
340 #            define BREATHING_NO_HALT 0
341 #            define BREATHING_HALT_OFF 1
342 #            define BREATHING_HALT_ON 2
343 #            define BREATHING_STEPS 128
344
345 static uint8_t breathing_period = BREATHING_PERIOD;
346 static uint8_t breathing_halt = BREATHING_NO_HALT;
347 static uint16_t breathing_counter = 0;
348
349 #            ifdef BACKLIGHT_PWM_TIMER
350 static bool breathing = false;
351
352 bool is_breathing(void) { return breathing; }
353
354 #                define breathing_interrupt_enable() \
355                     do {                             \
356                         breathing = true;            \
357                     } while (0)
358 #                define breathing_interrupt_disable() \
359                     do {                              \
360                         breathing = false;            \
361                     } while (0)
362 #            else
363
364 bool is_breathing(void) { return !!(TIMSKx & _BV(TOIEx)); }
365
366 #                define breathing_interrupt_enable() \
367                     do {                             \
368                         TIMSKx |= _BV(TOIEx);        \
369                     } while (0)
370 #                define breathing_interrupt_disable() \
371                     do {                              \
372                         TIMSKx &= ~_BV(TOIEx);        \
373                     } while (0)
374 #            endif
375
376 #            define breathing_min()        \
377                 do {                       \
378                     breathing_counter = 0; \
379                 } while (0)
380 #            define breathing_max()                                 \
381                 do {                                                \
382                     breathing_counter = breathing_period * 244 / 2; \
383                 } while (0)
384
385 void breathing_enable(void) {
386     breathing_counter = 0;
387     breathing_halt = BREATHING_NO_HALT;
388     breathing_interrupt_enable();
389 }
390
391 void breathing_pulse(void) {
392     if (get_backlight_level() == 0)
393         breathing_min();
394     else
395         breathing_max();
396     breathing_halt = BREATHING_HALT_ON;
397     breathing_interrupt_enable();
398 }
399
400 void breathing_disable(void) {
401     breathing_interrupt_disable();
402     // Restore backlight level
403     backlight_set(get_backlight_level());
404 }
405
406 void breathing_self_disable(void) {
407     if (get_backlight_level() == 0)
408         breathing_halt = BREATHING_HALT_OFF;
409     else
410         breathing_halt = BREATHING_HALT_ON;
411 }
412
413 void breathing_toggle(void) {
414     if (is_breathing())
415         breathing_disable();
416     else
417         breathing_enable();
418 }
419
420 void breathing_period_set(uint8_t value) {
421     if (!value) value = 1;
422     breathing_period = value;
423 }
424
425 void breathing_period_default(void) { breathing_period_set(BREATHING_PERIOD); }
426
427 void breathing_period_inc(void) { breathing_period_set(breathing_period + 1); }
428
429 void breathing_period_dec(void) { breathing_period_set(breathing_period - 1); }
430
431 /* To generate breathing curve in python:
432  * from math import sin, pi; [int(sin(x/128.0*pi)**4*255) for x in range(128)]
433  */
434 static const uint8_t breathing_table[BREATHING_STEPS] PROGMEM = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 17, 20, 24, 28, 32, 36, 41, 46, 51, 57, 63, 70, 76, 83, 91, 98, 106, 113, 121, 129, 138, 146, 154, 162, 170, 178, 185, 193, 200, 207, 213, 220, 225, 231, 235, 240, 244, 247, 250, 252, 253, 254, 255, 254, 253, 252, 250, 247, 244, 240, 235, 231, 225, 220, 213, 207, 200, 193, 185, 178, 170, 162, 154, 146, 138, 129, 121, 113, 106, 98, 91, 83, 76, 70, 63, 57, 51, 46, 41, 36, 32, 28, 24, 20, 17, 15, 12, 10, 8, 6, 5, 4, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
435
436 // Use this before the cie_lightness function.
437 static inline uint16_t scale_backlight(uint16_t v) { return v / BACKLIGHT_LEVELS * get_backlight_level(); }
438
439 #            ifdef BACKLIGHT_PWM_TIMER
440 void breathing_task(void)
441 #            else
442 /* Assuming a 16MHz CPU clock and a timer that resets at 64k (ICR1), the following interrupt handler will run
443  * about 244 times per second.
444  */
445 ISR(TIMERx_OVF_vect)
446 #            endif
447 {
448     uint16_t interval = (uint16_t)breathing_period * 244 / BREATHING_STEPS;
449     // resetting after one period to prevent ugly reset at overflow.
450     breathing_counter = (breathing_counter + 1) % (breathing_period * 244);
451     uint8_t index = breathing_counter / interval % BREATHING_STEPS;
452
453     if (((breathing_halt == BREATHING_HALT_ON) && (index == BREATHING_STEPS / 2)) || ((breathing_halt == BREATHING_HALT_OFF) && (index == BREATHING_STEPS - 1))) {
454         breathing_interrupt_disable();
455     }
456
457     set_pwm(cie_lightness(scale_backlight((uint16_t)pgm_read_byte(&breathing_table[index]) * 0x0101U)));
458 }
459
460 #        endif  // BACKLIGHT_BREATHING
461
462 __attribute__((weak)) void backlight_init_ports(void) {
463     // Setup backlight pin as output and output to on state.
464     FOR_EACH_LED(setPinOutput(backlight_pin); backlight_on(backlight_pin);)
465
466     // I could write a wall of text here to explain... but TL;DW
467     // Go read the ATmega32u4 datasheet.
468     // And this: http://blog.saikoled.com/post/43165849837/secret-konami-cheat-code-to-high-resolution-pwm-on
469
470 #        ifdef BACKLIGHT_PWM_TIMER
471     // TimerX setup, Fast PWM mode count to TOP set in ICRx
472     TCCRxA = _BV(WGM11);  // = 0b00000010;
473     // clock select clk/1
474     TCCRxB = _BV(WGM13) | _BV(WGM12) | _BV(CS10);  // = 0b00011001;
475 #        else  // hardware PWM
476     // Pin PB7 = OCR1C (Timer 1, Channel C)
477     // Compare Output Mode = Clear on compare match, Channel C = COM1C1=1 COM1C0=0
478     // (i.e. start high, go low when counter matches.)
479     // WGM Mode 14 (Fast PWM) = WGM13=1 WGM12=1 WGM11=1 WGM10=0
480     // Clock Select = clk/1 (no prescaling) = CS12=0 CS11=0 CS10=1
481
482     /*
483     14.8.3:
484     "In fast PWM mode, the compare units allow generation of PWM waveforms on the OCnx pins. Setting the COMnx1:0 bits to two will produce a non-inverted PWM [..]."
485     "In fast PWM mode the counter is incremented until the counter value matches either one of the fixed values 0x00FF, 0x01FF, or 0x03FF (WGMn3:0 = 5, 6, or 7), the value in ICRn (WGMn3:0 = 14), or the value in OCRnA (WGMn3:0 = 15)."
486     */
487     TCCRxA = _BV(COMxx1) | _BV(WGM11);             // = 0b00001010;
488     TCCRxB = _BV(WGM13) | _BV(WGM12) | _BV(CS10);  // = 0b00011001;
489 #        endif
490     // Use full 16-bit resolution. Counter counts to ICR1 before reset to 0.
491     ICRx = TIMER_TOP;
492
493     backlight_init();
494 #        ifdef BACKLIGHT_BREATHING
495     if (is_backlight_breathing()) {
496         breathing_enable();
497     }
498 #        endif
499 }
500
501 #    endif  // hardware backlight
502
503 #else  // no backlight
504
505 __attribute__((weak)) void backlight_init_ports(void) {}
506
507 __attribute__((weak)) void backlight_set(uint8_t level) {}
508
509 #endif  // backlight