ht1621b 0.2.0

Platform-agnostic embedded-hal driver for the HT1621B LCD controller (3-wire bit-bang)
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Platform-agnostic driver for the **HT1621B** LCD controller.
//!
//! The HT1621B is driven over a custom 3‑ or 4‑wire serial interface (not
//! SPI):
//! - **CS**: active-low chip select, frames each transaction
//! - **WR**: write clock, data latched on the rising edge
//! - **RD**: read clock (only needed for read / read‑modify‑write)
//! - **DA**: bidirectional data line
//!
//! Each transaction is framed by CS↓ … CS↑.  Within a frame the first 3 bits
//! select the mode:
//!
//! | ID   | Mode                | Payload                            |
//! |------|---------------------|------------------------------------|
//! | 100  | Command             | 8-bit command + 1 don't-care bit   |
//! | 101  | Write / Read‑Modify‑Write | 6-bit addr + N × 4-bit data   |
//! | 110  | Read RAM            | 6-bit addr + N × 4-bit data (read) |
//!
//! RAM is 32 × 4 bits (128 segments).  The address auto-increments after each
//! nibble in write/read mode, allowing continuous burst transfer.  Command
//! bits and the RAM address are sent MSB-first; RAM data nibbles are sent
//! LSB-first (D0→D3) per the datasheet.
//!
//! # Layers
//!
//! | Struct | Pins | Capabilities |
//! |--------|------|--------------|
//! | [`Ht1621bBus`] + [`Ht1621b`] | CS, WR, DA | Write commands + RAM data |
//! | `Ht1621bBusRW` + `Ht1621bRW` | CS, WR, **RD**, DA | Write + read + read‑modify‑write |
//!
//! The read / read‑modify‑write layer (`Ht1621bBusRW` / `Ht1621bRW`) is gated
//! behind the **`read`** feature, which also pulls in `embedded-flex-pin` for
//! the bidirectional DA pin.
//!
//! Both are generic over [`embedded_hal::digital::OutputPin`] /
//! `FlexPin` and
//! [`embedded_hal::delay::DelayNs`], so the driver works with any
//! `embedded-hal` 1.0 implementation.
//!
//! # Example
//!
//! ```ignore
//! use ht1621b::{Config, Ht1621b};
//!
//! // `cs`, `wr`, `da`: OutputPin; `delay`: DelayNs; `async_delay`: async DelayNs
//! let mut lcd = Ht1621b::new(cs, wr, da, delay, &mut async_delay, Config::default()).await;
//! lcd.write_byte(arbitrary_int::u6::new(0x00), 0xEF); // display a digit
//! ```

#![no_std]

use arbitrary_int::{u4, u6};
use derive_setters::Setters;
#[cfg(feature = "read")]
use embedded_flex_pin::FlexPin;
use embedded_hal::delay::DelayNs;
use embedded_hal::digital::OutputPin;

mod bus;
pub use bus::Ht1621bBus;
#[cfg(feature = "read")]
pub use bus::Ht1621bBusRW;
#[cfg(feature = "read")]
use bus::Ht1621bBusRead;
use bus::Ht1621bBusWrite;

/// Raw 8-bit command codes.
///
/// The `write_command` bus method prepends the 3-bit ID (100) and appends the
/// don't-care fill bit X (=0), forming the full 12-bit frame: `100` + C7–C0
/// + `X`.  All don't-care bits (X) are filled with 0.
pub mod cmd {
    // System / display control
    pub const SYS_DIS: u8 = 0x00; // 0000_0000  osc + LCD bias off
    pub const SYS_EN: u8 = 0x01; // 0000_0001  system oscillator on
    pub const LCD_OFF: u8 = 0x02; // 0000_0010  LCD bias off
    pub const LCD_ON: u8 = 0x03; // 0000_0011  LCD bias on

    // Time base / WDT enable
    pub const TIMER_DIS: u8 = 0x04; // 0000_0100
    pub const WDT_DIS: u8 = 0x05; // 0000_0101
    pub const TIMER_EN: u8 = 0x06; // 0000_0110
    pub const WDT_EN: u8 = 0x07; // 0000_0111

    // Tone enable
    pub const TONE_OFF: u8 = 0x08; // 0000_1000
    pub const TONE_ON: u8 = 0x09; // 0000_1001

    // Clear
    pub const CLR_TIMER: u8 = 0x0C; // 0000_11XX
    pub const CLR_WDT: u8 = 0x0E; // 0000_111X

    // System clock source
    pub const XTAL_32K: u8 = 0x14; // 0001_01XX
    pub const RC_256K: u8 = 0x18; // 0001_10XX
    pub const EXT_256K: u8 = 0x1C; // 0001_11XX

    // LCD bias / COM  (0010_abX?, ab: 00=2COM 01=3COM 10=4COM)
    pub const BIAS_1_2_2COM: u8 = 0x20; // 0010_0000
    pub const BIAS_1_2_3COM: u8 = 0x24; // 0010_0100
    pub const BIAS_1_2_4COM: u8 = 0x28; // 0010_1000
    pub const BIAS_1_3_2COM: u8 = 0x21; // 0010_0001
    pub const BIAS_1_3_3COM: u8 = 0x25; // 0010_0101
    pub const BIAS_1_3_4COM: u8 = 0x29; // 0010_1001

    // Tone frequency
    pub const TONE_4K: u8 = 0x40; // 010X_XXXX
    pub const TONE_2K: u8 = 0x60; // 011X_XXXX

    // IRQ enable
    pub const IRQ_DIS: u8 = 0x80; // 100X_0XXX
    pub const IRQ_EN: u8 = 0x88; // 100X_1XXX

    // Time base / WDT clock output frequency
    pub const F1: u8 = 0xA0; // 101X_X000
    pub const F2: u8 = 0xA1; // 101X_X001
    pub const F4: u8 = 0xA2; // 101X_X010
    pub const F8: u8 = 0xA3; // 101X_X011
    pub const F16: u8 = 0xA4; // 101X_X100
    pub const F32: u8 = 0xA5; // 101X_X101
    pub const F64: u8 = 0xA6; // 101X_X110
    pub const F128: u8 = 0xA7; // 101X_X111

    // Test mode
    pub const TEST: u8 = 0xE0; // 1110_0000
    pub const NORMAL: u8 = 0xE3; // 1110_0011
}

/// LCD bias level.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Bias {
    /// 1/2 bias.
    Half,
    /// 1/3 bias.
    Third,
}

/// Number of COM (backplane) lines driven.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Commons {
    Two,
    Three,
    Four,
}

/// System clock source.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ClockSource {
    /// On-chip RC oscillator, 256 kHz.
    Rc256k,
    /// External 32.768 kHz crystal.
    Xtal32k,
    /// External 256 kHz clock.
    Ext256k,
}

impl ClockSource {
    #[inline]
    fn command(self) -> u8 {
        match self {
            ClockSource::Rc256k => cmd::RC_256K,
            ClockSource::Xtal32k => cmd::XTAL_32K,
            ClockSource::Ext256k => cmd::EXT_256K,
        }
    }

    /// Oscillator stabilisation time (ms) to wait after `SYS_EN` before
    /// enabling the LCD bias.  A 32.768 kHz crystal needs far longer to
    /// start up than the on-chip RC or an already-running external clock.
    #[inline]
    fn stabilize_ms(self) -> u32 {
        match self {
            ClockSource::Rc256k => 2,
            ClockSource::Ext256k => 2,
            ClockSource::Xtal32k => 50,
        }
    }
}

/// Buzzer output frequency.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ToneFreq {
    /// 4 kHz.
    Khz4,
    /// 2 kHz.
    Khz2,
}

impl ToneFreq {
    #[inline]
    fn command(self) -> u8 {
        match self {
            ToneFreq::Khz4 => cmd::TONE_4K,
            ToneFreq::Khz2 => cmd::TONE_2K,
        }
    }
}

/// Time base / WDT clock output frequency.
///
/// Sets both the time-base output frequency and the WDT time-out period
/// (they share one prescaler): the higher the frequency, the shorter the WDT
/// time-out.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TimerFreq {
    /// 1 Hz, WDT time-out 4 s.
    Hz1,
    /// 2 Hz, WDT time-out 2 s.
    Hz2,
    /// 4 Hz, WDT time-out 1 s.
    Hz4,
    /// 8 Hz, WDT time-out 1/2 s.
    Hz8,
    /// 16 Hz, WDT time-out 1/4 s.
    Hz16,
    /// 32 Hz, WDT time-out 1/8 s.
    Hz32,
    /// 64 Hz, WDT time-out 1/16 s.
    Hz64,
    /// 128 Hz, WDT time-out 1/32 s.
    Hz128,
}

impl TimerFreq {
    #[inline]
    fn command(self) -> u8 {
        match self {
            TimerFreq::Hz1 => cmd::F1,
            TimerFreq::Hz2 => cmd::F2,
            TimerFreq::Hz4 => cmd::F4,
            TimerFreq::Hz8 => cmd::F8,
            TimerFreq::Hz16 => cmd::F16,
            TimerFreq::Hz32 => cmd::F32,
            TimerFreq::Hz64 => cmd::F64,
            TimerFreq::Hz128 => cmd::F128,
        }
    }
}

/// Time-base subsystem mode.  Time base and WDT share one generator and are
/// mutually exclusive; this enum makes an illegal "both on" state
/// unrepresentable.  IRQ output follows the mode (on for TimeBase/Watchdog,
/// off for Off).
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum TimerMode {
    /// Time base + WDT off; IRQ output off.
    Off,
    /// Periodic time-base interrupt at `freq` (IRQ enabled).
    TimeBase(TimerFreq),
    /// Watchdog at `freq` (IRQ enabled); feed with [`Ht1621b::wdt_feed`].
    Watchdog(TimerFreq),
}

/// Power-on configuration for [`Ht1621b`].
#[derive(Clone, Copy, Setters)]
pub struct Config {
    pub bias: Bias,
    pub commons: Commons,
    pub clock: ClockSource,
}

impl Default for Config {
    /// 1/3 bias, 4 COM, internal RC 256 kHz — the datasheet reset defaults
    /// for a typical multiplexed LCD panel.
    fn default() -> Self {
        Self {
            bias: Bias::Third,
            commons: Commons::Four,
            clock: ClockSource::Rc256k,
        }
    }
}

impl Config {
    /// Resolve `bias` + `commons` into the matching BIAS command code.
    #[inline]
    fn bias_command(self) -> u8 {
        match (self.bias, self.commons) {
            (Bias::Half, Commons::Two) => cmd::BIAS_1_2_2COM,
            (Bias::Half, Commons::Three) => cmd::BIAS_1_2_3COM,
            (Bias::Half, Commons::Four) => cmd::BIAS_1_2_4COM,
            (Bias::Third, Commons::Two) => cmd::BIAS_1_3_2COM,
            (Bias::Third, Commons::Three) => cmd::BIAS_1_3_3COM,
            (Bias::Third, Commons::Four) => cmd::BIAS_1_3_4COM,
        }
    }
}

/// High-level, ergonomic HT1621B driver.
///
/// Generic over the bus implementation `B`.  Two concrete aliases are provided:
/// - [`Ht1621b`] – 3-wire write‑only (CS, WR, DA)
#[cfg_attr(
    feature = "read",
    doc = "- [`Ht1621bRW`] – 4-wire with read support (CS, WR, **RD**, DA)"
)]
#[cfg_attr(
    not(feature = "read"),
    doc = "- `Ht1621bRW` (enable the `read` feature) – 4-wire with read support"
)]
pub struct Driver<B> {
    bus: B,
}

#[allow(private_bounds)]
impl<B: Ht1621bBusWrite> Driver<B> {
    /// Shared power-on initialisation sequence.
    async fn init<AD: embedded_hal_async::delay::DelayNs>(
        &mut self,
        async_delay: &mut AD,
        config: Config,
    ) {
        async_delay.delay_ms(1).await;
        self.bus.write_command(config.bias_command());
        self.bus.write_command(config.clock.command());
        self.bus.write_command(cmd::SYS_DIS);
        self.bus.write_command(cmd::SYS_EN);
        async_delay.delay_ms(config.clock.stabilize_ms()).await;
        self.clear();
        self.bus.write_command(cmd::LCD_ON);
    }

    /// Clear all display RAM (32 × 4 bits) to zero, blanking every segment.
    #[inline]
    pub fn clear(&mut self) {
        self.bus.write_bytes(u6::new(0), &[0u8; 16]);
    }

    /// Apply a new [`Config`] at runtime.
    ///
    /// Updates the LCD bias/COM and system clock source (BIAS + clock
    /// commands).  Other state (LCD on/off, time base, tone) is left
    /// untouched.
    #[inline]
    pub fn set_config(&mut self, config: Config) {
        self.bus.write_command(config.bias_command());
        self.bus.write_command(config.clock.command());
    }

    /// Turn the LCD bias generator on (LCD ON).
    #[inline]
    pub fn lcd_on(&mut self) {
        self.bus.write_command(cmd::LCD_ON);
    }

    /// Turn the LCD bias generator off (LCD OFF).
    #[inline]
    pub fn lcd_off(&mut self) {
        self.bus.write_command(cmd::LCD_OFF);
    }

    /// Enter lowest-power sleep: blank the display, then stop the system
    /// oscillator and LCD bias generator (LCD OFF + SYS DIS).
    ///
    /// The time base / WDT stop while asleep and RAM should be considered
    /// stale on wake.  Use [`Ht1621b::wake`] to resume.
    #[inline]
    pub fn sleep(&mut self) {
        self.bus.write_command(cmd::LCD_OFF);
        self.bus.write_command(cmd::SYS_DIS);
    }

    /// Wake from [`Ht1621b::sleep`]: restart the oscillator and turn the LCD
    /// bias generator back on (SYS EN + LCD ON).
    ///
    /// RAM contents are not restored here; rewrite the display data after
    /// waking if needed.
    #[inline]
    pub fn wake(&mut self) {
        self.bus.write_command(cmd::SYS_EN);
        self.bus.write_command(cmd::LCD_ON);
    }

    /// Turn the buzzer on at the given frequency.
    ///
    /// Sets the tone frequency (`TONE 4k`/`TONE 2k`) then enables output
    /// (`TONE ON`).
    #[inline]
    pub fn tone_on(&mut self, freq: ToneFreq) {
        self.bus.write_command(freq.command());
        self.bus.write_command(cmd::TONE_ON);
    }

    /// Turn the buzzer off (TONE OFF).
    #[inline]
    pub fn tone_off(&mut self) {
        self.bus.write_command(cmd::TONE_OFF);
    }

    /// Configure the time-base / WDT subsystem.
    ///
    /// Time base and WDT are mutually exclusive (shared generator); the
    /// unused one is disabled here, the frequency set, the counter cleared,
    /// and IRQ output enabled/disabled to match the mode.
    pub fn set_timer_mode(&mut self, mode: TimerMode) {
        match mode {
            TimerMode::Off => {
                self.bus.write_command(cmd::TIMER_DIS);
                self.bus.write_command(cmd::WDT_DIS);
                self.bus.write_command(cmd::IRQ_DIS);
            }
            TimerMode::TimeBase(freq) => {
                self.bus.write_command(cmd::WDT_DIS);
                self.bus.write_command(freq.command());
                self.bus.write_command(cmd::CLR_TIMER);
                self.bus.write_command(cmd::TIMER_EN);
                self.bus.write_command(cmd::IRQ_EN);
            }
            TimerMode::Watchdog(freq) => {
                self.bus.write_command(cmd::TIMER_DIS);
                self.bus.write_command(freq.command());
                self.bus.write_command(cmd::CLR_WDT);
                self.bus.write_command(cmd::WDT_EN);
                self.bus.write_command(cmd::IRQ_EN);
            }
        }
    }

    /// Feed the watchdog (CLR WDT); call periodically in `Watchdog` mode.
    #[inline]
    pub fn wdt_feed(&mut self) {
        self.bus.write_command(cmd::CLR_WDT);
    }

    /// Reset the time-base counter / realign phase (CLR TIMER).
    #[inline]
    pub fn timer_clear(&mut self) {
        self.bus.write_command(cmd::CLR_TIMER);
    }

    /// Access the underlying protocol layer for raw operations.
    #[inline]
    pub fn bus(&mut self) -> &mut B {
        &mut self.bus
    }

    /// Burst-write 4-bit words to RAM.
    #[inline]
    pub fn write_words(&mut self, addr: u6, words: &[u4]) {
        self.bus.write_words(addr, words);
    }

    /// Write a single 4-bit word to RAM.
    #[inline]
    pub fn write_word(&mut self, addr: u6, word: u4) {
        self.bus.write_word(addr, word);
    }

    /// Burst-write bytes to RAM.
    #[inline]
    pub fn write_bytes(&mut self, addr: u6, data: &[u8]) {
        self.bus.write_bytes(addr, data);
    }

    /// Write a single byte to RAM.
    #[inline]
    pub fn write_byte(&mut self, addr: u6, data: u8) {
        self.bus.write_byte(addr, data);
    }
}

#[cfg(feature = "read")]
#[allow(private_bounds)]
impl<B: Ht1621bBusRead> Driver<B> {
    /// Read a single 4-bit word from RAM.
    #[inline]
    pub fn read_word(&mut self, addr: u6) -> u4 {
        self.bus.read_word(addr)
    }

    /// Burst-read 4-bit words from RAM.
    #[inline]
    pub fn read_words(&mut self, addr: u6, buf: &mut [u4]) {
        self.bus.read_words(addr, buf);
    }

    /// Read-modify-write a single 4-bit word at `addr`.
    #[inline]
    pub fn read_modify_write_word(&mut self, addr: u6, f: impl FnOnce(u4) -> u4) {
        self.bus.read_modify_write_word(addr, f);
    }

    /// Read a single byte from RAM.
    #[inline]
    pub fn read_byte(&mut self, addr: u6) -> u8 {
        self.bus.read_byte(addr)
    }

    /// Burst-read bytes from RAM.
    #[inline]
    pub fn read_bytes(&mut self, addr: u6, buf: &mut [u8]) {
        self.bus.read_bytes(addr, buf);
    }

    /// Read-modify-write multiple 4-bit words at `addr`.
    #[inline]
    pub fn read_modify_write_words(
        &mut self,
        addr: u6,
        len: usize,
        f: impl FnMut(u4, usize) -> u4,
    ) {
        self.bus.read_modify_write_words(addr, len, f);
    }
}

/// 3-wire write-only driver.  Uses CS, WR, DA pins.
///
/// Alias for `Driver<Ht1621bBus<CS, WR, DA, D>>`.
pub type Ht1621b<CS, WR, DA, D> = Driver<Ht1621bBus<CS, WR, DA, D>>;

/// 4-wire driver with read / read‑modify‑write support.  Adds **RD** pin and
/// requires a [`FlexPin`] **DA** pin.
///
/// Alias for `Driver<Ht1621bBusRW<CS, WR, RD, DA, D>>`.
#[cfg(feature = "read")]
pub type Ht1621bRW<CS, WR, RD, DA, D> = Driver<Ht1621bBusRW<CS, WR, RD, DA, D>>;

impl<CS, WR, DA, D> Ht1621b<CS, WR, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    DA: OutputPin,
    D: DelayNs,
{
    /// Create the driver and run the power-on initialisation sequence.
    ///
    /// `async_delay` is borrowed only for the duration of this call and is
    /// used for the long, ms-scale waits (power-on settle and clock-dependent
    /// oscillator stabilisation) so the executor is not blocked; the short
    /// bit-level bus timing still uses the owned blocking `delay`.
    ///
    /// Sequence: ~1 ms power-on settle → bias/COM → clock source →
    /// system disable → system enable → oscillator-stabilisation delay
    /// (clock-dependent) → clear RAM → LCD on.  A blank display is shown as
    /// soon as the bias generator turns on.
    pub async fn new<AD>(
        cs: CS,
        wr: WR,
        da: DA,
        delay: D,
        async_delay: &mut AD,
        config: Config,
    ) -> Self
    where
        AD: embedded_hal_async::delay::DelayNs,
    {
        let mut this = Self {
            bus: Ht1621bBus::new(cs, wr, da, delay),
        };
        this.init(async_delay, config).await;
        this
    }
}

#[cfg(feature = "read")]
impl<CS, WR, RD, DA, D> Ht1621bRW<CS, WR, RD, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    RD: OutputPin,
    DA: FlexPin,
    D: DelayNs,
{
    /// Create the driver and run the power-on initialisation sequence.
    ///
    /// `async_delay` is borrowed only for the duration of this call and is
    /// used for the long, ms-scale waits (power-on settle and clock-dependent
    /// oscillator stabilisation) so the executor is not blocked; the short
    /// bit-level bus timing still uses the owned blocking `delay`.
    ///
    /// Sequence: ~1 ms power-on settle → bias/COM → clock source →
    /// system disable → system enable → oscillator-stabilisation delay
    /// (clock-dependent) → clear RAM → LCD on.  A blank display is shown as
    /// soon as the bias generator turns on.
    pub async fn new<AD>(
        cs: CS,
        wr: WR,
        rd: RD,
        da: DA,
        delay: D,
        async_delay: &mut AD,
        config: Config,
    ) -> Self
    where
        AD: embedded_hal_async::delay::DelayNs,
    {
        let mut this = Self {
            bus: Ht1621bBusRW::new(cs, wr, rd, da, delay),
        };
        this.init(async_delay, config).await;
        this
    }
}