├── .gitignore ├── prj.conf ├── CMakeLists.txt ├── boards ├── xiao_ble_nrf52840.overlay └── xiao_ble_nrf52840_sense.overlay ├── dts └── bindings │ └── xiao-ble-battery.yaml ├── src ├── main.c └── battery │ ├── battery.h │ └── battery.c ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # editors 2 | *.swp 3 | *~ 4 | *.vscode 5 | 6 | # build 7 | /build*/ 8 | -------------------------------------------------------------------------------- /prj.conf: -------------------------------------------------------------------------------- 1 | #Peripherials 2 | CONFIG_GPIO=y 3 | CONFIG_ADC=y 4 | 5 | #USB / Termial 6 | CONFIG_SERIAL=y 7 | CONFIG_LOG=y 8 | 9 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # SPDX-License-Identifier: Apache-2.0 2 | 3 | cmake_minimum_required(VERSION 3.20.0) 4 | find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) 5 | project(peripheral) 6 | 7 | target_sources(app PRIVATE 8 | src/main.c 9 | src/battery/battery.c 10 | ) 11 | -------------------------------------------------------------------------------- /boards/xiao_ble_nrf52840.overlay: -------------------------------------------------------------------------------- 1 | / { 2 | xiao_ble_battery_dev: xiao_ble_battery_dev { 3 | compatible = "xiao-ble-battery"; 4 | charging-enable-gpios = <&gpio0 17 GPIO_ACTIVE_LOW>; 5 | read-enable-gpios = <&gpio0 14 GPIO_ACTIVE_LOW>; 6 | charge-speed-gpios = <&gpio0 13 GPIO_ACTIVE_LOW>; 7 | adc-channel = ; 8 | }; 9 | }; -------------------------------------------------------------------------------- /boards/xiao_ble_nrf52840_sense.overlay: -------------------------------------------------------------------------------- 1 | / { 2 | xiao_ble_battery_dev: xiao_ble_battery_dev { 3 | compatible = "xiao-ble-battery"; 4 | charging-enable-gpios = <&gpio0 17 GPIO_ACTIVE_LOW>; 5 | read-enable-gpios = <&gpio0 14 GPIO_ACTIVE_LOW>; 6 | charge-speed-gpios = <&gpio0 13 GPIO_ACTIVE_LOW>; 7 | adc-channel = ; 8 | }; 9 | }; -------------------------------------------------------------------------------- /dts/bindings/xiao-ble-battery.yaml: -------------------------------------------------------------------------------- 1 | description: binding for XIAO BLE Battery Management Library 2 | 3 | compatible: "xiao-ble-battery" 4 | 5 | properties: 6 | charging-enable-gpios: 7 | type: phandle-array 8 | required: true 9 | description: | 10 | GPIO used to enable charging 11 | 12 | read-enable-gpios: 13 | type: phandle-array 14 | required: true 15 | description: GPIO used to enable the readout of the charging voltage 16 | 17 | charge-speed-gpios: 18 | type: phandle-array 19 | required: true 20 | description: GPIO used to select the charging speed (high = 100mA, low = 50mA) 21 | 22 | adc-input-id: 23 | type: int 24 | default: 7 25 | description: ADC channel id 26 | 27 | adc-gain: 28 | type: int 29 | default: 0 30 | description: ADC channel gain factor. ADC-reference * 6 = 3.6V 31 | 32 | adc-reference: 33 | type: int 34 | default: 4 35 | description: ADC reference. usually 0.6V. 36 | 37 | adc-channel: 38 | type: int 39 | required: true 40 | description: ADC channel to read out the battery voltage. Usually AIN7. 41 | 42 | adc-channel-id: 43 | type: int 44 | default: 7 45 | description: ADC channel to read out the battery voltage 46 | 47 | adc-resolution: 48 | type: int 49 | default: 12 50 | description: ADC resolution 51 | 52 | adc-sample-interval: 53 | type: int 54 | default: 500 55 | description: defines the time between each sample in [us]. 56 | 57 | adc-total-samples: 58 | type: int 59 | default: 10 60 | description: | 61 | Change this to a higher number for better averages 62 | Note that increasing this holds up the thread / ADC for longer. 63 | 64 | adc-acquisition-time: 65 | type: int 66 | default: 0 67 | description: ADC Acquisition time 68 | 69 | battery-callbacks-max: 70 | type: int 71 | default: 3 72 | description: | 73 | Defines the number of battery callbacks. 74 | Feel free to increas it if necessary. 75 | -------------------------------------------------------------------------------- /src/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Marcus Alexander Tjomsaas 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "battery/battery.h" 18 | 19 | #include 20 | #include 21 | #include 22 | LOG_MODULE_REGISTER(main, LOG_LEVEL_INF); 23 | 24 | void log_battery_voltage(uint16_t millivolt) 25 | { 26 | uint8_t battery_percentage = 0; 27 | 28 | int ret = battery_get_percentage(&battery_percentage, millivolt); 29 | if (ret) 30 | { 31 | LOG_ERR("Failed to calculate battery percentage"); 32 | return; 33 | } 34 | 35 | LOG_INF("Battery at %d mV (capacity %d%%)", millivolt, battery_percentage); 36 | } 37 | 38 | void log_charging_state(bool is_charging) 39 | { 40 | LOG_INF("Charger %s", is_charging ? "connected" : "disconnected"); 41 | } 42 | 43 | int main(void) 44 | { 45 | int ret = 0; 46 | k_msleep(1000); // Gives time for the terminal to connect to catch logs 47 | 48 | ret = battery_init(); 49 | if (ret) 50 | { 51 | LOG_ERR("Failed to initialize battery management (error %d)", ret); 52 | return ret; 53 | } 54 | 55 | ret = battery_register_charging_callback(log_charging_state); 56 | if (ret) 57 | { 58 | LOG_ERR("Failed to register charging callback (error %d)", ret); 59 | return ret; 60 | } 61 | 62 | ret = battery_register_sample_callback(log_battery_voltage); 63 | if (ret) 64 | { 65 | LOG_ERR("Failed to register sample callback (error %d)", ret); 66 | return ret; 67 | } 68 | 69 | // Take a one-time sample 70 | battery_sample_once(); 71 | k_sleep(K_SECONDS(3)); 72 | 73 | // Start periodic sampling every 1000 ms 74 | battery_start_sampling(1000); 75 | 76 | while (1) 77 | { 78 | k_sleep(K_SECONDS(60)); 79 | // You can stop periodic sampling if needed 80 | // battery_stop_sampling(); 81 | } 82 | 83 | return 0; 84 | } -------------------------------------------------------------------------------- /src/battery/battery.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Marcus Alexander Tjomsaas 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __BATTERY_H__ 18 | #define __BATTERY_H__ 19 | 20 | #include 21 | #include 22 | 23 | // Callback function type definitions 24 | typedef void (*battery_charging_callback_t)(bool is_charging); 25 | typedef void (*battery_sample_callback_t)(uint16_t millivolt); 26 | 27 | /** 28 | * @brief Register a callback function that is executed every time the charging state changes. 29 | * 30 | * @retval 0 if successful. Negative errno number on error. 31 | * 32 | * @note If the error is -12, try increasing the BATTERY_CALLBACK_MAX define in the library. 33 | */ 34 | int battery_register_charging_callback(battery_charging_callback_t callback); 35 | 36 | /** 37 | * @brief Register a callback function that is executed every time a voltage sample is ready. 38 | * 39 | * @retval 0 if successful. Negative errno number on error. 40 | * 41 | * @note If the error is -12, try increasing the BATTERY_CALLBACK_MAX define in the library. 42 | */ 43 | int battery_register_sample_callback(battery_sample_callback_t callback); 44 | 45 | /** 46 | * @brief Set battery charging to fast charge (100mA). 47 | * 48 | * @retval 0 if successful. Negative errno number on error. 49 | */ 50 | int battery_set_fast_charge(void); 51 | 52 | /** 53 | * @brief Set battery charging to slow charge (50mA). 54 | * 55 | * @retval 0 if successful. Negative errno number on error. 56 | */ 57 | int battery_set_slow_charge(void); 58 | 59 | /** 60 | * @brief Get the current battery voltage in millivolts. 61 | * 62 | * @param[out] battery_millivolt Pointer where the battery voltage will be stored. 63 | * 64 | * @retval 0 if successful. Negative errno number on error. 65 | */ 66 | int battery_get_millivolt(uint16_t *battery_millivolt); 67 | 68 | /** 69 | * @brief Calculate the battery percentage based on the voltage. 70 | * 71 | * @param[out] battery_percentage Pointer where the battery percentage will be stored. 72 | * @param[in] battery_millivolt Voltage reading to calculate the percentage from. 73 | * 74 | * @retval 0 if successful. Negative errno number on error. 75 | */ 76 | int battery_get_percentage(uint8_t *battery_percentage, uint16_t battery_millivolt); 77 | 78 | /** 79 | * @brief Start periodic sampling of the battery voltage. 80 | * 81 | * @param[in] interval_ms Sampling interval in milliseconds. 82 | * 83 | * @retval 0 if successful. Negative errno number on error. 84 | * 85 | * @note Registered sample callbacks are called when a new sample is ready. 86 | */ 87 | int battery_start_sampling(uint32_t interval_ms); 88 | 89 | /** 90 | * @brief Stop periodic sampling of the battery voltage. 91 | * 92 | * @retval 0 if successful. Negative errno number on error. 93 | */ 94 | int battery_stop_sampling(void); 95 | 96 | /** 97 | * @brief Take a one-time battery voltage sample. 98 | * 99 | * @retval 0 if successful. Negative errno number on error. 100 | * 101 | * @note Registered sample callbacks are called when the sample is ready. 102 | */ 103 | int battery_sample_once(void); 104 | 105 | /** 106 | * @brief Initialize the battery management system. 107 | * 108 | * @retval 0 if successful. Negative errno number on error. 109 | */ 110 | int battery_init(void); 111 | 112 | #endif 113 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # XIAO BLE Sense (nRF52840) Battery Management Library 2 | 3 |

4 |
5 | GitHub Repo stars 6 | Hits 7 |

8 | 9 | ## Overview 10 | 11 | This library is designed to manage the battery charging functionality of the XIAO BLE and XIAO BLE Sense board. It supports the following features for a 3.7V LiPo battery: 12 | 13 | - Reading battery voltage. 14 | - Calculating battery capacity as a percentage. 15 | - Setting charging modes (fast or slow). 16 | - Registering callbacks for charging state changes. 17 | - Registering callbacks for battery voltage samples. 18 | - One-shot and periodic battery voltage sampling. 19 | 20 | The library is built on the Zephyr Real-Time Operating System (RTOS). For comprehensive details on Zephyr and how to get started, visit the [Zephyr Getting Started Guide](https://docs.zephyrproject.org/latest/develop/getting_started/index.html). The Nordic Semiconductor [nRF Connect SDK](https://www.nordicsemi.com/Products/Development-software/nRF-Connect-SDK/GetStarted) tool with VSCode is a good alternative as it includes Zephyr (and much more). 21 | 22 | ## Features 23 | 24 | ### Battery Voltage Reading 25 | 26 | - **Function:** `int battery_get_millivolt(uint16_t *battery_millivolt)` 27 | - **Description:** Calculates the battery voltage using the ADC and stores the value in the provided pointer. 28 | - **Usage:** 29 | 30 | ``` 31 | uint16_t voltage; 32 | 33 | int ret = battery_get_millivolt(&voltage); 34 | if (ret == 0) { 35 | // Use the voltage value here 36 | } else { 37 | // Handle error 38 | } 39 | ``` 40 | 41 | ### Battery Percentage Calculation 42 | 43 | - **Function:** `int battery_get_percentage(uint8_t *battery_percentage, uint16_t battery_millivolt)` 44 | - **Description:** Calculates the battery percentage based on the voltage and stores it in the provided pointer. 45 | - **Usage:** 46 | 47 | ``` 48 | uint8_t percentage; 49 | uint16_t voltage; 50 | 51 | battery_get_millivolt(&voltage); 52 | 53 | int ret = battery_get_percentage(&percentage, voltage); 54 | if (ret == 0) { 55 | // Use the percentage value here 56 | } else { 57 | // Handle error 58 | } 59 | ``` 60 | 61 | ### Charging Modes 62 | 63 | - **Set Fast Charge (Default)** 64 | 65 | - **Function:** `int battery_set_fast_charge(void)` 66 | - **Description:** Sets the battery charging current to fast charge mode (100mA). 67 | - **Usage:** 68 | 69 | ``` 70 | int ret = battery_set_fast_charge(); 71 | if (ret != 0) { 72 | // Handle error 73 | } 74 | ``` 75 | 76 | - **Set Slow Charge** 77 | 78 | - **Function:** `int battery_set_slow_charge(void)` 79 | - **Description:** Sets the battery charging current to slow charge mode (50mA). 80 | - **Usage:** 81 | 82 | ``` 83 | int ret = battery_set_slow_charge(); 84 | if (ret != 0) { 85 | // Handle error 86 | } 87 | ``` 88 | 89 | ### Charging State Change Callback 90 | 91 | - **Function:** `int battery_register_charging_changed_callback(battery_charging_changed_callback_t callback)` 92 | - **Description:** Registers a callback function that is executed whenever the charging state changes. 93 | - **Callback Type Definition:** `typedef void (*battery_charging_callback_t)(bool is_charging);` 94 | - **Usage:** 95 | 96 | ``` 97 | void charging_state_changed(bool is_charging) { 98 | if (is_charging) { 99 | // Charging started 100 | } else { 101 | // Charging stopped 102 | } 103 | } 104 | 105 | int ret = battery_register_charging_callback(charging_state_changed); 106 | if (ret != 0) { 107 | // Handle error 108 | } 109 | ``` 110 | 111 | ### Battery Sample Ready Callback 112 | 113 | - **Function:** `int battery_register_sample_callback(battery_sample_callback_t callback);` 114 | - **Description:** Registers a callback function that is executed whenever a battery voltage sample is ready. 115 | - **Callback Type Definition:** `typedef void (*battery_sample_callback_t)(uint16_t millivolt); 116 | ` 117 | - **Usage:** 118 | 119 | ``` 120 | void battery_sample_ready(uint16_t millivolt) { 121 | // Process the millivolt value 122 | } 123 | 124 | int ret = battery_register_sample_callback(battery_sample_ready); 125 | if (ret != 0) { 126 | // Handle error 127 | } 128 | ``` 129 | 130 | ### One-Shot Battery Sampling 131 | 132 | - **Function:** `int battery_sample_once(void)` 133 | - **Description:** Initiates a one-time battery voltage sampling. Registered sample callbacks will be called when the sample is ready. 134 | - **Usage:** 135 | 136 | ``` 137 | int ret = battery_sample_once(); 138 | if (ret != 0) { 139 | // Handle error 140 | } 141 | ``` 142 | 143 | ### Periodic Battery Sampling 144 | 145 | - **Start Periodic Sampling:** 146 | 147 | - **Function:** `int battery_start_sampling(uint32_t interval_ms);` 148 | - **Description:** Starts periodic sampling of the battery voltage at the specified interval in milliseconds. Registered sample callbacks will be called each time a sample is ready. 149 | - **Usage:** 150 | 151 | ``` 152 | uint32_t interval_ms = 1000; // Sample every 1 second 153 | 154 | int ret = battery_start_sampling(interval_ms); 155 | if (ret != 0) { 156 | // Handle error 157 | } 158 | ``` 159 | 160 | - **Stop Periodic Sampling:** 161 | 162 | - **Function:** `int battery_stop_sampling(void);` 163 | - **Description:** Stops periodic sampling of the battery voltage. 164 | - **Usage:** 165 | 166 | ``` 167 | int ret = battery_stop_sampling(); 168 | if (ret != 0) { 169 | // Handle error 170 | } 171 | ``` 172 | 173 | ### Initialization 174 | 175 | - **Function:** `battery_init(void)` 176 | - **Description:** Initializes the battery charging circuit. Must be called before using other battery functions. 177 | - **Usage:** 178 | 179 | ``` 180 | int ret = battery_init(); 181 | if (ret != 0) { 182 | // Handle error 183 | } 184 | ``` 185 | 186 | ### Example Usage 187 | 188 | There is an example in the `main.c` file that demonstrates how to use the battery management library. This example initializes the battery management library, registers callbacks for charging state changes and battery voltage samples, and starts periodic sampling of the battery voltage. 189 | 190 | ## Programming 191 | 192 | ### Adafruit nRF52 Bootloader 193 | 194 | The XIAO BLE Sense is equipped with the Adafruit nRF52 Bootloader, which supports UF2 flashing—a simple drag-and-drop method to program your device. 195 | 196 | #### Entering Bootloader Mode 197 | 198 | 1. Use a USB-C cable to connect to the XIAO BLE to your computer 199 | 2. **Double-Click** the Reset button (located to the left of the USB connector) quickly. The device should enter bootloader mode and appear as a mass storage device named XIAO on your computer. If the device doesn't appear, ensure your USB cable supports data transfer (some cables are charge-only), and check your computer's device manager or disk utility for new devices. 200 | 201 | #### Flashing the Firmware 202 | 203 | - Navigate to the '**build/zephyr/**' directory and locate the '**zephyr.uf2**' file. If you can not find the build folder, build or rebuild the project. 204 | - Drag and drop the **zephyr.uf2** file into the XIAO drive that appeared when the device entered bootloader mode or copy the file using your command line. 205 | 206 | After the UF2 file transfer is complete, the XIAO BLE will automatically reset and launch the new application. 207 | 208 | For additional information on the flashing process and the XIAO BLE Sense board, refer to 209 | the [Zephyr Board Documentation for XIAO BLE](https://docs.zephyrproject.org/latest/boards/seeed/xiao_ble/doc/index.html). 210 | 211 | ## Serial Logging 212 | 213 | Connect to the device's serial port to view log messages from the device. Use a serial terminal application (e.g., PuTTY, Tera Term, Minicom) with the following settings: 214 | 215 | - **Baud Rate:** 115200 216 | - **Data Bits:** 8 217 | - **Parity:** None 218 | - **Stop Bits:** 1 219 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 Marcus Alexander Tjomsaas 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/battery/battery.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2024 Marcus Alexander Tjomsaas 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "battery.h" 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | LOG_MODULE_REGISTER(battery, LOG_LEVEL_INF); 27 | 28 | #if !DT_NODE_EXISTS(DT_NODELABEL(xiao_ble_battery_dev)) 29 | #error "Overlay for xiao_ble_battery_dev node not properly defined." 30 | #endif 31 | 32 | #define BATTERY_NODE DT_NODELABEL(xiao_ble_battery_dev) 33 | #define BATTERY_CALLBACK_MAX DT_PROP(BATTERY_NODE, battery_callbacks_max) 34 | 35 | // Change this to a higher number for better averages 36 | // Note that increasing this holds up the thread / ADC for longer. 37 | #define ADC_TOTAL_SAMPLES DT_PROP(BATTERY_NODE, adc_total_samples) 38 | 39 | //-------------------------------------------------------------- 40 | // ADC setup 41 | 42 | #define ADC_RESOLUTION DT_PROP(BATTERY_NODE, adc_resolution) 43 | #define ADC_CHANNEL DT_PROP(BATTERY_NODE, adc_channel_id) 44 | #define ADC_PORT DT_PROP(BATTERY_NODE, adc_channel) 45 | #define ADC_REFERENCE DT_PROP(BATTERY_NODE, adc_reference) 46 | #define ADC_GAIN DT_PROP(BATTERY_NODE, adc_gain) 47 | #define ADC_SAMPLE_INTERVAL_US DT_PROP(BATTERY_NODE, adc_sample_interval) 48 | #define ADC_ACQUISITION_TIME DT_PROP(BATTERY_NODE, adc_acquisition_time) 49 | 50 | static struct adc_channel_cfg channel_7_cfg = { 51 | .gain = ADC_GAIN, 52 | .reference = ADC_REFERENCE, 53 | .acquisition_time = ADC_ACQUISITION_TIME, 54 | .channel_id = ADC_CHANNEL, 55 | #ifdef CONFIG_ADC_NRFX_SAADC 56 | .input_positive = ADC_PORT 57 | #endif 58 | }; 59 | 60 | static struct adc_sequence_options options = { 61 | .extra_samplings = ADC_TOTAL_SAMPLES - 1, 62 | .interval_us = ADC_SAMPLE_INTERVAL_US, 63 | }; 64 | 65 | static int16_t sample_buffer[ADC_TOTAL_SAMPLES]; 66 | static struct adc_sequence sequence = { 67 | .options = &options, 68 | .channels = BIT(ADC_CHANNEL), 69 | .buffer = sample_buffer, 70 | .buffer_size = sizeof(sample_buffer), 71 | .resolution = ADC_RESOLUTION, 72 | }; 73 | 74 | //-------------------------------------------------------------- 75 | // Local variables 76 | 77 | // MCU peripherals for reading battery voltage 78 | static const struct device *adc_battery_dev = DEVICE_DT_GET(DT_NODELABEL(adc)); 79 | 80 | static const struct gpio_dt_spec charging_enable = GPIO_DT_SPEC_GET_OR(BATTERY_NODE, charging_enable_gpios, {0}); 81 | static const struct gpio_dt_spec read_enable = GPIO_DT_SPEC_GET_OR(BATTERY_NODE, read_enable_gpios, {0}); 82 | static const struct gpio_dt_spec charge_speed = GPIO_DT_SPEC_GET_OR(BATTERY_NODE, charge_speed_gpios, {0}); 83 | 84 | // Battery work and work queue 85 | static struct k_work_delayable sample_periodic_work; 86 | static struct k_work sample_once_work; 87 | 88 | // Charging interrupt 89 | static struct gpio_callback charging_callback; 90 | static struct k_work charging_interrupt_work; 91 | 92 | // Callbacks for change in charging 93 | static battery_charging_callback_t charging_callbacks[BATTERY_CALLBACK_MAX]; 94 | static size_t charging_callbacks_registered = 0; 95 | 96 | // Callbacks for when a battery sample is ready 97 | static battery_sample_callback_t sample_ready_callback[BATTERY_CALLBACK_MAX]; 98 | static size_t sample_ready_callbacks_registered = 0; 99 | 100 | static uint32_t sampling_interval_ms; 101 | static uint8_t is_initialized = false; 102 | 103 | static K_MUTEX_DEFINE(battery_mut); 104 | 105 | typedef struct 106 | { 107 | uint16_t voltage; 108 | uint8_t percentage; 109 | } BatteryState; 110 | 111 | #define BATTERY_STATES_COUNT 11 112 | // Voltage levels in millivolts and corresponding percentages for a typical LiPo battery. 113 | // Adjust these values based on your battery's datasheet for better accuracy. 114 | static BatteryState battery_states[BATTERY_STATES_COUNT] = { 115 | {4200, 100}, // Fully charged 116 | {4110, 90}, 117 | {4020, 80}, 118 | {3930, 70}, 119 | {3840, 60}, 120 | {3750, 50}, 121 | {3660, 40}, 122 | {3570, 30}, 123 | {3480, 20}, 124 | {3390, 10}, 125 | {3300, 0} // Minimum safe voltage 126 | }; 127 | 128 | //------------------------------------------------------------------------------------------ 129 | // Private functions 130 | 131 | static int battery_enable_read() 132 | { 133 | return gpio_pin_set_dt(&read_enable, 1); 134 | } 135 | 136 | static void run_charging_callbacks(struct k_work *work) 137 | { 138 | bool is_charging = gpio_pin_get_dt(&charging_enable); 139 | LOG_DBG("Charger %s", is_charging ? "connected" : "disconnected"); 140 | 141 | for (uint8_t callback = 0; callback < charging_callbacks_registered; callback++) 142 | { 143 | charging_callbacks[callback](is_charging); 144 | } 145 | } 146 | 147 | static void run_sample_ready_callbacks(uint32_t millivolt) 148 | { 149 | 150 | for (uint8_t callback = 0; callback < sample_ready_callbacks_registered; callback++) 151 | { 152 | sample_ready_callback[callback](millivolt); 153 | } 154 | } 155 | 156 | static void charging_callback_handler(const struct device *dev, 157 | struct gpio_callback *cb, 158 | uint32_t pins) 159 | { 160 | k_work_submit(&charging_interrupt_work); 161 | } 162 | 163 | static void sample_periodic_handler(struct k_work *work) 164 | { 165 | uint16_t millivolt; 166 | int ret = battery_get_millivolt(&millivolt); 167 | if (ret) 168 | { 169 | LOG_ERR("Failed to get battery voltage"); 170 | goto reschedule; 171 | } 172 | 173 | // Run all the callbacks waiting for a voltage reading. 174 | run_sample_ready_callbacks(millivolt); 175 | 176 | reschedule: 177 | k_work_reschedule(&sample_periodic_work, K_MSEC(sampling_interval_ms)); 178 | } 179 | 180 | static void sample_once_handler(struct k_work *work) 181 | { 182 | uint16_t millivolt; 183 | int ret = battery_get_millivolt(&millivolt); 184 | if (ret) 185 | { 186 | LOG_ERR("Failed to get battery voltage"); 187 | return; 188 | } 189 | 190 | // Run all the callbacks waiting for voltage readings. 191 | run_sample_ready_callbacks(millivolt); 192 | } 193 | 194 | //------------------------------------------------------------------------------------------ 195 | // Public functions 196 | 197 | int battery_register_charging_callback(battery_charging_callback_t callback) 198 | { 199 | if (charging_callbacks_registered == BATTERY_CALLBACK_MAX) 200 | { 201 | LOG_ERR("Maximum number of callbacks reached, operation aborted"); 202 | return -ENOMEM; 203 | } 204 | 205 | charging_callbacks[charging_callbacks_registered++] = callback; 206 | 207 | return 0; 208 | } 209 | 210 | int battery_register_sample_callback(battery_sample_callback_t callback) 211 | { 212 | if (sample_ready_callbacks_registered == BATTERY_CALLBACK_MAX) 213 | { 214 | LOG_ERR("Maximum number of callbacks reached, operation aborted"); 215 | return -ENOMEM; 216 | } 217 | 218 | sample_ready_callback[sample_ready_callbacks_registered++] = callback; 219 | return 0; 220 | } 221 | 222 | int battery_set_fast_charge() 223 | { 224 | if (!is_initialized) 225 | { 226 | return -ECANCELED; 227 | } 228 | 229 | return gpio_pin_set_dt(&charge_speed, 1); // FAST charge 100mA 230 | } 231 | 232 | int battery_set_slow_charge() 233 | { 234 | if (!is_initialized) 235 | { 236 | return -ECANCELED; 237 | } 238 | 239 | return gpio_pin_set_dt(&charge_speed, 0); // SLOW charge 50mA 240 | } 241 | 242 | int battery_get_millivolt(uint16_t *battery_millivolt) 243 | { 244 | 245 | int ret = 0; 246 | 247 | // Voltage divider circuit (Should tune R1 in software if possible) 248 | const uint16_t R1 = 1037; // Originally 1M ohm, calibrated after measuring actual voltage values. Can happen due to resistor tolerances, temperature ect.. 249 | const uint16_t R2 = 510; // 510K ohm 250 | 251 | // ADC measure 252 | uint16_t adc_vref = adc_ref_internal(adc_battery_dev); 253 | 254 | ret = k_mutex_lock(&battery_mut, K_SECONDS(10)); 255 | if (ret < 0) 256 | { 257 | LOG_ERR("Cannot get battery voltage as mutex is locked"); 258 | return ret; 259 | } 260 | 261 | ret |= adc_read(adc_battery_dev, &sequence); 262 | 263 | if (ret) 264 | { 265 | LOG_WRN("ADC read failed (error %d)", ret); 266 | } 267 | 268 | uint32_t adc_sum = 0; 269 | // Get average sample value. 270 | for (uint8_t sample = 0; sample < ADC_TOTAL_SAMPLES; sample++) 271 | { 272 | adc_sum += sample_buffer[sample]; // ADC value, not millivolt yet. 273 | } 274 | uint32_t adc_average = adc_sum / ADC_TOTAL_SAMPLES; 275 | 276 | // Convert ADC value to millivolts 277 | uint32_t adc_mv = adc_average; 278 | ret |= adc_raw_to_millivolts(adc_vref, ADC_GAIN, ADC_RESOLUTION, &adc_mv); 279 | 280 | // Calculate battery voltage. 281 | float scale_factor = ((float)(R1 + R2)) / R2; 282 | *battery_millivolt = (uint16_t)(adc_mv * scale_factor); 283 | 284 | k_mutex_unlock(&battery_mut); 285 | 286 | LOG_DBG("%d mV", *battery_millivolt); 287 | return ret; 288 | } 289 | 290 | int battery_get_percentage(uint8_t *battery_percentage, uint16_t battery_millivolt) 291 | { 292 | // Ensure voltage is within bounds 293 | if (battery_millivolt >= battery_states[0].voltage) 294 | { 295 | *battery_percentage = 100; 296 | return 0; 297 | } 298 | else if (battery_millivolt <= battery_states[BATTERY_STATES_COUNT - 1].voltage) 299 | { 300 | *battery_percentage = 0; 301 | return 0; 302 | } 303 | 304 | for (uint16_t i = 0; i < BATTERY_STATES_COUNT - 1; i++) 305 | { 306 | uint16_t voltage_high = battery_states[i].voltage; 307 | uint16_t voltage_low = battery_states[i + 1].voltage; 308 | 309 | // Find the two points between which battery_millivolt lies 310 | if (battery_millivolt <= voltage_high && battery_millivolt >= voltage_low) 311 | { 312 | uint8_t percentage_high = battery_states[i].percentage; 313 | uint8_t percentage_low = battery_states[i + 1].percentage; 314 | 315 | int32_t voltage_range = voltage_high - voltage_low; // Should be positive 316 | int32_t percentage_range = percentage_high - percentage_low; // Should be positive 317 | int32_t voltage_diff = battery_millivolt - voltage_low; // Non-negative 318 | 319 | if (voltage_range == 0) 320 | { 321 | *battery_percentage = percentage_high; 322 | } 323 | else 324 | { 325 | *battery_percentage = percentage_low + (voltage_diff * percentage_range) / voltage_range; 326 | } 327 | 328 | LOG_DBG("%d %%", *battery_percentage); 329 | return 0; 330 | } 331 | } 332 | 333 | // If voltage is not within any defined range 334 | return -ESPIPE; 335 | } 336 | 337 | int battery_start_sampling(uint32_t interval_ms) 338 | { 339 | if (interval_ms == 0) 340 | { 341 | LOG_ERR("Sampling interval must be greater than zero"); 342 | return -EINVAL; 343 | } 344 | 345 | sampling_interval_ms = interval_ms; 346 | k_work_schedule(&sample_periodic_work, K_MSEC(interval_ms)); 347 | 348 | LOG_INF("Start sampling battery voltage at %d ms", interval_ms); 349 | return 0; 350 | } 351 | 352 | int battery_stop_sampling(void) 353 | { 354 | k_work_cancel_delayable(&sample_periodic_work); 355 | LOG_INF("Stopped periodic sampling of battery voltage"); 356 | return 0; 357 | } 358 | 359 | int battery_sample_once(void) 360 | { 361 | k_work_submit(&sample_once_work); 362 | return 0; 363 | } 364 | 365 | int battery_init() 366 | { 367 | int ret = 0; 368 | 369 | // ADC setup 370 | if (!device_is_ready(adc_battery_dev)) 371 | { 372 | LOG_ERR("ADC device not found!"); 373 | return -EIO; 374 | } 375 | 376 | ret |= adc_channel_setup(adc_battery_dev, &channel_7_cfg); 377 | if (ret) 378 | { 379 | LOG_ERR("ADC setup failed (error %d)", ret); 380 | return ret; 381 | } 382 | 383 | // GPIO setup 384 | if (!gpio_is_ready_dt(&charging_enable)) 385 | { 386 | LOG_ERR("GPIO charging_enable not found!"); 387 | return -EIO; 388 | } 389 | 390 | if (!gpio_is_ready_dt(&read_enable)) 391 | { 392 | LOG_ERR("GPIO read_enable not found!"); 393 | return -EIO; 394 | } 395 | 396 | if (!gpio_is_ready_dt(&charge_speed)) 397 | { 398 | LOG_ERR("GPIO charging_enable not found!"); 399 | return -EIO; 400 | } 401 | 402 | ret |= gpio_pin_configure_dt(&charging_enable, GPIO_INPUT | GPIO_ACTIVE_LOW); 403 | if (ret) 404 | { 405 | LOG_ERR("Failed to configure GPIO_BATTERY_CHARGING_ENABLE pin (error %d)", ret); 406 | return ret; 407 | } 408 | 409 | ret |= gpio_pin_interrupt_configure_dt(&charging_enable, GPIO_INT_EDGE_BOTH); 410 | if (ret) 411 | { 412 | LOG_ERR("Failed to configure GPIO_BATTERY_CHARGING_ENABLE pin interrupt (error %d)", ret); 413 | return ret; 414 | } 415 | 416 | ret |= gpio_pin_configure_dt(&read_enable, GPIO_OUTPUT | GPIO_ACTIVE_LOW); 417 | if (ret) 418 | { 419 | LOG_ERR("Failed to configure GPIO_BATTERY_READ_ENABLE pin (error %d)", ret); 420 | return ret; 421 | } 422 | ret |= gpio_pin_configure_dt(&charge_speed, GPIO_OUTPUT | GPIO_ACTIVE_LOW); 423 | if (ret) 424 | { 425 | LOG_ERR("Failed to configure GPIO_BATTERY_CHARGE_SPEED pin (error %d)", ret); 426 | return ret; 427 | } 428 | 429 | // Battery workers 430 | k_work_init_delayable(&sample_periodic_work, sample_periodic_handler); 431 | k_work_init(&sample_once_work, sample_once_handler); 432 | 433 | // Charger interrupt setup 434 | k_work_init(&charging_interrupt_work, run_charging_callbacks); 435 | gpio_init_callback(&charging_callback, charging_callback_handler, 436 | BIT(charging_enable.pin)); 437 | gpio_add_callback_dt(&charging_enable, &charging_callback); 438 | 439 | // Lets check the current charging status 440 | bool is_charging = gpio_pin_get_dt(&charging_enable); 441 | LOG_INF("Charger %s", is_charging ? "connected" : "disconnected"); 442 | 443 | is_initialized = true; 444 | LOG_INF("Initialized"); 445 | 446 | // Get ready for battery charging and sampling 447 | ret |= battery_set_fast_charge(); 448 | if (ret) 449 | { 450 | LOG_ERR("Failed to set fast charging (error %d)", ret); 451 | return ret; 452 | } 453 | 454 | ret |= battery_enable_read(); 455 | if (ret) 456 | { 457 | LOG_ERR("Failed to enable battery reading (error %d)", ret); 458 | return ret; 459 | } 460 | 461 | return 0; 462 | } 463 | --------------------------------------------------------------------------------