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
#![no_std]

//use core::fmt::Result;
//use core::fmt::Write;

use embedded_hal::blocking::delay::{DelayMs, DelayUs};
use embedded_hal::blocking::i2c;
use embedded_hal::digital::v2::OutputPin;

pub mod bus;
use bus::{DataBus, EightBitBus, FourBitBus, I2CBus};

pub mod error;
use error::Result;

pub mod entry_mode;

use entry_mode::{CursorMode, EntryMode};

pub mod display_mode;

pub use display_mode::DisplayMode;

pub struct HD44780<B: DataBus> {
    bus: B,
    entry_mode: EntryMode,
    display_mode: DisplayMode,
}

/// Used in the direction argument for shifting the cursor and the display
pub enum Direction {
    Left,
    Right,
}

/// Used in set_display_mode to make the parameters more clear
pub enum Display {
    On,
    Off,
}

pub enum Cursor {
    Visible,
    Invisible,
}

pub enum CursorBlink {
    On,
    Off,
}

impl<
        RS: OutputPin,
        EN: OutputPin,
        D0: OutputPin,
        D1: OutputPin,
        D2: OutputPin,
        D3: OutputPin,
        D4: OutputPin,
        D5: OutputPin,
        D6: OutputPin,
        D7: OutputPin,
    > HD44780<EightBitBus<RS, EN, D0, D1, D2, D3, D4, D5, D6, D7>>
{
    /// Create an instance of a `HD44780` from 8 data pins, a register select
    /// pin, an enable pin and a struct implementing the delay trait.
    /// - The delay instance is used to sleep between commands to
    /// ensure the `HD44780` has enough time to process commands.
    /// - The eight db0..db7 pins are used to send and recieve with
    ///  the `HD44780`.
    /// - The register select pin is used to tell the `HD44780`
    /// if incoming data is a command or data.
    /// - The enable pin is used to tell the `HD44780` that there
    /// is data on the 8 data pins and that it should read them in.
    ///
    pub fn new_8bit<D: DelayUs<u16> + DelayMs<u8>>(
        rs: RS,
        en: EN,
        d0: D0,
        d1: D1,
        d2: D2,
        d3: D3,
        d4: D4,
        d5: D5,
        d6: D6,
        d7: D7,
        delay: &mut D,
    ) -> Result<HD44780<EightBitBus<RS, EN, D0, D1, D2, D3, D4, D5, D6, D7>>> {
        let mut hd = HD44780 {
            bus: EightBitBus::from_pins(rs, en, d0, d1, d2, d3, d4, d5, d6, d7),
            entry_mode: EntryMode::default(),
            display_mode: DisplayMode::default(),
        };

        hd.init_8bit(delay)?;

        return Ok(hd);
    }
}

impl<RS: OutputPin, EN: OutputPin, D4: OutputPin, D5: OutputPin, D6: OutputPin, D7: OutputPin>
    HD44780<FourBitBus<RS, EN, D4, D5, D6, D7>>
{
    /// Create an instance of a `HD44780` from 4 data pins, a register select
    /// pin, an enable pin and a struct implementing the delay trait.
    /// - The delay instance is used to sleep between commands to
    /// ensure the `HD44780` has enough time to process commands.
    /// - The four db0..db3 pins are used to send and recieve with
    ///  the `HD44780`.
    /// - The register select pin is used to tell the `HD44780`
    /// if incoming data is a command or data.
    /// - The enable pin is used to tell the `HD44780` that there
    /// is data on the 4 data pins and that it should read them in.
    ///
    /// This mode operates differently than 8 bit mode by using 4 less
    /// pins for data, which is nice on devices with less I/O although
    /// the I/O takes a 'bit' longer
    ///
    /// Instead of commands being sent byte by byte each command is
    /// broken up into it's upper and lower nibbles (4 bits) before
    /// being sent over the data bus
    ///
    pub fn new_4bit<D: DelayUs<u16> + DelayMs<u8>>(
        rs: RS,
        en: EN,
        d4: D4,
        d5: D5,
        d6: D6,
        d7: D7,
        delay: &mut D,
    ) -> Result<HD44780<FourBitBus<RS, EN, D4, D5, D6, D7>>> {
        let mut hd = HD44780 {
            bus: FourBitBus::from_pins(rs, en, d4, d5, d6, d7),
            entry_mode: EntryMode::default(),
            display_mode: DisplayMode::default(),
        };

        hd.init_4bit(delay)?;

        return Ok(hd);
    }
}

impl<I2C: i2c::Write> HD44780<I2CBus<I2C>> {
    /// Create an instance of a `HD44780` from an i2c write peripheral,
    /// the `HD44780` I2C address and a struct implementing the delay trait.
    /// - The delay instance is used to sleep between commands to
    /// ensure the `HD44780` has enough time to process commands.
    /// - The i2c peripheral is used to send data to the `HD44780` and to set
    /// its register select and enable pins.
    ///
    /// This mode operates on an I2C bus, using an I2C to parallel port expander
    ///
    pub fn new_i2c<D: DelayUs<u16> + DelayMs<u8>>(
        i2c_bus: I2C,
        address: u8,
        delay: &mut D,
    ) -> Result<HD44780<I2CBus<I2C>>> {
        let mut hd = HD44780 {
            bus: I2CBus::new(i2c_bus, address),
            entry_mode: EntryMode::default(),
            display_mode: DisplayMode::default(),
        };

        hd.init_4bit(delay)?;

        return Ok(hd);
    }
}

impl<B> HD44780<B>
where
    B: DataBus,
{
    /// Unshifts the display and sets the cursor position to 0
    ///
    /// ```rust,ignore
    /// lcd.reset();
    /// ```
    pub fn reset<D: DelayUs<u16> + DelayMs<u8>>(&mut self, delay: &mut D) -> Result<()> {
        self.write_command(0b0000_0010, delay)?;

        Ok(())
    }

    /// Set if the display should be on, if the cursor should be
    /// visible, and if the cursor should blink
    ///
    /// Note: This is equivilent to calling all of the other relavent
    /// methods however this operation does it all in one go to the `HD44780`
    pub fn set_display_mode<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        display_mode: DisplayMode,
        delay: &mut D,
    ) -> Result<()> {
        self.display_mode = display_mode;

        let cmd_byte = self.display_mode.as_byte();

        self.write_command(cmd_byte, delay)?;

        Ok(())
    }

    /// Clear the entire display
    ///
    /// ```rust,ignore
    /// lcd.clear();
    /// ```
    pub fn clear<D: DelayUs<u16> + DelayMs<u8>>(&mut self, delay: &mut D) -> Result<()> {
        self.write_command(0b0000_0001, delay)?;

        Ok(())
    }

    /// If enabled, automatically scroll the display when a new
    /// character is written to the display
    ///
    /// ```rust,ignore
    /// lcd.set_autoscroll(true);
    /// ```
    pub fn set_autoscroll<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        enabled: bool,
        delay: &mut D,
    ) -> Result<()> {
        self.entry_mode.shift_mode = enabled.into();

        let cmd = self.entry_mode.as_byte();

        self.write_command(cmd, delay)?;

        Ok(())
    }

    /// Set if the cursor should be visible
    pub fn set_cursor_visibility<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        visibility: Cursor,
        delay: &mut D,
    ) -> Result<()> {
        self.display_mode.cursor_visibility = visibility;

        let cmd = self.display_mode.as_byte();

        self.write_command(cmd, delay)?;

        Ok(())
    }

    /// Set if the characters on the display should be visible
    pub fn set_display<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        display: Display,
        delay: &mut D,
    ) -> Result<()> {
        self.display_mode.display = display;

        let cmd = self.display_mode.as_byte();

        self.write_command(cmd, delay)?;

        Ok(())
    }

    /// Set if the cursor should blink
    pub fn set_cursor_blink<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        blink: CursorBlink,
        delay: &mut D,
    ) -> Result<()> {
        self.display_mode.cursor_blink = blink;

        let cmd = self.display_mode.as_byte();

        self.write_command(cmd, delay)?;

        Ok(())
    }

    /// Set which way the cursor will move when a new character is written
    ///
    /// ```rust,ignore
    /// // Move right (Default) when a new character is written
    /// lcd.set_cursor_mode(CursorMode::Right)
    ///
    /// // Move left when a new character is written
    /// lcd.set_cursor_mode(CursorMode::Left)
    /// ```
    pub fn set_cursor_mode<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        mode: CursorMode,
        delay: &mut D,
    ) -> Result<()> {
        self.entry_mode.cursor_mode = mode;

        let cmd = self.entry_mode.as_byte();

        self.write_command(cmd, delay)?;

        Ok(())
    }

    /// Set the cursor position
    ///
    /// ```rust,ignore
    /// // Move to line 2
    /// lcd.set_cursor_pos(40)
    /// ```
    pub fn set_cursor_pos<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        position: u8,
        delay: &mut D,
    ) -> Result<()> {
        let lower_7_bits = 0b0111_1111 & position;

        self.write_command(0b1000_0000 | lower_7_bits, delay)?;

        Ok(())
    }

    /// Shift just the cursor to the left or the right
    ///
    /// ```rust,ignore
    /// lcd.shift_cursor(Direction::Left);
    /// lcd.shift_cursor(Direction::Right);
    /// ```
    pub fn shift_cursor<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        dir: Direction,
        delay: &mut D,
    ) -> Result<()> {
        let bits = match dir {
            Direction::Left => 0b0000_0000,
            Direction::Right => 0b0000_0100,
        };

        self.write_command(0b0001_0000 | bits | bits, delay)?;

        Ok(())
    }

    /// Shift the entire display to the left or the right
    ///
    /// ```rust,ignore
    /// lcd.shift_display(Direction::Left);
    /// lcd.shift_display(Direction::Right);
    /// ```
    pub fn shift_display<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        dir: Direction,
        delay: &mut D,
    ) -> Result<()> {
        let bits = match dir {
            Direction::Left => 0b0000_0000,
            Direction::Right => 0b0000_0100,
        };

        self.write_command(0b0001_1000 | bits, delay)?;

        Ok(())
    }

    /// Write a single character to the `HD44780`. This `char` just gets downcast to a `u8`
    /// internally, so make sure that whatever character you're printing fits inside that range, or
    /// you can just use [write_byte](#method.write_byte) to have the compiler check for you.
    /// See the documentation on that function for more details about compatibility.
    ///
    /// ```rust,ignore
    /// lcd.write_char('A', &mut delay)?; // prints 'A'
    /// ```
    pub fn write_char<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        data: char,
        delay: &mut D,
    ) -> Result<()> {
        self.write_byte(data as u8, delay)
    }

    fn write_command<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        cmd: u8,
        delay: &mut D,
    ) -> Result<()> {
        self.bus.write(cmd, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);
        Ok(())
    }

    fn init_4bit<D: DelayUs<u16> + DelayMs<u8>>(&mut self, delay: &mut D) -> Result<()> {
        // Wait for the LCD to wakeup if it was off
        delay.delay_ms(15u8);

        // Initialize Lcd in 4-bit mode
        self.bus.write(0x33, false, delay)?;

        // Wait for the command to be processed
        delay.delay_ms(5u8);

        // Sets 4-bit operation and enables 5x7 mode for chars
        self.bus.write(0x32, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        self.bus.write(0x28, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        // Clear Display
        self.bus.write(0x0E, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        // Move the cursor to beginning of first line
        self.bus.write(0x01, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        // Set entry mode
        self.bus.write(self.entry_mode.as_byte(), false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        self.bus.write(0x80, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        Ok(())
    }

    // Follow the 8-bit setup procedure as specified in the HD44780 datasheet
    fn init_8bit<D: DelayUs<u16> + DelayMs<u8>>(&mut self, delay: &mut D) -> Result<()> {
        // Wait for the LCD to wakeup if it was off
        delay.delay_ms(15u8);

        // Initialize Lcd in 8-bit mode
        self.bus.write(0b0011_0000, false, delay)?;

        // Wait for the command to be processed
        delay.delay_ms(5u8);

        // Sets 8-bit operation and enables 5x7 mode for chars
        self.bus.write(0b0011_1000, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        self.bus.write(0b0000_1110, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        // Clear Display
        self.bus.write(0b0000_0001, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        // Move the cursor to beginning of first line
        self.bus.write(0b000_0111, false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        // Set entry mode
        self.bus.write(self.entry_mode.as_byte(), false, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        Ok(())
    }

    /// Writes a string to the HD44780. Internally, this just prints the string byte-by-byte, so
    /// make sure the characters in the string fit in a normal `u8`. See the documentation on
    /// [write_byte](#method.write_byte) for more details on compatibility.
    ///
    /// ```rust,ignore
    /// lcd.write_str("Hello, World!", &mut delay)?;
    /// ```
    pub fn write_str<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        string: &str,
        delay: &mut D,
    ) -> Result<()> {
        self.write_bytes(string.as_bytes(), delay)
    }

    /// Writes a sequence of bytes to the HD44780. See the documentation on the
    /// [write_byte](#method.write_byte) function for more details about compatibility.
    ///
    /// ```rust,ignore
    /// lcd.write_bytes(b"Hello, World!", &mut delay)?;
    /// ```
    pub fn write_bytes<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        string: &[u8],
        delay: &mut D,
    ) -> Result<()> {
        for &b in string {
            self.write_byte(b, delay)?;
        }
        Ok(())
    }

    /// Writes a single byte to the HD44780. These usually map to ASCII characters when printed on the
    /// screen, but not always. While it varies depending on the ROM of the LCD, `0x20u8..=0x5b`
    /// and `0x5d..=0x7d` should map to their standard ASCII characters. That is, all the printable
    /// ASCII characters work, excluding `\` and `~`, which are usually displayed as `¥` and `🡢`
    /// respectively.
    ///
    /// More information can be found in the Hitachi datasheets for the HD44780.
    ///
    /// ```rust,ignore
    /// lcd.write_byte(b'A', &mut delay)?; // prints 'A'
    /// lcd.write_byte(b'\\', &mut delay)?; // usually prints ¥
    /// lcd.write_byte(b'~', &mut delay)?; // usually prints 🡢
    /// lcd.write_byte(b'\x7f', &mut delay)?; // usually prints 🡠
    /// ```
    pub fn write_byte<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        data: u8,
        delay: &mut D
    ) -> Result<()> {
        self.bus.write(data, true, delay)?;

        // Wait for the command to be processed
        delay.delay_us(100);

        Ok(())
    }

    // Pulse the enable pin telling the HD44780 that we something for it
    /*fn pulse_enable(&mut self) {
        self.en.set_high();
        self.delay.delay_ms(15u8);
        self.en.set_low();
    }*/
}

//impl<B> Write for HD44780<B>
//where
//    B: DataBus,
//{
//    fn write_str(&mut self, string: &str) -> Result {
//        for c in string.chars() {
//            self.write_char(c, delay);
//        }
//        Ok(())
//    }
//}