Skip to main content

m5stack_core/board/
display.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! ILI9342C panel bring-up shared by both boards (feature `display`).
3//!
4//! The M5Stack Fire27 and CoreS3 use the same 320x240 ILI9342C panel with the
5//! same controller options (inverted colors, BGR order); only the reset wiring
6//! differs — Fire27 has a GPIO reset pin, the CoreS3 panel is reset via the
7//! AW9523B expander (see [`super::cores3::power_display_reset`]) and
8//! falls back to lcd-async's SPI `SoftReset` ([`NoResetPin`]), which is
9//! harmless after the hardware pulse.
10//!
11//! Generic over the [`Interface`]: works with a plain shared `Spi` bus device
12//! (the examples) as well as a descriptor-backed `SpiDma` device
13//! ([`super::spi2`]).
14//!
15//! The panel is driven through [`M5Ili9342cRgb565`] rather than lcd-async's
16//! stock model, because the stock init leaves the gamma and power registers on
17//! their power-on defaults — see that type for what that costs on glass.
18//!
19//! # Writing an app against this panel
20//!
21//! Nothing is required of the caller for correct tone response: every route
22//! that produces a panel — [`init_ili9342c`], [`init_ili9342c_with_reset`], and
23//! both [`super::spi2`] paths on both boards — runs the same init, so a display
24//! obtained from this crate already has gamma programmed.
25//!
26//! What the init cannot do for you:
27//!
28//! - **A neutral grey needs `r == b` and `g == 2 * r`.** Green has one more bit
29//!   than red and blue in RGB565, so equal channel numbers are not neutral.
30//!   Converting an 8-bit token by truncation (`>>3`, `>>2`) breaks that
31//!   relation; at the dark end one LSB is a large relative step, so a value
32//!   meant as neutral can land with a visible cast.
33//! - **32 neutral steps is the RGB565 ceiling, not a gamma limit.** The panel is
34//!   262K-colour — 6 bits per channel, 64 neutral steps — and this crate drives
35//!   it at 5-6-5. Reaching the rest needs an 18-bit pipeline
36//!   (`lcd_async::models::ILI9342CRgb666`), which is a change here rather than
37//!   in an app.
38//! - **Do not software-reset the panel after bring-up.** Gamma lives in
39//!   controller registers, and `SWRESET` restores the power-on curve — silently
40//!   undoing this. Sleep and wake are safe: they send only `SLPIN`/`SLPOUT`.
41//!
42//! `examples/greyscale.rs` renders all 32 neutral greys as a labelled
43//! checkerboard for judging a panel by eye.
44
45use core::convert::Infallible;
46
47use embedded_graphics_core::pixelcolor::Rgb565;
48use embedded_hal::digital::OutputPin;
49use embedded_hal_async::delay::DelayNs;
50use lcd_async::{
51    Builder, Display, InitError, NoResetPin,
52    dcs::{InterfaceExt, SetAddressMode},
53    interface::Interface,
54    models::{ILI9342CRgb565, Model, ModelInitError},
55    options::{ColorInversion, ColorOrder, ModelOptions},
56};
57
58/// Panel resolution — the single per-target source in [`super`] (a board fact,
59/// not display-driver-specific); re-exported here for the display API.
60pub use super::{SCREEN_H, SCREEN_W};
61
62/// The gamma and power registers, byte-for-byte from M5GFX's
63/// `Panel_ILI9342::getInitCommands()` — the sequence M5Stack's own firmware
64/// programs into this panel.
65///
66/// Only the registers lcd-async leaves untouched are here. M5GFX additionally
67/// sends `0xB0` (RGB interface signal control), `0xF6` (interface control) and
68/// `0xB6` (display function control); those are deliberately omitted, because
69/// lcd-async has already configured the pixel path and scan setup by the time
70/// this runs and re-stating them risks contradicting it. `0xF6`'s payload is
71/// the reset default in any case.
72const GAMMA_AND_POWER: &[(u8, &[u8])] = &[
73    // Undocumented vendor unlock. The datasheet does not list 0xC8 at all, and
74    // the writes below are ignored until it has been sent — which is why M5GFX
75    // opens with it.
76    (0xC8, &[0xFF, 0x93, 0x42]),
77    (0xC0, &[0x12, 0x12]), // Power Control 1 — GVDD
78    (0xC1, &[0x03]),       // Power Control 2 — step-up factor
79    (0xC5, &[0xF2]),       // VCOM Control 1
80    (
81        0xE0,
82        &[
83            0x00, 0x0C, 0x11, 0x04, 0x11, 0x08, 0x37, 0x89, 0x4C, 0x06, 0x0C, 0x0A, 0x2E, 0x34,
84            0x0F,
85        ],
86    ), // Positive Gamma Correction
87    (
88        0xE1,
89        &[
90            0x00, 0x0B, 0x11, 0x05, 0x13, 0x09, 0x33, 0x67, 0x48, 0x07, 0x0E, 0x0B, 0x2E, 0x33,
91            0x0F,
92        ],
93    ), // Negative Gamma Correction
94];
95
96/// The ILI9342C driven the way M5Stack drives it: lcd-async's init sequence,
97/// then the gamma and power registers that sequence never programs.
98///
99/// lcd-async sends MADCTL, inversion, COLMOD, NORON, SLPOUT and DISPON and
100/// stops, so the controller keeps its power-on gamma curve. Measured on a
101/// Fire27, that lifts the dark end by roughly 8x — a framebuffer `(8, 8, 8)`
102/// reads as mid-grey instead of near-black, which makes the dark half of a
103/// palette unusable as designed (#97).
104///
105/// This delegates to the stock model rather than reimplementing it, so
106/// upstream stays authoritative for reset and the sleep-out timing that the
107/// datasheet pins to specific delays; only the missing writes are ours.
108///
109/// One deviation from M5GFX worth knowing: it programs these registers
110/// *before* sleep-out, whereas delegating necessarily programs them after the
111/// panel is already awake and on.
112pub struct M5Ili9342cRgb565(ILI9342CRgb565);
113
114impl Model for M5Ili9342cRgb565 {
115    type ColorFormat = Rgb565;
116    const FRAMEBUFFER_SIZE: (u16, u16) = ILI9342CRgb565::FRAMEBUFFER_SIZE;
117
118    async fn init<DELAY, DI>(
119        &mut self,
120        di: &mut DI,
121        delay: &mut DELAY,
122        options: &ModelOptions,
123    ) -> Result<SetAddressMode, ModelInitError<DI::Error>>
124    where
125        DELAY: DelayNs,
126        DI: Interface,
127    {
128        let madctl = self.0.init(di, delay, options).await?;
129        for (cmd, data) in GAMMA_AND_POWER {
130            di.write_raw(*cmd, data).await?;
131        }
132        Ok(madctl)
133    }
134}
135
136/// The configured panel type: ILI9342C in RGB565 over `DI`.
137pub type Ili9342c<DI, RST = NoResetPin> = Display<DI, M5Ili9342cRgb565, RST>;
138
139fn builder<DI: Interface>(di: DI) -> Builder<DI, M5Ili9342cRgb565, NoResetPin> {
140    Builder::new(M5Ili9342cRgb565(ILI9342CRgb565), di)
141        .invert_colors(ColorInversion::Inverted)
142        .color_order(ColorOrder::Bgr)
143        .display_size(SCREEN_W, SCREEN_H)
144}
145
146/// Initialise the panel without a reset pin (CoreS3). The hardware reset must
147/// have been pulsed beforehand (AW9523B `LCD_RST`); init falls back to a SPI
148/// `SoftReset` command.
149pub async fn init_ili9342c<DI: Interface>(
150    di: DI,
151) -> Result<Ili9342c<DI>, InitError<DI::Error, Infallible>> {
152    let mut delay = embassy_time::Delay;
153    builder(di).init(&mut delay).await
154}
155
156/// Initialise the panel with a hardware reset pin (Fire27, RST=GPIO33).
157pub async fn init_ili9342c_with_reset<DI: Interface, RST: OutputPin>(
158    di: DI,
159    rst: RST,
160) -> Result<Ili9342c<DI, RST>, InitError<DI::Error, RST::Error>> {
161    let mut delay = embassy_time::Delay;
162    builder(di).reset_pin(rst).init(&mut delay).await
163}