Skip to main content

core_s3/
sd.rs

1//! TF/microSD card metadata and helpers for CoreS3.
2//!
3//! CoreS3 routes the TF card over the same SPI signal group used by the LCD:
4//! SCLK GPIO36, MOSI/COPI GPIO37, MISO/CIPO GPIO35, and CS GPIO4. Applications
5//! that need both display and SD access should coordinate ownership of this
6//! shared bus at the HAL layer. The card-detect switch is exposed through
7//! AW9523B port 0 bit 4 and is active-low, matching the official M5Stack demo.
8
9use crate::pins::SpiSdPins;
10
11/// Default SPI clock used by M5Stack's CoreS3 SD demo.
12pub const DEFAULT_SPI_HZ: u32 = 25_000_000;
13/// AW9523B port-0 bit used for TF card detect.
14pub const CARD_DETECT_P0_BIT: u8 = 4;
15
16/// Static CoreS3 TF-card wiring and bus settings.
17#[cfg_attr(feature = "defmt", derive(defmt::Format))]
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub struct SdCardSlot {
20    /// SPI pins for the TF card socket.
21    pub spi: SpiSdPins,
22    /// Recommended maximum SPI clock for initialization/use.
23    pub spi_hz: u32,
24    /// Card-detect signal exposed through AW9523B input port 0.
25    pub detect: SdCardDetect,
26}
27
28impl SdCardSlot {
29    /// CoreS3 onboard TF-card slot.
30    pub const CORE_S3: Self = Self {
31        spi: SpiSdPins::TF_CARD,
32        spi_hz: DEFAULT_SPI_HZ,
33        detect: SdCardDetect::AW9523B_P0_4_ACTIVE_LOW,
34    };
35}
36
37/// Card-detect wiring description.
38#[cfg_attr(feature = "defmt", derive(defmt::Format))]
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub struct SdCardDetect {
41    /// AW9523B input port number.
42    pub port: u8,
43    /// Bit in the input port.
44    pub bit: u8,
45    /// Whether a low level means card-present.
46    pub active_low: bool,
47}
48
49impl SdCardDetect {
50    /// CoreS3 TF card detect: AW9523B port 0 bit 4, active-low.
51    pub const AW9523B_P0_4_ACTIVE_LOW: Self = Self {
52        port: 0,
53        bit: CARD_DETECT_P0_BIT,
54        active_low: true,
55    };
56
57    /// Interpret a raw AW9523B input-port value.
58    pub const fn present_from_port_value(self, value: u8) -> bool {
59        let high = (value & (1 << self.bit)) != 0;
60        if self.active_low { !high } else { high }
61    }
62}
63
64/// Interpret CoreS3's raw AW9523B P0 input byte as TF-card presence.
65pub const fn core_s3_card_present_from_aw9523_p0(value: u8) -> bool {
66    SdCardDetect::AW9523B_P0_4_ACTIVE_LOW.present_from_port_value(value)
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn card_detect_is_active_low_on_p0_bit4() {
75        assert!(core_s3_card_present_from_aw9523_p0(0b1110_1111));
76        assert!(!core_s3_card_present_from_aw9523_p0(0b0001_0000));
77    }
78}