Line data Source code
1 0 : /*
2 : * Copyright 2024 Embeint Inc
3 : *
4 : * SPDX-License-Identifier: Apache-2.0
5 : */
6 :
7 : #ifndef ZEPHYR_INCLUDE_DRIVERS_SENSOR_BATTERY_H_
8 : #define ZEPHYR_INCLUDE_DRIVERS_SENSOR_BATTERY_H_
9 :
10 : #include <stdint.h>
11 : #include <errno.h>
12 :
13 : #include <zephyr/devicetree.h>
14 : #include <zephyr/math/interpolation.h>
15 : #include <zephyr/sys/util_macro.h>
16 :
17 : #ifdef __cplusplus
18 : extern "C" {
19 : #endif
20 :
21 : /**
22 : * @brief Battery API
23 : * @defgroup battery_apis Battery APIs
24 : * @ingroup sensor_interface
25 : * @{
26 : */
27 :
28 : /* Battery chemistry enumeration.
29 : * Value names must match those from dts/bindings/battery.yaml
30 : */
31 0 : enum battery_chemistry {
32 : BATTERY_CHEMISTRY_UNKNOWN = 0,
33 : BATTERY_CHEMISTRY_NICKEL_CADMIUM,
34 : BATTERY_CHEMISTRY_NICKEL_METAL_HYDRIDE,
35 : BATTERY_CHEMISTRY_LITHIUM_ION,
36 : BATTERY_CHEMISTRY_LITHIUM_ION_POLYMER,
37 : BATTERY_CHEMISTRY_LITHIUM_ION_IRON_PHOSPHATE,
38 : BATTERY_CHEMISTRY_LITHIUM_ION_MANGANESE_OXIDE,
39 : };
40 :
41 : /* Length of open circuit voltage table */
42 0 : #define BATTERY_OCV_TABLE_LEN 11
43 :
44 : /**
45 : * @brief Get the battery chemistry enum value
46 : *
47 : * @param node_id node identifier
48 : */
49 1 : #define BATTERY_CHEMISTRY_DT_GET(node_id) \
50 : UTIL_CAT(BATTERY_CHEMISTRY_, DT_STRING_UPPER_TOKEN_OR(node_id, device_chemistry, UNKNOWN))
51 :
52 : /**
53 : * @brief Get the OCV curve for a given table
54 : *
55 : * @param node_id node identifier
56 : * @param table table to retrieve
57 : */
58 1 : #define BATTERY_OCV_TABLE_DT_GET(node_id, table) \
59 : COND_CODE_1(DT_NODE_HAS_PROP(node_id, table), \
60 : ({DT_FOREACH_PROP_ELEM_SEP(node_id, table, DT_PROP_BY_IDX, (,))}), ({-1}))
61 :
62 : /**
63 : * @brief Convert an OCV table and battery voltage to a charge percentage
64 : *
65 : * @param ocv_table Open circuit voltage curve
66 : * @param voltage_uv Battery voltage in microVolts
67 : *
68 : * @returns Battery state of charge in milliPercent
69 : */
70 1 : static inline int32_t battery_soc_lookup(const int32_t ocv_table[BATTERY_OCV_TABLE_LEN],
71 : uint32_t voltage_uv)
72 : {
73 : static const int32_t soc_axis[BATTERY_OCV_TABLE_LEN] = {
74 : 0, 10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000};
75 :
76 : /* Convert voltage to SoC */
77 : return linear_interpolate(ocv_table, soc_axis, BATTERY_OCV_TABLE_LEN, voltage_uv);
78 : }
79 :
80 : /**
81 : * @}
82 : */
83 :
84 : #ifdef __cplusplus
85 : }
86 : #endif
87 :
88 : #endif /* ZEPHYR_INCLUDE_DRIVERS_SENSOR_BATTERY_H_ */
|