1
0
Fork 0
forked from forks/qmk_firmware
qmk_firmware/quantum/backlight/backlight_software.c
Jeff Epler 9632360caa
Use a macro to compute the size of arrays at compile time (#18044)
* Add ARRAY_SIZE and CEILING utility macros

* Apply a coccinelle patch to use ARRAY_SIZE

* fix up some straggling items

* Fix 'make test:secure'

* Enhance ARRAY_SIZE macro to reject acting on pointers

The previous definition would not produce a diagnostic for
```
int *p;
size_t num_elem = ARRAY_SIZE(p)
```
but the new one will.

* explicitly get definition of ARRAY_SIZE

* Convert to ARRAY_SIZE when const is involved

The following spatch finds additional instances where the array is
const and the division is by the size of the type, not the size of
the first element:
```
@ rule5a using "empty.iso" @
type T;
const T[] E;
@@

- (sizeof(E)/sizeof(T))
+ ARRAY_SIZE(E)

@ rule6a using "empty.iso" @
type T;
const T[] E;
@@

- sizeof(E)/sizeof(T)
+ ARRAY_SIZE(E)
```

* New instances of ARRAY_SIZE added since initial spatch run

* Use `ARRAY_SIZE` in docs (found by grep)

* Manually use ARRAY_SIZE

hs_set is expected to be the same size as uint16_t, though it's made
of two 8-bit integers

* Just like char, sizeof(uint8_t) is guaranteed to be 1

This is at least true on any plausible system where qmk is actually used.

Per my understanding it's universally true, assuming that uint8_t exists:
https://stackoverflow.com/questions/48655310/can-i-assume-that-sizeofuint8-t-1

* Run qmk-format on core C files touched in this branch

Co-authored-by: Stefan Kerkmann <karlk90@pm.me>
2022-08-30 10:20:04 +02:00

55 lines
1.3 KiB
C

#include "quantum.h"
#include "backlight.h"
#include "backlight_driver_common.h"
#ifdef BACKLIGHT_BREATHING
# error "Backlight breathing is not available for software PWM. Please disable."
#endif
static uint16_t s_duty_pattern = 0;
// clang-format off
/** \brief PWM duty patterns
*
* We scale the current backlight level to an index within this array. This allows
* backlight_task to focus on just switching LEDs on/off, and we can predict the duty pattern
*/
static const uint16_t backlight_duty_table[] = {
0b0000000000000000,
0b1000000000000000,
0b1000000010000000,
0b1000001000010000,
0b1000100010001000,
0b1001001001001000,
0b1010101010101010,
0b1110111011101110,
0b1111111111111111,
};
#define backlight_duty_table_size ARRAY_SIZE(backlight_duty_table)
// clang-format on
static uint8_t scale_backlight(uint8_t v) {
return v * (backlight_duty_table_size - 1) / BACKLIGHT_LEVELS;
}
void backlight_init_ports(void) {
backlight_pins_init();
}
void backlight_set(uint8_t level) {
s_duty_pattern = backlight_duty_table[scale_backlight(level)];
}
void backlight_task(void) {
static uint8_t backlight_tick = 0;
if (s_duty_pattern & ((uint16_t)1 << backlight_tick)) {
backlight_pins_on();
} else {
backlight_pins_off();
}
backlight_tick = (backlight_tick + 1) % 16;
}