Skip to content

Commit 6070043

Browse files
authored
Create battery_common.c
1 parent e52d025 commit 6070043

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
2+
/*
3+
* Copyright (c) 2021 The ZMK Contributors
4+
*
5+
* SPDX-License-Identifier: MIT
6+
*/
7+
8+
#include <errno.h>
9+
#include <zephyr/drivers/sensor.h>
10+
11+
#include "battery_common.h"
12+
13+
int battery_channel_get(const struct battery_value *value, enum sensor_channel chan,
14+
struct sensor_value *val_out) {
15+
switch (chan) {
16+
case SENSOR_CHAN_GAUGE_VOLTAGE:
17+
val_out->val1 = value->millivolts / 1000;
18+
val_out->val2 = (value->millivolts % 1000) * 1000U;
19+
break;
20+
21+
case SENSOR_CHAN_GAUGE_STATE_OF_CHARGE:
22+
val_out->val1 = value->state_of_charge;
23+
val_out->val2 = 0;
24+
break;
25+
26+
default:
27+
return -ENOTSUP;
28+
}
29+
30+
return 0;
31+
}
32+
33+
uint8_t lithium_ion_mv_to_pct(int16_t bat_mv) {
34+
static int16_t mv_history[5] = {0};
35+
static uint8_t history_index = 0;
36+
static bool history_filled = false;
37+
38+
// 履歴に追加
39+
mv_history[history_index] = bat_mv;
40+
history_index = (history_index + 1) % 5;
41+
if (history_index == 0) history_filled = true;
42+
43+
// 平均値を計算
44+
int32_t sum = 0;
45+
uint8_t count = history_filled ? 5 : history_index;
46+
for (uint8_t i = 0; i < count; i++) {
47+
sum += mv_history[i];
48+
}
49+
int16_t avg_mv = sum / count;
50+
51+
if (avg_mv >= 2350) {
52+
return 100;
53+
} else if (avg_mv <= 1950) {
54+
return 0;
55+
}
56+
return avg_mv / 4 - 487.5;
57+
}

0 commit comments

Comments
 (0)