st77916 0.1.1

A Rust driver for the ST77916 TFT-LCD display controller
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! # ST77916 Driver Crate
//!
//! An `embedded-graphics` compatible driver for the Sitronix ST77916 TFT-LCD
//! display controller (360x390, 262K color).
//!
//! The driver is generic over the communication interface and reset pin,
//! allowing it to work with SPI or any other bus by implementing
//! [`ControllerInterface`] and [`ResetInterface`].
//!
//! ## Buffering modes
//!
//! The builder defaults to an **unbuffered** instance. Three additional modes
//! are available when the `embedded-graphics` feature is enabled (default):
//!
//! | Mode | Type | RAM | `DrawTarget` | Flush |
//! |------|------|-----|-------------|-------|
//! | Unbuffered (default) | `St77916<I, R>` | 0 | No | `send_pixels()` |
//! | Unbuffered DrawTarget | `St77916<I, R, Unbuffered<C>>` | 0 | Yes (fallible) | Each draw -> HW |
//! | **Single-buffered** | `St77916<I, R, Buffered<C>>` | 1x FB | Yes (infallible) | `flush()` (dirty-aware) |
//! | **Double-buffered** | `St77916<I, R, DoubleBuffered<C>>` | 2x FB | Yes (infallible) | `swap_buffers()` + `flush_front()` |
//!
//! ## Single-buffered with dirty tracking
//!
//! The recommended mode for most applications. All `DrawTarget` operations
//! automatically track which rows were modified. [`flush()`](St77916::flush)
//! sends only the dirty band — a single contiguous slice with no allocation.
//! If nothing changed, `flush()` is a no-op.
//!
//! ```ignore
//! let mut display = St77916::builder(iface, reset, size)
//!     .with_init_commands(&PANEL_INIT)
//!     .buffered::<Rgb565>(Framebuffer::heap::<FB_SIZE>())
//!     .build(ColorMode::Rgb565, &mut delay)?;
//!
//! Circle::new(Point::new(100, 100), 50)
//!     .into_styled(PrimitiveStyle::with_fill(Rgb565::RED))
//!     .draw(&mut display)?;
//! display.flush()?;  // sends only the affected rows
//! ```
//!
//! ## Platform access
//!
//! [`interface_mut()`](St77916::interface_mut) exposes the underlying
//! [`ControllerInterface`] for platform-specific operations (e.g.
//! non-blocking DMA flush) that go beyond the trait's synchronous API.
//!
//! See [`commands`] for the full register set from the datasheet.

#![no_std]

extern crate alloc;

pub mod commands;

// -- embedded-graphics integration (single feature gate) --------------------
#[cfg(feature = "embedded-graphics")]
mod embedded_graphics;
#[cfg(feature = "embedded-graphics")]
pub use embedded_graphics::*;

use embedded_hal::delay::DelayNs;

// ---------------------------------------------------------------------------
// Display geometry
// ---------------------------------------------------------------------------

/// Display dimensions in pixels.
#[derive(Debug, Clone, Copy)]
pub struct DisplaySize {
    pub width: u16,
    pub height: u16,
}

impl DisplaySize {
    pub const fn new(width: u16, height: u16) -> Self {
        Self { width, height }
    }
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Driver errors, generic over interface and reset error types.
#[derive(Debug)]
pub enum DriverError<InterfaceError, ResetError> {
    InterfaceError(InterfaceError),
    ResetError(ResetError),
    InvalidConfiguration(&'static str),
}

/// Convenience alias for results from driver operations.
pub type DriverResult<T, IFACE, RST> =
    Result<T, DriverError<<IFACE as ControllerInterface>::Error, <RST as ResetInterface>::Error>>;

// ---------------------------------------------------------------------------
// Interface traits
// ---------------------------------------------------------------------------

/// Communication interface for the ST77916 (SPI, parallel, etc.).
pub trait ControllerInterface {
    type Error;

    /// Send a command byte with no data.
    fn send_command(&mut self, cmd: u8) -> Result<(), Self::Error>;

    /// Send a command byte followed by data parameters.
    fn send_command_with_data(&mut self, cmd: u8, data: &[u8]) -> Result<(), Self::Error>;

    /// Send pixel data to the display RAM.
    ///
    /// Called after `set_window()` has defined the target region via CASET/RASET.
    /// The implementation must send RAMWR (0x2C) for the first chunk and
    /// RAMWRC (0x3C) for subsequent chunks, handling any transport-level
    /// chunking (e.g. DMA size limits).
    fn send_pixels(&mut self, pixels: &[u8]) -> Result<(), Self::Error>;
}

/// Hardware reset control for the ST77916.
pub trait ResetInterface {
    type Error;

    /// Perform the hardware reset sequence.
    ///
    /// Per the ST77916 datasheet (Section 7.4.7, p.42):
    /// pull RESX low for >= 10us, then high, then wait >= 120ms before commands.
    fn reset(&mut self) -> Result<(), Self::Error>;
}

// ---------------------------------------------------------------------------
// Color mode
// ---------------------------------------------------------------------------

/// Pixel color format for the controller's COLMOD register.
pub enum ColorMode {
    /// 16-bit RGB565 (COLMOD 0x55)
    Rgb565,
    /// 18-bit RGB666 (COLMOD 0x66)
    Rgb666,
}

impl ColorMode {
    pub const fn bytes_per_pixel(&self) -> usize {
        match self {
            ColorMode::Rgb565 => 2,
            ColorMode::Rgb666 => 3,
        }
    }

    pub const fn colmod_param(&self) -> u8 {
        match self {
            ColorMode::Rgb565 => commands::COLMOD_RGB565,
            ColorMode::Rgb666 => commands::COLMOD_RGB666,
        }
    }
}

// ---------------------------------------------------------------------------
// Driver
// ---------------------------------------------------------------------------

/// Driver for the ST77916 TFT-LCD display controller.
///
/// Generic over:
/// - `IFACE`: communication interface ([`ControllerInterface`])
/// - `RST`: reset pin ([`ResetInterface`])
/// - `BUF`: buffer state — `()` for unbuffered (default), or a buffered
///   variant from the `embedded_graphics` module when the feature is enabled.
pub struct St77916<IFACE, RST, BUF = ()>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    pub(crate) interface: IFACE,
    pub(crate) reset: RST,
    pub(crate) config: DisplaySize,
    #[allow(dead_code)] // typestate parameter; read only by buffered variants
    pub(crate) buffer: BUF,
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Builder for [`St77916`].
///
/// Defaults to an unbuffered instance. With the `embedded-graphics` feature,
/// call `.buffered()`, `.double_buffered()`, or `.unbuffered()` before
/// `.build()` to opt into a `DrawTarget`-capable variant.
pub struct St77916Builder<IFACE, RST, BUF = ()>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    pub(crate) interface: IFACE,
    pub(crate) reset: RST,
    pub(crate) config: DisplaySize,
    pub(crate) init_commands: Option<&'static [(u8, &'static [u8], u16)]>,
    #[allow(dead_code)] // typestate parameter; read only by buffered variants
    pub(crate) buffer: BUF,
}

impl<IFACE, RST, BUF> St77916Builder<IFACE, RST, BUF>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Provide a custom init command sequence.
    ///
    /// Each entry is `(command, &data, delay_ms)`. The caller is responsible
    /// for the complete sequence including sleep-out, COLMOD, and display-on.
    pub fn with_init_commands(mut self, commands: &'static [(u8, &'static [u8], u16)]) -> Self {
        self.init_commands = Some(commands);
        self
    }
}

impl<IFACE, RST> St77916Builder<IFACE, RST, ()>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Build an unbuffered driver instance (no `DrawTarget`).
    pub fn build<DELAY>(
        self,
        color: ColorMode,
        delay: &mut DELAY,
    ) -> DriverResult<St77916<IFACE, RST>, IFACE, RST>
    where
        DELAY: DelayNs,
    {
        build_driver(
            self.interface,
            self.reset,
            self.config,
            self.init_commands,
            (),
            delay,
            color,
        )
    }
}

// ---------------------------------------------------------------------------
// Shared init helpers
// ---------------------------------------------------------------------------

/// Internal: construct + init a driver with any buffer type.
pub(crate) fn build_driver<IFACE, RST, BUF, DELAY>(
    interface: IFACE,
    reset: RST,
    config: DisplaySize,
    init_commands: Option<&[(u8, &[u8], u16)]>,
    buffer: BUF,
    delay: &mut DELAY,
    color: ColorMode,
) -> DriverResult<St77916<IFACE, RST, BUF>, IFACE, RST>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
    DELAY: DelayNs,
{
    let mut driver = St77916 {
        interface,
        reset,
        config,
        buffer,
    };
    driver.hard_reset()?;
    run_init(&mut driver.interface, init_commands, delay, color)
        .map_err(DriverError::InterfaceError)?;
    Ok(driver)
}

fn run_init<IFACE: ControllerInterface, DELAY: DelayNs>(
    interface: &mut IFACE,
    init_commands: Option<&[(u8, &[u8], u16)]>,
    delay: &mut DELAY,
    color: ColorMode,
) -> Result<(), IFACE::Error> {
    if let Some(cmds) = init_commands {
        for &(cmd, data, delay_ms) in cmds {
            if data.is_empty() {
                interface.send_command(cmd)?;
            } else {
                interface.send_command_with_data(cmd, data)?;
            }
            if delay_ms > 0 {
                delay.delay_ms(delay_ms as u32);
            }
        }
    } else {
        interface.send_command(commands::SWRESET)?;
        delay.delay_ms(120);
        interface.send_command(commands::SLPOUT)?;
        delay.delay_ms(120);
        interface.send_command_with_data(commands::COLMOD, &[color.colmod_param()])?;
        delay.delay_ms(5);
        interface.send_command_with_data(commands::MADCTL, &[0x00])?;
        interface.send_command(commands::INVON)?;
        interface.send_command(commands::DISPON)?;
        delay.delay_ms(20);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Methods available on ALL variants
// ---------------------------------------------------------------------------

impl<IFACE, RST> St77916<IFACE, RST>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Create a builder.
    ///
    /// ```ignore
    /// let display = St77916::builder(iface, reset, size)
    ///     .build(ColorMode::Rgb565, &mut delay)?;
    /// ```
    pub fn builder(
        interface: IFACE,
        reset: RST,
        config: DisplaySize,
    ) -> St77916Builder<IFACE, RST> {
        St77916Builder {
            interface,
            reset,
            config,
            init_commands: None,
            buffer: (),
        }
    }
}

impl<IFACE, RST, BUF> St77916<IFACE, RST, BUF>
where
    IFACE: ControllerInterface,
    RST: ResetInterface,
{
    /// Mutable access to the underlying communication interface.
    pub fn interface_mut(&mut self) -> &mut IFACE {
        &mut self.interface
    }

    /// Hardware reset via the [`ResetInterface`].
    pub fn hard_reset(&mut self) -> DriverResult<(), IFACE, RST> {
        self.reset.reset().map_err(DriverError::ResetError)
    }

    /// Send a command with no data.
    pub fn send_command(&mut self, cmd: u8) -> DriverResult<(), IFACE, RST> {
        self.interface
            .send_command(cmd)
            .map_err(DriverError::InterfaceError)
    }

    /// Send a command with data parameters.
    pub fn send_command_with_data(
        &mut self,
        cmd: u8,
        data: &[u8],
    ) -> DriverResult<(), IFACE, RST> {
        self.interface
            .send_command_with_data(cmd, data)
            .map_err(DriverError::InterfaceError)
    }

    /// Send pixel data to the display.
    pub fn send_pixels(&mut self, pixels: &[u8]) -> DriverResult<(), IFACE, RST> {
        self.interface
            .send_pixels(pixels)
            .map_err(DriverError::InterfaceError)
    }

    /// Set the active drawing window (CASET + RASET).
    pub fn set_window(
        &mut self,
        x_start: u16,
        y_start: u16,
        x_end: u16,
        y_end: u16,
    ) -> DriverResult<(), IFACE, RST> {
        self.send_command_with_data(
            commands::CASET,
            &[
                (x_start >> 8) as u8,
                (x_start & 0xFF) as u8,
                (x_end >> 8) as u8,
                (x_end & 0xFF) as u8,
            ],
        )?;
        self.send_command_with_data(
            commands::RASET,
            &[
                (y_start >> 8) as u8,
                (y_start & 0xFF) as u8,
                (y_end >> 8) as u8,
                (y_end & 0xFF) as u8,
            ],
        )
    }

    /// Convenience: set window to full display and send pixels.
    pub fn flush_pixels(&mut self, pixels: &[u8]) -> DriverResult<(), IFACE, RST> {
        self.set_window(0, 0, self.config.width - 1, self.config.height - 1)?;
        self.send_pixels(pixels)
    }

    /// Enter sleep mode.
    pub fn sleep_in<DELAY>(&mut self, delay: &mut DELAY) -> DriverResult<(), IFACE, RST>
    where
        DELAY: DelayNs,
    {
        self.send_command(commands::SLPIN)?;
        delay.delay_ms(5);
        Ok(())
    }

    /// Exit sleep mode.
    pub fn sleep_out<DELAY>(&mut self, delay: &mut DELAY) -> DriverResult<(), IFACE, RST>
    where
        DELAY: DelayNs,
    {
        self.send_command(commands::SLPOUT)?;
        delay.delay_ms(120);
        Ok(())
    }

    /// Turn display off.
    pub fn display_off(&mut self) -> DriverResult<(), IFACE, RST> {
        self.send_command(commands::DISPOFF)
    }

    /// Turn display on.
    pub fn display_on(&mut self) -> DriverResult<(), IFACE, RST> {
        self.send_command(commands::DISPON)
    }

    /// Set MADCTL (orientation, RGB/BGR order, scan direction).
    pub fn set_madctl(&mut self, value: u8) -> DriverResult<(), IFACE, RST> {
        self.send_command_with_data(commands::MADCTL, &[value])
    }

    /// Set display brightness (0x00-0xFF).
    pub fn set_brightness(&mut self, value: u8) -> DriverResult<(), IFACE, RST> {
        self.send_command_with_data(commands::WRDISBV, &[value])
    }

    /// Get the configured display size.
    pub fn size(&self) -> DisplaySize {
        self.config
    }
}