Skip to main content

rm690b0_rs/
lib.rs

1//! # RM690B0 Driver Crate
2//!
3//! An embedded-graphics compatible driver for the RM690B0 display controller IC.
4//!
5//! This driver is not embedded-hal compatible, but provides a generic interface
6//! for controlling the RM690B0 display controller.
7//! Different displays can be supported by implementing the `ControllerInterface` and `ResetInterface` traits.
8//! This is because the RM690B0 is used in displays with various interfaces such as SPI or QSPI.
9//! Additionally, the reset pin is controlled via GPIO or I2C GPIO expander.
10//!
11//! The driver currently supports the Lilygo T4-S3 AMOLED display out of the box, but can be extended to support other displays.
12//!
13//! ## Usage
14//! 1. Implement the `ControllerInterface` trait for the controller driving interface Ex. QSPI
15//! 2. Implement the `ResetInterface` trait for the Reset pin.
16//! 3. Create a `Rm690b0Driver` instance with the display interface and reset pin.
17//! 4. Use the driver to draw using `embedded-graphics`.
18//!
19//! If you are going to use heap allocated framebuffer, you will need to make sure that an allocator is available in your environment.
20//! In some crates this is done by enabling the `alloc` feature.
21//!
22//! ## Feature Flags
23#![doc = document_features::document_features!()]
24//!
25//! ## Examples
26//! See the `examples` directory for a usage example with the Lilygo T4-S3 Display.
27//!
28//! The Lilygo T4-S3 Display controls the RM690B0 via an ESP32-S3 over QSPI and uses GPIO output to control the reset pin.
29//! The example implementation uses a PSRAM heap allocated framebuffer and DMA for efficient transfers.
30//!
31//! The schematic is available here: <https://github.com/Xinyuan-LilyGO/LilyGo-AMOLED-Series/blob/master/schematic/T4-S3-240719.pdf>
32//!
33//! To run the example, with the Lilygo T4-S3 Display, clone the project and run following command from the project root:
34//! ```bash
35//! cargo run --example lilygo_t4_s3 --features "lilygo_t4_s3 --release"
36//! ```
37//!
38
39#![no_std]
40#[cfg(feature = "lilygo_t4_s3")]
41pub mod displays;
42
43#[cfg(feature = "lilygo_t4_s3")]
44pub use displays::lilygo_t4_s3::*;
45
46extern crate alloc;
47
48mod graphics_core;
49
50use alloc::boxed::Box;
51use embedded_graphics::prelude::PixelColor;
52use embedded_graphics_core::draw_target::DrawTarget;
53use embedded_hal::delay::DelayNs;
54
55/// Configuration for the display dimensions.
56#[derive(Debug, Clone, Copy)]
57pub struct DisplaySize {
58    /// Display width in pixels.
59    pub width: u16,
60    /// Display height in pixels.
61    pub height: u16,
62}
63
64impl DisplaySize {
65    /// Creates a new display size in pixels.
66    pub const fn new(width: u16, height: u16) -> Self {
67        DisplaySize { width, height }
68    }
69}
70
71/// RM690B0 Driver Errors
72#[derive(Debug)]
73pub enum DriverError<InterfaceError, ResetError> {
74    /// Error originating from the display interface (QSPI/SPI/I2C).
75    InterfaceError(InterfaceError),
76    /// Error originating from the reset pin control.
77    ResetError(ResetError),
78    /// Invalid configuration provided to the driver.
79    InvalidConfiguration(&'static str),
80}
81
82/// Trait to implement the controller communication interface (QSPI, SPI, etc.).
83pub trait ControllerInterface {
84    /// The specific error type for this interface implementation.
85    type Error;
86
87    /// Sends a command byte to the display.
88    fn send_command(&mut self, cmd: u8) -> Result<(), Self::Error>;
89
90    /// Sends data bytes to the display following a command.
91    fn send_command_with_data(&mut self, cmd: u8, data: &[u8]) -> Result<(), Self::Error>;
92
93    /// Sends pixel data
94    fn send_pixels(&mut self, pixels: &[u8]) -> Result<(), Self::Error>;
95
96    /// Starts a pixel write transaction for an already configured display window.
97    fn send_pixels_start(&mut self, pixels: &[u8]) -> Result<(), Self::Error> {
98        self.send_pixels(pixels)
99    }
100
101    /// Continues a pixel write transaction for an already configured display window.
102    fn send_pixels_continue(&mut self, pixels: &[u8]) -> Result<(), Self::Error> {
103        self.send_pixels(pixels)
104    }
105}
106
107/// Trait for controlling the hardware reset pin.
108pub trait ResetInterface {
109    /// The specific error type for this reset implementation.
110    type Error;
111
112    /// Performs the hardware reset sequence according to the datasheet definition.
113    fn reset(&mut self) -> Result<(), Self::Error>;
114}
115
116/// RM690B0 Command Set
117pub mod commands {
118    pub const NOP: u8 = 0x00;
119    pub const SWRESET: u8 = 0x01;
120    pub const RDDID: u8 = 0x04; // Read Display Identification Information
121    pub const RDNUMED: u8 = 0x05; // Read Number of Errors on DSI
122    pub const RDDPM: u8 = 0x0A; // Read Display Power Mode
123    pub const RDDMADCTR: u8 = 0x0B; // Read Display MADCTR
124    pub const RDDCOLMOD: u8 = 0x0C; // Read Display Pixel Format
125    pub const RDDIM: u8 = 0x0D; // Read Display Image Mode
126    pub const RDDSM: u8 = 0x0E; // Read Display Signal Mode
127    pub const RDDSDR: u8 = 0x0F; // Read Display Self-Diagnostic Result
128    pub const SLPIN: u8 = 0x10;
129    pub const SLPOUT: u8 = 0x11;
130    pub const PTLON: u8 = 0x12; // Partial Display Mode On
131    pub const NORON: u8 = 0x13; // Normal Display Mode On
132    pub const INVOFF: u8 = 0x20; // Display Inversion Off
133    pub const INVON: u8 = 0x21; // Display Inversion On
134    pub const ALLPOFF: u8 = 0x22; // All Pixel Off
135    pub const ALLPON: u8 = 0x23; // All Pixel On
136    pub const DISPOFF: u8 = 0x28;
137    pub const DISPON: u8 = 0x29;
138    pub const CASET: u8 = 0x2A; // Column Address Set
139    pub const RASET: u8 = 0x2B; // Row Address Set
140    pub const RAMWR: u8 = 0x2C; // Memory Write
141    pub const PTLAR: u8 = 0x30; // Partial Area
142    pub const TEOFF: u8 = 0x34; // Tearing Effect Off
143    pub const TEON: u8 = 0x35; // Tearing Effect On
144    pub const MADCTR: u8 = 0x36; // Memory Data Access Control
145    pub const IDMOFF: u8 = 0x38; // Idle Mode Off
146    pub const IDMON: u8 = 0x39; // Idle Mode On
147    pub const COLMOD: u8 = 0x3A; // Interface Pixel Format
148    pub const RAMWRC: u8 = 0x3C; // Memory Continuous Write
149    pub const STESL: u8 = 0x44; // Set Tear Scan Line
150    pub const GSL: u8 = 0x45; // Get Scan Line
151    pub const DSTBON: u8 = 0x4F; // Deep Standby Mode On
152    pub const WRDISBV: u8 = 0x51; // Write Display Brightness
153    pub const RDDISBV: u8 = 0x52; // Read Display Brightness
154    pub const WRCTRLD: u8 = 0x53; // Write CTRL Display
155    pub const RDCTRLD: u8 = 0x54; // Read CTRL Display
156    pub const WRRADACL: u8 = 0x55; // RAD_ACL Control
157    pub const COLORTEMP: u8 = 0x55; // Color Temperature Selection (shared with WRRADACL)
158    pub const WRHBM: u8 = 0x63; // Write HBM Display Brightness
159    pub const RDHBM: u8 = 0x64; // Read HBM Display Brightness
160    pub const HBM_MODE: u8 = 0x66; // Set HBM Mode
161    pub const FR_LEVEL: u8 = 0x67; // Frame Rate Level Control
162    pub const COLSET: u8 = 0x70; // Interface Pixel Format Set
163    pub const COLOPT: u8 = 0x80; // Interface Pixel Format Option
164    pub const RDDDBS: u8 = 0xA1; // Read DDB Start
165    pub const RDDDBC: u8 = 0xA8; // Read DDB Continuous
166    pub const RDFCS: u8 = 0xAA; // Read First Checksum
167    pub const RDCCS: u8 = 0xAF; // Read Continue Checksum
168}
169
170/// Color modes supported by the RM690B0 display controller.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum ColorMode {
173    /// 16-bit RGB565 format
174    Rgb565,
175    /// 24-bit RGB888 format
176    Rgb888,
177    /// 18-bit RGB666 format
178    Rgb666,
179    /// 8-bit 256 Gray
180    Gray8,
181}
182
183impl ColorMode {
184    /// Returns the number of bytes per pixel for the color format.
185    pub const fn bytes_per_pixel(&self) -> usize {
186        match self {
187            ColorMode::Rgb565 => 2,
188            ColorMode::Rgb888 => 3,
189            ColorMode::Rgb666 => 3,
190            ColorMode::Gray8 => 1,
191        }
192    }
193}
194
195/// Computes the framebuffer size (in bytes) for a given display and color mode.
196pub const fn framebuffer_size(display: DisplaySize, color: ColorMode) -> usize {
197    (display.width as usize) * (display.height as usize) * color.bytes_per_pixel()
198}
199
200/// Framebuffer enum to hold either a static array or a boxed array
201pub enum Framebuffer {
202    Static(&'static mut [u8]),
203    Heap(Box<[u8]>),
204}
205
206impl Framebuffer {
207    /// Returns a mutable view of the raw framebuffer bytes.
208    pub fn as_mut_slice(&mut self) -> &mut [u8] {
209        match self {
210            Framebuffer::Static(ref mut arr) => arr,
211            Framebuffer::Heap(ref mut boxed) => boxed,
212        }
213    }
214
215    /// Returns an immutable view of the raw framebuffer bytes.
216    pub fn as_slice(&self) -> &[u8] {
217        match self {
218            Framebuffer::Static(ref arr) => arr,
219            Framebuffer::Heap(ref boxed) => boxed,
220        }
221    }
222
223    /// Returns the framebuffer length in bytes.
224    pub fn len(&self) -> usize {
225        self.as_slice().len()
226    }
227}
228
229impl core::ops::Deref for Framebuffer {
230    type Target = [u8];
231    fn deref(&self) -> &Self::Target {
232        match self {
233            Framebuffer::Static(arr) => arr,
234            Framebuffer::Heap(boxed) => boxed,
235        }
236    }
237}
238
239impl core::ops::DerefMut for Framebuffer {
240    fn deref_mut(&mut self) -> &mut Self::Target {
241        match self {
242            Framebuffer::Static(arr) => arr,
243            Framebuffer::Heap(boxed) => boxed,
244        }
245    }
246}
247
248/// Main Driver for the RM690B0 display controller.
249pub struct Rm690b0Driver<IFACE, RST, C>
250where
251    IFACE: ControllerInterface,
252    RST: ResetInterface,
253    C: PixelColor,
254{
255    interface: IFACE,
256    reset: RST,
257    framebuffer: Framebuffer,
258    config: DisplaySize,
259    color_mode: ColorMode,
260    _color: core::marker::PhantomData<C>,
261}
262
263impl<IFACE, RST, C> Rm690b0Driver<IFACE, RST, C>
264where
265    IFACE: ControllerInterface,
266    RST: ResetInterface,
267    C: PixelColor,
268{
269    /// Creates a new driver instance with static array and initializes the display.
270    pub fn new_static<DELAY, const N: usize>(
271        interface: IFACE,
272        reset: RST,
273        colormode: ColorMode,
274        config: DisplaySize,
275        mut delay: DELAY,
276        framebuffer: &'static mut [u8; N],
277    ) -> Result<Self, DriverError<IFACE::Error, RST::Error>>
278    where
279        DELAY: DelayNs,
280    {
281        let expected_fb_size = framebuffer_size(config, colormode);
282        if N != expected_fb_size {
283            return Err(DriverError::InvalidConfiguration(
284                "Framebuffer size does not match display size and color mode",
285            ));
286        }
287
288        let mut driver = Self {
289            interface,
290            reset,
291            framebuffer: Framebuffer::Static(&mut framebuffer[..]),
292            config,
293            color_mode: colormode,
294            _color: core::marker::PhantomData,
295        };
296        driver.hard_reset()?;
297        driver.initialize_display(&mut delay, colormode)?;
298        Ok(driver)
299    }
300
301    /// Creates a new driver instance with a boxed array framebuffer.
302    pub fn new_heap<DELAY, const N: usize>(
303        interface: IFACE,
304        reset: RST,
305        color: ColorMode,
306        config: DisplaySize,
307        mut delay: DELAY,
308    ) -> Result<Self, DriverError<IFACE::Error, RST::Error>>
309    where
310        DELAY: DelayNs,
311    {
312        let expected_fb_size = framebuffer_size(config, color);
313        if N != expected_fb_size {
314            return Err(DriverError::InvalidConfiguration(
315                "Framebuffer size does not match display size and color mode",
316            ));
317        }
318
319        let mut driver = Self {
320            interface,
321            reset,
322            framebuffer: Framebuffer::Heap(Box::new([0u8; N])),
323            config,
324            color_mode: color,
325            _color: core::marker::PhantomData,
326        };
327        driver.hard_reset()?;
328        driver.initialize_display(&mut delay, color)?;
329        Ok(driver)
330    }
331
332    /// Performs a hardware reset using the provided `ResetPin` implementation.
333    pub fn hard_reset(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
334        self.reset.reset().map_err(DriverError::ResetError)?;
335        Ok(())
336    }
337
338    /// Sends the essential initialization command sequence to the display.
339    pub fn initialize_display<DELAY>(
340        &mut self,
341        delay: &mut DELAY,
342        color: ColorMode,
343    ) -> Result<(), DriverError<IFACE::Error, RST::Error>>
344    where
345        DELAY: DelayNs,
346    {
347        self.send_command(commands::SLPOUT)?;
348        delay.delay_ms(120);
349
350        self.send_command_with_data(commands::MADCTR, &[0x00])?;
351
352        // Manufacturer-Specific Initialization
353        self.send_command_with_data(0xFE, &[0x20])?;
354        self.send_command_with_data(0x26, &[0x0A])?;
355        self.send_command_with_data(0x24, &[0x80])?;
356        self.send_command_with_data(0x5A, &[0x51])?;
357        self.send_command_with_data(0x5B, &[0x2E])?;
358        self.send_command_with_data(0xFE, &[0x00])?;
359
360        // Sets Interface Pixel Format to 24-bit/pixel (RGB888)
361        match color {
362            ColorMode::Rgb565 => {
363                // Set pixel format to RGB565
364                self.send_command_with_data(commands::COLMOD, &[0x55])?;
365            }
366            ColorMode::Rgb888 => {
367                // Set pixel format to RGB888
368                self.send_command_with_data(commands::COLMOD, &[0x77])?;
369            }
370            ColorMode::Rgb666 => {
371                // Set pixel format to RGB666
372                self.send_command_with_data(commands::COLMOD, &[0x66])?;
373            }
374            ColorMode::Gray8 => {
375                // Set pixel format to 8-bit grayscale
376                self.send_command_with_data(commands::COLMOD, &[0x11])?;
377            }
378        }
379
380        self.send_command_with_data(commands::TEON, &[0x00])?;
381
382        self.send_command(commands::DISPON)?;
383        delay.delay_ms(20);
384
385        // Display Brightness Set to Maximum
386        self.send_command_with_data(commands::WRDISBV, &[0xFF])?;
387
388        Ok(())
389    }
390
391    /// Send a command with no data
392    fn send_command(&mut self, cmd: u8) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
393        self.interface
394            .send_command(cmd)
395            .map_err(DriverError::InterfaceError)
396    }
397
398    /// Helper to send a command with associated data parameters
399    fn send_command_with_data(
400        &mut self,
401        cmd: u8,
402        data: &[u8],
403    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
404        self.interface
405            .send_command_with_data(cmd, data)
406            .map_err(DriverError::InterfaceError)?;
407        Ok(())
408    }
409
410    /// Sleep Mode In (SLPIN)
411    pub fn sleep_in<DELAY>(
412        &mut self,
413        delay: &mut DELAY,
414    ) -> Result<(), DriverError<IFACE::Error, RST::Error>>
415    where
416        DELAY: DelayNs,
417    {
418        self.send_command(commands::SLPIN)?;
419        delay.delay_ms(5);
420        Ok(())
421    }
422
423    /// Sleep Out (SLPOUT)
424    pub fn sleep_out<DELAY>(
425        &mut self,
426        delay: &mut DELAY,
427    ) -> Result<(), DriverError<IFACE::Error, RST::Error>>
428    where
429        DELAY: DelayNs,
430    {
431        self.send_command(commands::SLPOUT)?;
432        delay.delay_ms(5);
433        Ok(())
434    }
435
436    /// Turns the display panel off
437    pub fn display_off(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
438        self.send_command(commands::DISPOFF)
439    }
440
441    /// Turns the display panel on
442    pub fn display_on(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
443        self.send_command(commands::DISPON)
444    }
445
446    /// Sets the active drawing window on the display RAM.
447    pub fn set_window(
448        &mut self,
449        x_start: u16,
450        y_start: u16,
451        x_end: u16,
452        y_end: u16,
453    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
454        let width = x_end.saturating_sub(x_start).saturating_add(1);
455        let height = y_end.saturating_sub(y_start).saturating_add(1);
456
457        if x_start % 2 != 0 || width % 2 != 0 {
458            return Err(DriverError::InvalidConfiguration(
459                "x_start and width must both be even",
460            ));
461        }
462        if y_start % 2 != 0 || height % 2 != 0 {
463            return Err(DriverError::InvalidConfiguration(
464                "y_start and height must both be even",
465            ));
466        }
467        if x_end < x_start
468            || y_end < y_start
469            || x_end >= self.config.width
470            || y_end >= self.config.height
471        {
472            return Err(DriverError::InvalidConfiguration(
473                "Invalid window dimensions",
474            ));
475        }
476
477        // CASET
478        self.send_command_with_data(
479            commands::CASET,
480            &[
481                (x_start >> 8) as u8,
482                (x_start & 0xFF) as u8,
483                (x_end >> 8) as u8,
484                (x_end & 0xFF) as u8,
485            ],
486        )?;
487
488        // RASET
489        self.send_command_with_data(
490            commands::RASET,
491            &[
492                (y_start >> 8) as u8,
493                (y_start & 0xFF) as u8,
494                (y_end >> 8) as u8,
495                (y_end & 0xFF) as u8,
496            ],
497        )?;
498        Ok(())
499    }
500
501    /// Sets the Memory Data Access Control (MADCTR) register.
502    pub fn set_madctr(&mut self, value: u8) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
503        self.send_command_with_data(commands::MADCTR, &[value])
504    }
505
506    /// Sets the display brightness (0x00 - 0xFF for RM690B0).
507    pub fn set_brightness(
508        &mut self,
509        value: u8,
510    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
511        self.send_command_with_data(commands::WRDISBV, &[value])
512    }
513
514    /// Writes the contents of the framebuffer to the display RAM.
515    pub fn flush(&mut self) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
516        // Set window to full display
517        self.set_window(0, 0, self.config.width - 1, self.config.height - 1)?;
518        self.interface
519            .send_pixels(&self.framebuffer)
520            .map_err(DriverError::InterfaceError)?;
521        Ok(())
522    }
523
524    /// Flushes a rectangular region from the framebuffer to display RAM.
525    ///
526    /// The region bounds are inclusive and must satisfy the alignment
527    /// constraints enforced by [`Self::set_window`].
528    pub fn partial_flush(
529        &mut self,
530        x_start: u16,
531        x_end: u16,
532        y_start: u16,
533        y_end: u16,
534    ) -> Result<(), DriverError<IFACE::Error, RST::Error>> {
535        self.set_window(x_start, y_start, x_end, y_end)?;
536        let bytes_per_pixel = self.color_mode.bytes_per_pixel();
537        let fb_width = self.config.width as usize * bytes_per_pixel;
538        let width = (x_end - x_start + 1) as usize;
539        let height = (y_end - y_start + 1) as usize;
540        for y in 0..height {
541            let offset = (y_start as usize + y) * fb_width + (x_start as usize * bytes_per_pixel);
542            let row_end = offset + (width * bytes_per_pixel);
543            if offset >= self.framebuffer.len() || row_end > self.framebuffer.len() {
544                return Err(DriverError::InvalidConfiguration(
545                    "Framebuffer slice out of bounds",
546                ));
547            }
548
549            let row = &self.framebuffer[offset..row_end];
550            if y == 0 {
551                self.interface
552                    .send_pixels_start(row)
553                    .map_err(DriverError::InterfaceError)?;
554            } else {
555                self.interface
556                    .send_pixels_continue(row)
557                    .map_err(DriverError::InterfaceError)?;
558            }
559        }
560        Ok(())
561    }
562}