Skip to content

Battery Snippets

Joseph Freeston edited this page May 13, 2023 · 2 revisions

Add the libraries you need

In order to get the battery voltage, you will need to download this .zip file and extract its contents into your lib folder: battery_lib_cpy8.x.x_5-13-23.zip

Important Note

Your ESP32 boards have been modified by Mr. Chin such that the battery can be plugged in and on simultaneous to the board being plugged into your computer via USB-C.

Battery monitoring will only work with the battery plugged in and on (if you are only powering from the computer, you will see an error)

Code

Initialization

Required imports in order to be able to use the voltage sensor:

import board
from adafruit_lc709203f import LC709203F

Initialize the voltage sensor

i2c = board.I2C()  # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C()  # For using the built-in STEMMA QT connector on a microcontroller
voltage_sensor = LC709203F(i2c)

If you have already initialized the i2c bus for use with your environmental sensor, you will only need the following

voltage_sensor = LC709203F(i2c)

The voltage sensor is on the microcontroller board, connected internally to the i2c bus (SDA and SCL) that you used to connect your environmental sensor.

Getting the battery voltage

You can treat voltage_sensor.cell_voltage as a variable whose value (as a decimal) is always equal to the current battery voltage.

Print the current battery voltage to the terminal:

print(voltage_sensor.cell_voltage)

Posting the Battery Voltage

Importing the BatteryLevel DataPoint subclass...

from servercom import BatteryLevel

Assuming connection is a properly initialized servercom.Connection() instance and voltage_sensor is initialized as described above...

connection.post(BatteryLevel(voltage_sensor.cell_voltage))

Voltage to Percentage

The adafruit_lc709203f library has a feature for estimating the percent capacity remaining for lithium batteries, but it is not intended for doing these calculations for alkaline AA batteries such as the ones we are using. Keep in mind that you are using three cells

(This guy reviews all sorts of batteries and tests them under a handful of current conditions.)

Further Reference

If you seek further information, check these links out:

Clone this wiki locally