"""CircuitPython Battery Monitor utility. Wraps analogio.AnalogIn to read voltage via a 2x divider and estimate capacity. """ import analogio import board class BatteryMonitor: def __init__(self, pin=board.IO9): self.adc = analogio.AnalogIn(pin) def read_voltage(self): try: # AnalogIn value is 16-bit (0-65535). Map to 3.3V reference. # Divider is 2x, so actual voltage is scale * 2. raw = self.adc.value voltage = (raw / 65535.0) * 3.3 * 2.0 return round(voltage, 3) except Exception as e: print(f"Error reading battery ADC: {e}") return None def read_percentage(self): voltage = self.read_voltage() if voltage is None: return 0 v_min = 3.0 v_max = 4.2 if voltage <= v_min: return 0 if voltage >= v_max: return 100 pct = (voltage - v_min) / (v_max - v_min) * 100.0 return int(pct) def get_status_summary(self): v = self.read_voltage() p = self.read_percentage() if v is None: return "Battery: Error" return f"Battery: {v:.2f}V ({p}%)"