| 1 |
# Basic MAX17048 library for OMGS3 and other Unexpected Maker products |
| 2 |
# MIT license; Copyright (c) 2024 Seon Rozenblum - Unexpected Maker |
| 3 |
# |
| 4 |
# Project home: |
| 5 |
# https://unexpectedmaker.com |
| 6 |
|
| 7 |
from machine import I2C |
| 8 |
|
| 9 |
|
| 10 |
class MAX17048: |
| 11 |
_MAX17048_ADDRESS = 0x36 |
| 12 |
|
| 13 |
_VCELL_REGISTER = 0x02 |
| 14 |
_SOC_REGISTER = 0x04 |
| 15 |
_MODE_REGISTER = 0x06 |
| 16 |
_VERSION_REGISTER = 0x08 |
| 17 |
_HIBRT_REGISTER = 0x0A |
| 18 |
_CONFIG_REGISTER = 0x0C |
| 19 |
_COMMAND_REGISTER = 0xFE |
| 20 |
|
| 21 |
def __init__(self, i2c, address=_MAX17048_ADDRESS): |
| 22 |
self.i2c = i2c |
| 23 |
self.address = address |
| 24 |
|
| 25 |
def _read_register(self, register, num_bytes): |
| 26 |
result = self.i2c.readfrom_mem(self.address, register, num_bytes) |
| 27 |
return int.from_bytes(result, "big") |
| 28 |
|
| 29 |
def _write_register(self, register, value, num_bytes): |
| 30 |
data = value.to_bytes(num_bytes, "big") |
| 31 |
self.i2c.writeto_mem(self.address, register, data) |
| 32 |
|
| 33 |
@property |
| 34 |
def cell_voltage(self): |
| 35 |
"""The voltage of the connected cell in Volts.""" |
| 36 |
raw_voltage = self._read_register(self._VCELL_REGISTER, 2) |
| 37 |
voltage = (raw_voltage >> 4) * 0.00125 |
| 38 |
return voltage |
| 39 |
|
| 40 |
@property |
| 41 |
def state_of_charge(self): |
| 42 |
"""The state of charge of the battery in percentage.""" |
| 43 |
raw_soc = self._read_register(self._SOC_REGISTER, 2) |
| 44 |
return raw_soc / 256 |
| 45 |
|
| 46 |
@property |
| 47 |
def version(self): |
| 48 |
"""The chip version.""" |
| 49 |
return self._read_register(self._VERSION_REGISTER, 2) |
| 50 |
|
| 51 |
@property |
| 52 |
def hibernate(self): |
| 53 |
"""True if the chip is in hibernate mode, False otherwise.""" |
| 54 |
hib = self._read_register(self._HIBRT_REGISTER, 2) |
| 55 |
return (hib & 0x4000) != 0 |
| 56 |
|
| 57 |
@hibernate.setter |
| 58 |
def hibernate(self, value): |
| 59 |
config = self._read_register(self._CONFIG_REGISTER, 2) |
| 60 |
if value: |
| 61 |
config |= 0x8000 # Set the sleep bit |
| 62 |
else: |
| 63 |
config &= ~0x8000 # Clear the sleep bit |
| 64 |
self._write_register(self._CONFIG_REGISTER, config, 2) |
| 65 |
|
| 66 |
def quick_start(self): |
| 67 |
"""Perform a quick start to reset the SOC calculation in the chip.""" |
| 68 |
self._write_register(self._MODE_REGISTER, 0x4000, 2) |
| 69 |
|
| 70 |
def reset(self): |
| 71 |
"""Reset the chip.""" |
| 72 |
self._write_register(self._COMMAND_REGISTER, 0x5400, 2) |