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
//! Low-level HT1621B protocol layer.
//!
//! [`Ht1621bBus`] implements the raw 3-wire framing and knows nothing about
//! LCD semantics.  Most users should prefer the ergonomic [`crate::Ht1621b`]
//! wrapper; use this layer directly only when you need raw command / RAM
//! access.

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

// ---------------------------------------------------------------------------
// Write trait — implemented by every bus variant
// ---------------------------------------------------------------------------

/// Internal trait providing write-phase operations.
///
/// Implementors supply three primitive signals (`write_bit`, `cs_low`,
/// `cs_high`) and a per-frame settling delay.  All higher-level write methods
/// are derived from those.
pub(crate) trait Ht1621bBusWrite {
    /// Push one bit onto DA using a WR clock pulse.
    fn write_bit(&mut self, b: bool);

    /// Assert CS low (frame start).
    fn cs_low(&mut self);

    /// De-assert CS high (frame end).
    fn cs_high(&mut self);

    /// Post-frame settling delay (10 µs).
    fn frame_end(&mut self);

    /// Called just after CS↓ at the start of every write frame.
    ///
    /// Default no-op; the read/write bus variant overrides it to switch the
    /// bidirectional DA line back to output mode before clocking bits out.
    #[inline]
    fn begin_frame(&mut self) {}

    // -- helpers built on the primitives --------------------------------

    #[inline]
    fn write_addr_bits(&mut self, addr: u6) {
        let mut mask: u8 = 0x20;
        for _ in 0..6 {
            self.write_bit((addr.value() & mask) != 0);
            mask >>= 1;
        }
    }

    #[inline]
    fn write_id_101_addr(&mut self, addr: u6) {
        self.write_bit(true);
        self.write_bit(false);
        self.write_bit(true);
        self.write_addr_bits(addr);
    }

    #[inline]
    fn write_id_100(&mut self) {
        self.write_bit(true);
        self.write_bit(false);
        self.write_bit(false);
    }
    // -- public write API -----------------------------------------------

    /// Send an 8-bit command.
    ///
    /// Frame: CS↓ → `100` → C7–C0 → `X`(=0) → CS↑ → 10 µs settling.
    fn write_command(&mut self, cmd: u8) {
        self.cs_low();
        self.begin_frame();
        self.write_id_100();
        let mut mask: u8 = 0x80;
        for _ in 0..8 {
            self.write_bit((cmd & mask) != 0);
            mask >>= 1;
        }
        self.write_bit(false);
        self.cs_high();
        self.frame_end();
    }

    /// Burst-write multiple 4-bit words starting at `addr`.
    ///
    /// Frame: CS↓ → `101` → 6-bit addr → words … → CS↑ → 10 µs.
    fn write_words(&mut self, addr: u6, words: &[u4]) {
        self.cs_low();
        self.begin_frame();
        self.write_id_101_addr(addr);
        for &word in words {
            let value = word.value();
            let mut mask: u8 = 0x01;
            for _ in 0..4 {
                self.write_bit((value & mask) != 0);
                mask <<= 1;
            }
        }
        self.cs_high();
        self.frame_end();
    }

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

    /// Burst-write multiple bytes starting at `addr`.
    ///
    /// Each byte spans 2 RAM addresses (low→high nibble, LSB-first).
    fn write_bytes(&mut self, addr: u6, data: &[u8]) {
        self.cs_low();
        self.begin_frame();
        self.write_id_101_addr(addr);
        for &byte in data {
            let mut mask: u8 = 0x01;
            for _ in 0..8 {
                self.write_bit((byte & mask) != 0);
                mask <<= 1;
            }
        }
        self.cs_high();
        self.frame_end();
    }

    /// Write a single byte to `addr` (wrapper around `write_bytes`).
    #[inline]
    fn write_byte(&mut self, addr: u6, data: u8) {
        self.write_bytes(addr, &[data]);
    }
}

// ---------------------------------------------------------------------------
// Read trait — extends Write with read-phase operations
// ---------------------------------------------------------------------------

/// Internal trait extending [`Ht1621bBusWrite`] with read and
/// read-modify-write support.  Only bus variants that own an RD pin and a
/// bidirectional DA ([`FlexPin`]) implement this.
#[cfg(feature = "read")]
pub(crate) trait Ht1621bBusRead: Ht1621bBusWrite {
    /// Read one bit from DA using an RD clock pulse.
    ///
    /// RD↓ → wait → sample DA → RD↑ → wait.
    fn read_bit(&mut self) -> bool;

    /// Switch DA to input mode so the HT1621B can drive it.
    fn da_to_input(&mut self);

    /// Switch DA to output mode so the MCU can drive it.
    fn da_to_output(&mut self);

    // -- public read API ------------------------------------------------

    #[inline]
    fn write_id_110(&mut self) {
        self.write_bit(true);
        self.write_bit(true);
        self.write_bit(false);
    }

    #[inline]
    fn write_id_110_addr(&mut self, addr: u6) {
        self.write_id_110();
        self.write_addr_bits(addr);
    }

    /// Burst-read multiple 4-bit words starting at `addr`.
    ///
    /// Frame: CS↓ → `110` → 6-bit addr → read nibbles via RD → CS↑ → 10 µs.
    /// Data is output LSB-first (D0→D3) and sampled on RD↑.
    fn read_words(&mut self, addr: u6, buf: &mut [u4]) {
        self.cs_low();
        self.da_to_output();
        self.write_id_110_addr(addr);
        self.da_to_input();
        for slot in buf.iter_mut() {
            let mut value: u8 = 0;
            let mut mask: u8 = 0x01;
            for _ in 0..4 {
                if self.read_bit() {
                    value |= mask;
                }
                mask <<= 1;
            }
            *slot = u4::new(value);
        }
        self.cs_high();
        self.frame_end();
    }

    /// Read a single 4-bit word from `addr`.
    #[inline]
    fn read_word(&mut self, addr: u6) -> u4 {
        let mut buf = [u4::new(0)];
        self.read_words(addr, &mut buf);
        buf[0]
    }

    /// Read-modify-write a single 4-bit word at `addr` in a single CS frame.
    ///
    /// Frame: CS↓ → `101` → 6-bit addr → read nibble via RD → write modified
    /// nibble via WR → CS↑ → 10 µs.
    fn read_modify_write_word(&mut self, addr: u6, f: impl FnOnce(u4) -> u4) {
        self.cs_low();
        self.da_to_output();
        self.write_id_101_addr(addr);
        self.da_to_input();
        let mut value: u8 = 0;
        let mut mask: u8 = 0x01;
        for _ in 0..4 {
            if self.read_bit() {
                value |= mask;
            }
            mask <<= 1;
        }
        let current = u4::new(value);
        let modified = f(current);
        self.da_to_output();
        let mod_val = modified.value();
        let mut mask: u8 = 0x01;
        for _ in 0..4 {
            self.write_bit((mod_val & mask) != 0);
            mask <<= 1;
        }
        self.cs_high();
        self.frame_end();
    }

    /// Burst-read multiple bytes starting at `addr` in a single CS frame.
    ///
    /// Frame: CS↓ → `110` → 6-bit addr → read bytes via RD → CS↑ → 10 µs.
    /// Each byte spans 2 RAM addresses (low→high nibble, LSB-first).
    fn read_bytes(&mut self, addr: u6, buf: &mut [u8]) {
        self.cs_low();
        self.da_to_output();
        self.write_id_110_addr(addr);
        self.da_to_input();
        for slot in buf.iter_mut() {
            let mut lo: u8 = 0;
            let mut mask: u8 = 0x01;
            for _ in 0..4 {
                if self.read_bit() {
                    lo |= mask;
                }
                mask <<= 1;
            }
            let mut hi: u8 = 0;
            let mut mask: u8 = 0x01;
            for _ in 0..4 {
                if self.read_bit() {
                    hi |= mask;
                }
                mask <<= 1;
            }
            *slot = lo | (hi << 4);
        }
        self.cs_high();
        self.frame_end();
    }

    /// Read a single byte from `addr` (wrapper around `read_bytes`).
    #[inline]
    fn read_byte(&mut self, addr: u6) -> u8 {
        let mut buf = [0u8];
        self.read_bytes(addr, &mut buf);
        buf[0]
    }

    /// Read-modify-write multiple 4-bit words in a single CS frame.
    ///
    /// Frame: CS↓ → `101` → 6-bit addr → for each word: read nibble via RD →
    /// write modified nibble via WR → CS↑ → 10 µs.
    /// `f` receives the current nibble value and its index `0..len`.
    fn read_modify_write_words(
        &mut self,
        addr: u6,
        len: usize,
        mut f: impl FnMut(u4, usize) -> u4,
    ) {
        self.cs_low();
        self.da_to_output();
        self.write_id_101_addr(addr);
        for i in 0..len {
            self.da_to_input();
            let mut value: u8 = 0;
            let mut mask: u8 = 0x01;
            for _ in 0..4 {
                if self.read_bit() {
                    value |= mask;
                }
                mask <<= 1;
            }
            let modified = f(u4::new(value), i);
            self.da_to_output();
            let v = modified.value();
            let mut mask: u8 = 0x01;
            for _ in 0..4 {
                self.write_bit((v & mask) != 0);
                mask <<= 1;
            }
        }
        self.cs_high();
        self.frame_end();
    }
}

// ===========================================================================
// 3-wire bus — write only
// ===========================================================================

/// Low-level protocol layer (3-wire, write-only).
///
/// Owns CS, WR, DA pins plus a delay source and implements the raw HT1621B
/// 3-wire framing.  It is generic over any [`OutputPin`] and [`DelayNs`]
/// implementations, so it is not tied to a specific HAL.
pub struct Ht1621bBus<CS, WR, DA, D> {
    cs: CS,
    wr: WR,
    da: DA,
    delay: D,
}

impl<CS, WR, DA, D> Ht1621bBus<CS, WR, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    DA: OutputPin,
    D: DelayNs,
{
    /// Create the protocol-layer instance.
    ///
    /// Idles the bus (CS=High, WR=High, DA=High).
    pub fn new(mut cs: CS, mut wr: WR, mut da: DA, delay: D) -> Self {
        let _ = cs.set_high();
        let _ = wr.set_high();
        let _ = da.set_high();
        Self { cs, wr, da, delay }
    }
}

impl<CS, WR, DA, D> Ht1621bBusWrite for Ht1621bBus<CS, WR, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    DA: OutputPin,
    D: DelayNs,
{
    #[inline]
    fn write_bit(&mut self, b: bool) {
        if b {
            let _ = self.da.set_high();
        } else {
            let _ = self.da.set_low();
        }
        let _ = self.wr.set_low();
        self.delay.delay_us(5);
        let _ = self.wr.set_high();
        self.delay.delay_us(5);
    }

    #[inline]
    fn cs_low(&mut self) {
        let _ = self.cs.set_low();
    }

    #[inline]
    fn cs_high(&mut self) {
        let _ = self.cs.set_high();
    }

    #[inline]
    fn frame_end(&mut self) {
        self.delay.delay_us(10);
    }
}

// ===========================================================================
// 4-wire bus — write + read + read-modify-write
// ===========================================================================

/// Low-level protocol layer with read support (4-wire).
///
/// Like [`Ht1621bBus`] but adds the **RD** pin required for RAM read and
/// read-modify-write operations.  The DA pin must implement [`FlexPin`] so
/// the driver can switch between output and input modes at runtime.
#[cfg(feature = "read")]
pub struct Ht1621bBusRW<CS, WR, RD, DA, D> {
    cs: CS,
    wr: WR,
    rd: RD,
    da: DA,
    delay: D,
}

#[cfg(feature = "read")]
impl<CS, WR, RD, DA, D> Ht1621bBusRW<CS, WR, RD, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    RD: OutputPin,
    DA: FlexPin,
    D: DelayNs,
{
    /// Create the protocol-layer instance.
    ///
    /// Idles the bus (CS=High, WR=High, RD=High, DA=High).
    pub fn new(mut cs: CS, mut wr: WR, mut rd: RD, mut da: DA, delay: D) -> Self {
        let _ = cs.set_high();
        let _ = wr.set_high();
        let _ = rd.set_high();
        let _ = da.set_high();
        Self {
            cs,
            wr,
            rd,
            da,
            delay,
        }
    }
}

#[cfg(feature = "read")]
impl<CS, WR, RD, DA, D> Ht1621bBusWrite for Ht1621bBusRW<CS, WR, RD, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    RD: OutputPin,
    DA: FlexPin,
    D: DelayNs,
{
    #[inline]
    fn write_bit(&mut self, b: bool) {
        if b {
            let _ = self.da.set_high();
        } else {
            let _ = self.da.set_low();
        }
        let _ = self.wr.set_low();
        self.delay.delay_us(5);
        let _ = self.wr.set_high();
        self.delay.delay_us(5);
    }

    #[inline]
    fn cs_low(&mut self) {
        let _ = self.cs.set_low();
    }

    #[inline]
    fn cs_high(&mut self) {
        let _ = self.cs.set_high();
    }

    #[inline]
    fn frame_end(&mut self) {
        self.delay.delay_us(10);
    }

    #[inline]
    fn begin_frame(&mut self) {
        self.da_to_output();
    }
}

#[cfg(feature = "read")]
impl<CS, WR, RD, DA, D> Ht1621bBusRead for Ht1621bBusRW<CS, WR, RD, DA, D>
where
    CS: OutputPin,
    WR: OutputPin,
    RD: OutputPin,
    DA: FlexPin,
    D: DelayNs,
{
    #[inline]
    fn read_bit(&mut self) -> bool {
        let _ = self.rd.set_low();
        self.delay.delay_us(5);
        let bit = self.da.is_high().unwrap_or(true);
        let _ = self.rd.set_high();
        self.delay.delay_us(5);
        bit
    }

    #[inline]
    fn da_to_input(&mut self) {
        self.da.set_as_input_no_pull();
    }

    #[inline]
    fn da_to_output(&mut self) {
        self.da.set_as_output_default_speed();
        let _ = self.da.set_high();
    }
}