m5stack_core/driver/aw9523b.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! AW9523B I2C GPIO expander driver for M5Stack CoreS3 (I2C 0x58).
3//!
4//! Register map (AW9523B English datasheet V1.5, §5 "Register Description"):
5//! 0x00 Input P0 port 0 pin levels; READING CLEARS the interrupt
6//! 0x01 Input P1 port 1 pin levels; READING CLEARS the interrupt
7//! 0x02 Output P0 output latch for port 0 (default 0x00)
8//! 0x03 Output P1 output latch for port 1 (default 0x00)
9//! 0x04 Config P0 direction: 0=output, 1=input (default 0xFF = all input)
10//! 0x05 Config P1 direction: 0=output, 1=input (default 0xFF = all input)
11//! 0x06 Int P0 interrupt mask: 0=enabled, 1=DISABLED (default 0x00)
12//! 0x07 Int P1 interrupt mask, port 1
13//! 0x12 LEDMODE P0 0=LED current mode, 1=GPIO push-pull (default 0x00)
14//! 0x13 LEDMODE P1 0=LED current mode, 1=GPIO push-pull (default 0x00)
15//!
16//! Pin assignment (CoreS3 schematic v1.0 + M5Unified `Power_Class.cpp`):
17//! P0_0 TOUCH_RST active-LOW reset for FT6336U
18//! P0_1 BUS_OUT_EN active-HIGH — enables the M-Bus/Grove 5V output (load switch)
19//! P0_2 AW_RST self-reset (active-LOW)
20//! P0_5 USB_OTG_EN active-HIGH — enables USB OTG (kills USB-JTAG if asserted)
21//! P1_0 CAM_RST camera reset (active-LOW)
22//! P1_1 LCD_RST ILI9342C reset (active-LOW)
23//! P1_2 TOUCH_INT FT6336U interrupt (input)
24//! P1_3 AW_INT the chip's own INTN, looped back as an input
25//!
26//! The INTN **pin** leaves the expander and reaches the ESP32-S3 on **GPIO21**
27//! (M5Unified's CoreS3 `_wakeupPin`, commented there as `I2C_INT`). So the
28//! touch chain is `FT6336U TOUCH_INT -> P1_2 -> INTN -> GPIO21`, which makes
29//! touch a usable deep-sleep wake source: GPIO21 is an RTC IO. The `P1_3`
30//! entry above is the loopback, NOT the end of the chain -- reading it as the
31//! end is how this file previously implied touch could not wake the board.
32//! P1_7 BOOST_EN active-HIGH — enables the SY7088 5V boost converter
33//!
34//! NOTE: the BUS_OUT_EN polarity was verified active-HIGH against M5Unified
35//! (`setExtOutput(true)` *sets* the P0_1 bit) and the ME1502 load-switch topology
36//! — an earlier revision of this file wrongly documented it active-LOW.
37//!
38//! **SAFETY**: `init()` modifies P0 via read-modify-write touching ONLY P0_0
39//! (TOUCH_RST), preserving all other P0 bits at their power-on defaults so
40//! BUS_OUT_EN / USB_OTG_EN stay deasserted. The 5V output is brought up only by
41//! an explicit [`enable_bus_5v`](Aw9523bDriver::enable_bus_5v) call.
42//!
43//! Datasheet: <https://m5stack.oss-cn-shenzhen.aliyuncs.com/resource/docs/products/core/CoreS3/AW9523B-EN.pdf>
44//! CoreS3 schematic: <https://m5stack-doc.oss-cn-shenzhen.aliyuncs.com/490/Sch_M5_CoreS3_v1.0.pdf>
45//! M5Unified: <https://github.com/m5stack/M5Unified/blob/master/src/utility/Power_Class.cpp>
46use embassy_time::{Duration, Timer};
47use thiserror_no_std::Error;
48
49use crate::io::shared_i2c::SharedI2cBus;
50
51pub const ADDR: u8 = 0x58;
52
53const REG_INPUT_P0: u8 = 0x00;
54const REG_INPUT_P1: u8 = 0x01;
55const REG_OUTPUT_P0: u8 = 0x02;
56const REG_OUTPUT_P1: u8 = 0x03;
57const REG_CONFIG_P0: u8 = 0x04;
58const REG_CONFIG_P1: u8 = 0x05;
59const REG_INT_P0: u8 = 0x06; // interrupt mask: 1 = DISABLED
60const REG_INT_P1: u8 = 0x07;
61const REG_GCR: u8 = 0x11; // Global Control: bit4 = P0 push-pull (1) vs open-drain (0)
62const REG_LEDMODE_P0: u8 = 0x12;
63const REG_LEDMODE_P1: u8 = 0x13;
64
65const GCR_P0_PUSH_PULL: u8 = 0x10; // bit4
66
67// P0 pin masks
68pub const P0_TOUCH_RST: u8 = 0x01; // P0_0
69pub const P0_BUS_OUT_EN: u8 = 0x02; // P0_1 — active-HIGH: enables the M-Bus/Grove 5V output
70#[allow(dead_code)]
71pub const P0_AW_RST: u8 = 0x04; // P0_2
72
73// P1 pin masks
74pub const P1_CAM_RST: u8 = 0x01; // P1_0 (output)
75pub const P1_LCD_RST: u8 = 0x02; // P1_1 (output)
76pub const P1_BOOST_EN: u8 = 0x80; // P1_7 — active-HIGH: SY7088 5V boost converter
77#[allow(dead_code)]
78pub const P1_TOUCH_INT: u8 = 0x04; // P1_2 (input)
79#[allow(dead_code)]
80pub const P1_AW_INT: u8 = 0x08; // P1_3 (input)
81
82/// Every port-0 interrupt masked.
83const INT_P0_ALL_MASKED: u8 = 0xFF;
84/// Port 1 with only the touch line able to pull INTN low.
85const INT_P1_TOUCH_ONLY: u8 = !P1_TOUCH_INT;
86
87// P1: P1_0 (CAM_RST), P1_1 (LCD_RST) → outputs; rest inputs
88const CONFIG_P1_VAL: u8 = !(P1_CAM_RST | P1_LCD_RST);
89
90#[derive(Debug, Error)]
91pub enum Aw9523bError {
92 #[error("I2C error: {0:?}")]
93 I2cError(#[from] esp_hal::i2c::master::Error),
94}
95
96pub struct Aw9523bDriver {
97 i2c: &'static SharedI2cBus,
98 address: u8,
99}
100
101pub struct Aw9523bResources {
102 pub i2c: &'static SharedI2cBus,
103}
104
105impl Aw9523bDriver {
106 pub fn new(res: Aw9523bResources) -> Self {
107 Self {
108 i2c: res.i2c,
109 address: ADDR,
110 }
111 }
112
113 async fn read_reg(&mut self, reg: u8) -> Result<u8, Aw9523bError> {
114 let mut buf = [0u8];
115 self.i2c
116 .lock()
117 .await
118 .write_read_async(self.address, &[reg], &mut buf)
119 .await?;
120 Ok(buf[0])
121 }
122
123 async fn write_reg(&mut self, reg: u8, value: u8) -> Result<(), Aw9523bError> {
124 self.i2c
125 .lock()
126 .await
127 .write_async(self.address, &[reg, value])
128 .await?;
129 Ok(())
130 }
131
132 /// Read-modify-write: set bit(s) in register.
133 async fn set_bits(&mut self, reg: u8, mask: u8) -> Result<(), Aw9523bError> {
134 let val = self.read_reg(reg).await?;
135 self.write_reg(reg, val | mask).await
136 }
137
138 /// Read-modify-write: clear bit(s) in register.
139 async fn clear_bits(&mut self, reg: u8, mask: u8) -> Result<(), Aw9523bError> {
140 let val = self.read_reg(reg).await?;
141 self.write_reg(reg, val & !mask).await
142 }
143
144 /// Let ONLY the touch line pull `INTN` low, and clear anything pending.
145 ///
146 /// `INTN` reaches the ESP32-S3 on GPIO21, so this is what makes a touch end
147 /// a deep sleep. Two halves, both needed:
148 ///
149 /// * **Mask everything else.** The mask defaults to all-enabled, so any
150 /// input pin changing would assert `INTN` and wake the board for
151 /// something that is not a touch.
152 /// * **Read both input ports.** `INTN` latches until an input register is
153 /// read. A sleep entered with it already asserted ends immediately —
154 /// esp-hal wakes on the *level*, not on the edge — which reads exactly
155 /// like a board that refuses to sleep.
156 ///
157 /// Call it immediately before sleeping, not at init: anything that touches
158 /// the panel in between re-asserts `INTN`.
159 pub async fn arm_touch_interrupt(&mut self) -> Result<(), Aw9523bError> {
160 self.write_reg(REG_INT_P0, INT_P0_ALL_MASKED).await?;
161 self.write_reg(REG_INT_P1, INT_P1_TOUCH_ONLY).await?;
162 self.read_reg(REG_INPUT_P0).await?;
163 self.read_reg(REG_INPUT_P1).await?;
164 Ok(())
165 }
166
167 /// Is the touch line asserted right now? (`P1_2` is active-LOW.)
168 ///
169 /// Reading the port also clears `INTN`, so this doubles as the "is the pad
170 /// at its wake level?" check a caller needs before sleeping.
171 pub async fn touch_asserted(&mut self) -> Result<bool, Aw9523bError> {
172 Ok(self.read_reg(REG_INPUT_P1).await? & P1_TOUCH_INT == 0)
173 }
174
175 /// Set LEDMODE to GPIO, configure P1 outputs, set up P0_0 (TOUCH_RST) via RMW.
176 pub async fn init(&mut self) -> Result<(), Aw9523bError> {
177 // P0: RMW — set TOUCH_RST latch HIGH before making it an output
178 self.set_bits(REG_OUTPUT_P0, P0_TOUCH_RST).await?;
179 self.set_bits(REG_LEDMODE_P0, P0_TOUCH_RST).await?; // GPIO mode for P0_0 only
180 self.clear_bits(REG_CONFIG_P0, P0_TOUCH_RST).await?; // P0_0 = output (0)
181 // P1: full writes (we own all P1 pins)
182 self.write_reg(REG_LEDMODE_P1, 0xFF).await?;
183 self.write_reg(REG_OUTPUT_P1, P1_CAM_RST | P1_LCD_RST)
184 .await?;
185 self.write_reg(REG_CONFIG_P1, CONFIG_P1_VAL).await?;
186 Ok(())
187 }
188
189 /// Pulse LCD_RST (P1_1) low for ≥10 µs, then wait 120 ms for ILI9342C stabilisation.
190 pub async fn lcd_rst_pulse(&mut self) -> Result<(), Aw9523bError> {
191 self.write_reg(REG_OUTPUT_P1, P1_CAM_RST).await?; // LCD_RST=0, CAM_RST=1
192 Timer::after(Duration::from_micros(10)).await;
193 self.write_reg(REG_OUTPUT_P1, P1_CAM_RST | P1_LCD_RST)
194 .await?;
195 Timer::after(Duration::from_millis(120)).await;
196 Ok(())
197 }
198
199 /// Enable the M-Bus / Grove **5 V output** that powers an attached M5GO
200 /// bottom's RGB LEDs on CoreS3 (their supply is the M-Bus 5 V rail, pin 28).
201 ///
202 /// Asserts both `BOOST_EN` (P1_7, the SY7088 boost) and `BUS_OUT_EN` (P0_1,
203 /// the load switch) **HIGH** — matching M5Unified's `setExtOutput(true)`.
204 ///
205 /// **CALLER GUARD:** M5Unified only enables this when a battery is present or
206 /// USB is absent — enabling the bus output with **no battery while on USB**
207 /// contends the shared VBUS rail. The caller must enforce that (see the
208 /// CoreS3 example). Drives the two pins as push-pull GPIO outputs, latched
209 /// high (RMW — other bits preserved).
210 pub async fn enable_bus_5v(&mut self) -> Result<(), Aw9523bError> {
211 // SY7088 boost (P1_7) high
212 self.set_bits(REG_LEDMODE_P1, P1_BOOST_EN).await?; // GPIO push-pull mode
213 self.set_bits(REG_OUTPUT_P1, P1_BOOST_EN).await?; // latch HIGH first
214 self.clear_bits(REG_CONFIG_P1, P1_BOOST_EN).await?; // then P1_7 = output
215 // Bus-output load switch (P0_1) high. Port 0 is OPEN-DRAIN by default and
216 // cannot drive high — put it in push-pull mode (GCR bit4) first, or P0_1
217 // latches high but floats and BUS_OUT_EN never asserts.
218 self.set_bits(REG_GCR, GCR_P0_PUSH_PULL).await?;
219 self.set_bits(REG_LEDMODE_P0, P0_BUS_OUT_EN).await?;
220 self.set_bits(REG_OUTPUT_P0, P0_BUS_OUT_EN).await?;
221 self.clear_bits(REG_CONFIG_P0, P0_BUS_OUT_EN).await?;
222 Ok(())
223 }
224
225 /// Pulse TOUCH_RST (P0_0) low for 5 ms, then wait 300 ms for FT6336U boot.
226 pub async fn touch_rst_pulse(&mut self) -> Result<(), Aw9523bError> {
227 self.clear_bits(REG_OUTPUT_P0, P0_TOUCH_RST).await?;
228 Timer::after(Duration::from_millis(5)).await;
229 self.set_bits(REG_OUTPUT_P0, P0_TOUCH_RST).await?;
230 Timer::after(Duration::from_millis(300)).await;
231 Ok(())
232 }
233}