from maix import i2c, pinmap, time

# 配置 I2C1 引脚（请根据实际连接修改）
pinmap.set_pin_function("P18", "I2C1_SCL")
pinmap.set_pin_function("P21", "I2C1_SDA")

bus = i2c.I2C(1, i2c.Mode.MASTER)

INA226_ADDR = 0x40

# 寄存器定义
REG_CONFIGURATION = 0x00
REG_BUS_VOLTAGE = 0x02
REG_CALIBRATION = 0x05

# 校准值（不读取电流/功率时也可以省略）
CALIBRATION_VALUE = 0x1400

def write_register(reg, value):
    data = [(value >> 8) & 0xFF, value & 0xFF]
    bus.writeto_mem(INA226_ADDR, reg, bytes(data))

def read_register(reg):
    data = bus.readfrom_mem(INA226_ADDR, reg, 2)
    return (data[0] << 8) | data[1]

def init_ina226():
    write_register(REG_CONFIGURATION, 0x4527)
    write_register(REG_CALIBRATION, CALIBRATION_VALUE)

def get_bus_voltage():
    raw = read_register(REG_BUS_VOLTAGE)
    return raw * 1.25 / 1000  # 单位 V

def voltage_to_percent(voltage):
    if voltage >= 4.20:
        return 100
    elif voltage >= 4.15:
        return 95
    elif voltage >= 4.10:
        return 90
    elif voltage >= 4.05:
        return 85
    elif voltage >= 4.00:
        return 80
    elif voltage >= 3.95:
        return 75
    elif voltage >= 3.90:
        return 70
    elif voltage >= 3.85:
        return 65
    elif voltage >= 3.80:
        return 60
    elif voltage >= 3.75:
        return 55
    elif voltage >= 3.70:
        return 50
    elif voltage >= 3.65:
        return 45
    elif voltage >= 3.60:
        return 40
    elif voltage >= 3.55:
        return 35
    elif voltage >= 3.50:
        return 30
    elif voltage >= 3.45:
        return 25
    elif voltage >= 3.40:
        return 20
    elif voltage >= 3.35:
        return 15
    elif voltage >= 3.30:
        return 10
    elif voltage >= 3.20:
        return 5
    else:
        return 0

# 初始化 INA226
init_ina226()

# 主循环，只显示电量百分比
while True:
    voltage = get_bus_voltage()
    battery_percent = voltage_to_percent(voltage)
    print(f"当前电压: {voltage:.3f} V")
    print(f"估算电池电量: {battery_percent} %\n")
    time.sleep(2000)
