Skip to main content

m5stack_core/driver/
axp2101.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Minimal AXP2101 PMIC driver for M5Stack CoreS3 (I2C 0x34).
3//!
4//! Only DLDO1 (backlight), battery voltage ADC, VBUS detection and soft
5//! power-off are used.
6//!
7//! Register map (XPowersLib `isVbusGood`, M5Unified `isVBUS`):
8//!   0x00  Power status    bit 5 = VBUS good (bit 3 is battery-connected)
9//!   0x10  Common config   bit 0 = soft power-off (also PWRON-shut / PWROK / discharge)
10//!   0x34  VBAT ADC high   bits[5:0] = high 6 bits of 14-bit reading (1 mV/LSB)
11//!   0x35  VBAT ADC low    bits[7:0] = low 8 bits
12//!   0x90  LDO enable      bit 7 = DLDO1 enable
13//!   0x99  DLDO1 voltage   bits[4:0] = (mV − 500) / 100, range 500–3400 mV
14//!
15//! Datasheet: <https://m5stack.oss-cn-shenzhen.aliyuncs.com/resource/docs/products/core/CoreS3/AXP2101_Datasheet_V1.1_en.pdf>
16//! Also: <https://github.com/lewisxhe/XPowersLib> (register reference)
17use thiserror_no_std::Error;
18
19use crate::io::shared_i2c::SharedI2cBus;
20
21const REG_PWR_STATUS: u8 = 0x00;
22const REG_COMMON_CONFIG: u8 = 0x10;
23const REG_ADC_EN: u8 = 0x30; // ADC channel enable (XPowersLib: ADC_CHANNEL_CTRL)
24const REG_LDO_EN: u8 = 0x90;
25const REG_DLDO1_VOL: u8 = 0x99;
26const REG_VBAT_H: u8 = 0x34;
27
28const DLDO1_VOL_MIN_MV: u16 = 500;
29const DLDO1_VOL_MAX_MV: u16 = 3400;
30const DLDO1_VOL_STEP_MV: u16 = 100;
31const DLDO1_EN_BIT: u8 = 0x80; // bit 7
32const VBUS_GOOD_BIT: u8 = 0x20; // bit 5
33const VBAT_ADC_EN_BIT: u8 = 0x01; // REG 0x30 bit 0 = battery-voltage ADC
34const SOFT_PWROFF_BIT: u8 = 0x01; // REG 0x10 bit 0
35
36#[derive(Debug, Error)]
37pub enum Axp2101Error {
38    #[error("I2C error: {0:?}")]
39    I2cError(#[from] esp_hal::i2c::master::Error),
40
41    #[error("Voltage out of range")]
42    VoltageOutOfRange,
43}
44
45pub struct Axp2101Driver {
46    i2c: &'static SharedI2cBus,
47    address: u8,
48}
49
50impl Axp2101Driver {
51    pub fn new(i2c: &'static SharedI2cBus, address: u8) -> Self {
52        Self { i2c, address }
53    }
54
55    async fn read_reg(&mut self, reg: u8) -> Result<u8, Axp2101Error> {
56        let mut buf = [0u8; 1];
57        self.i2c
58            .lock()
59            .await
60            .write_read_async(self.address, &[reg], &mut buf)
61            .await?;
62        debug!("AXP2101 rd 0x{:02x} = 0x{:02x}", reg, buf[0]);
63        Ok(buf[0])
64    }
65
66    async fn write_reg(&mut self, reg: u8, value: u8) -> Result<(), Axp2101Error> {
67        debug!("AXP2101 wr 0x{:02x} = 0x{:02x}", reg, value);
68        self.i2c
69            .lock()
70            .await
71            .write_async(self.address, &[reg, value])
72            .await?;
73        Ok(())
74    }
75
76    /// Enable or disable DLDO1 and set output voltage (mV). Range: 500–3400 mV, 100 mV steps.
77    pub async fn set_dldo1(&mut self, enabled: bool, mv: u16) -> Result<(), Axp2101Error> {
78        if !(DLDO1_VOL_MIN_MV..=DLDO1_VOL_MAX_MV).contains(&mv)
79            || !(mv - DLDO1_VOL_MIN_MV).is_multiple_of(DLDO1_VOL_STEP_MV)
80        {
81            return Err(Axp2101Error::VoltageOutOfRange);
82        }
83        let vol_val = ((mv - DLDO1_VOL_MIN_MV) / DLDO1_VOL_STEP_MV) as u8;
84        debug!(
85            "AXP2101 DLDO1 enabled={} {}mV (reg_val={})",
86            enabled, mv, vol_val
87        );
88        self.write_reg(REG_DLDO1_VOL, vol_val).await?;
89
90        let en_reg = self.read_reg(REG_LDO_EN).await?;
91        let en_val = if enabled {
92            en_reg | DLDO1_EN_BIT
93        } else {
94            en_reg & !DLDO1_EN_BIT
95        };
96        self.write_reg(REG_LDO_EN, en_val).await?;
97        Ok(())
98    }
99
100    /// Soft power-off: drop every rail and stay down until the power key is
101    /// pressed.
102    ///
103    /// The deepest off state CoreS3 has: every rail down, against the ~10-30 mA
104    /// an ESP deep sleep still leaves on VDD_3V3 (AW9523B, FT6336U, LCD logic,
105    /// this chip). The power key reaches PWRON and nothing else, which is
106    /// exactly what brings the rails back.
107    ///
108    /// The alternative is an ESP deep sleep woken by touch: TOUCH_INT ->
109    /// AW9523B P1_2 -> AW9523B INTN -> GPIO21, an RTC IO (M5Unified uses it as
110    /// its CoreS3 `_wakeupPin`). That trades the residual draw for a nicer wake
111    /// gesture; this trades the gesture for the draw.
112    ///
113    /// Read-modify-write — REG 0x10 also holds the PWRON-shutdown, PWROK-pin
114    /// and internal-discharge configuration.
115    ///
116    /// Returns only if the write failed; on success the caller is gone with the
117    /// rails. Note the PMIC powers back up on its own while VBUS is present.
118    pub async fn power_off(&mut self) -> Result<(), Axp2101Error> {
119        let cfg = self.read_reg(REG_COMMON_CONFIG).await?;
120        self.write_reg(REG_COMMON_CONFIG, cfg | SOFT_PWROFF_BIT)
121            .await
122    }
123
124    /// Enable the battery-voltage ADC channel (REG 0x30 bit 0). Must be called
125    /// once before [`battery_voltage_mv`](Self::battery_voltage_mv) returns a
126    /// live reading — the ADC is off at reset, so the VBAT registers read 0.
127    pub async fn enable_battery_adc(&mut self) -> Result<(), Axp2101Error> {
128        let en = self.read_reg(REG_ADC_EN).await?;
129        self.write_reg(REG_ADC_EN, en | VBAT_ADC_EN_BIT).await?;
130        Ok(())
131    }
132
133    /// Read battery voltage in mV (14-bit ADC, 1 mV/LSB).
134    pub async fn battery_voltage_mv(&mut self) -> Result<u16, Axp2101Error> {
135        let hi = self.read_reg(REG_VBAT_H).await?;
136        let mut lo_buf = [0u8; 1];
137        self.i2c
138            .lock()
139            .await
140            .write_read_async(self.address, &[REG_VBAT_H + 1], &mut lo_buf)
141            .await?;
142        debug!("AXP2101 rd 0x{:02x} = 0x{:02x}", REG_VBAT_H + 1, lo_buf[0]);
143        let raw = ((hi as u16 & 0x3F) << 8) | lo_buf[0] as u16;
144        Ok(raw)
145    }
146
147    /// Returns true if VBUS (USB power) is present.
148    pub async fn vbus_present(&mut self) -> Result<bool, Axp2101Error> {
149        let status = self.read_reg(REG_PWR_STATUS).await?;
150        Ok(status & VBUS_GOOD_BIT != 0)
151    }
152}