logo

qmk_firmware

custom branch of QMK firmware git clone https://anongit.hacktivis.me/git/qmk_firmware.git

battery_adc.c (1368B)


  1. // Copyright 2025 QMK
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "analog.h"
  4. #include "gpio.h"
  5. #ifndef BATTERY_PIN
  6. # error("BATTERY_PIN not configured!")
  7. #endif
  8. #ifndef BATTERY_REF_VOLTAGE_MV
  9. # define BATTERY_REF_VOLTAGE_MV 3300
  10. #endif
  11. #ifndef BATTERY_VOLTAGE_DIVIDER_R1
  12. # define BATTERY_VOLTAGE_DIVIDER_R1 100
  13. #endif
  14. #ifndef BATTERY_VOLTAGE_DIVIDER_R2
  15. # define BATTERY_VOLTAGE_DIVIDER_R2 100
  16. #endif
  17. // TODO: infer from adc config?
  18. #ifndef BATTERY_ADC_RESOLUTION
  19. # define BATTERY_ADC_RESOLUTION 10
  20. #endif
  21. void battery_driver_init(void) {
  22. gpio_set_pin_input(BATTERY_PIN);
  23. }
  24. uint16_t battery_driver_get_mv(void) {
  25. uint32_t raw = analogReadPin(BATTERY_PIN);
  26. uint32_t bat_mv = raw * BATTERY_REF_VOLTAGE_MV / (1 << BATTERY_ADC_RESOLUTION);
  27. #if BATTERY_VOLTAGE_DIVIDER_R1 > 0 && BATTERY_VOLTAGE_DIVIDER_R2 > 0
  28. bat_mv = bat_mv * (BATTERY_VOLTAGE_DIVIDER_R1 + BATTERY_VOLTAGE_DIVIDER_R2) / BATTERY_VOLTAGE_DIVIDER_R2;
  29. #endif
  30. return bat_mv;
  31. }
  32. uint8_t battery_driver_sample_percent(void) {
  33. uint16_t bat_mv = battery_driver_get_mv();
  34. // https://github.com/zmkfirmware/zmk/blob/3f7c9d7cc4f46617faad288421025ea2a6b0bd28/app/module/drivers/sensor/battery/battery_common.c#L33
  35. if (bat_mv >= 4200) {
  36. return 100;
  37. } else if (bat_mv <= 3450) {
  38. return 0;
  39. }
  40. return bat_mv * 2 / 15 - 459;
  41. }