aboutsummaryrefslogtreecommitdiffstats
path: root/sw/deps/hd44780-driver/src/lib.rs
blob: 44421cecce28f47ec9b164ca82deb58165706209 (plain)
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
#![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, I2CMCP23008Bus};

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,
    /// I2C address and a struct implementing the delay trait.
    /// The `HD44780` is driven through a PCF8574 I2C port expander.
    /// - 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 a PCF8574 I2C to port expander
    /// The IC connections are described in `I2CBus`
    ///
    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<I2C: i2c::Write> HD44780<I2CMCP23008Bus<I2C>> {
    /// Create an instance of a `HD44780` from an i2c write peripheral,
    /// I2C address and a struct implementing the delay trait.
    /// The `HD44780` is driven through a MCP23008 I2C port expander.
    /// - 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 based on MCP23008.
    /// The IC connections are described in `I2CMCP23008Bus`
    ///
    pub fn new_i2c_mcp23008<D: DelayUs<u16> + DelayMs<u8>>(
        i2c_bus: I2C,
        address: u8,
        delay: &mut D,
    ) -> Result<HD44780<I2CMCP23008Bus<I2C>>> {
        let mut hd = HD44780 {
            bus: I2CMCP23008Bus::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`
    ///
    /// ```rust,ignore
    /// lcd.write_char('A');
    /// ```
    pub fn write_char<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        data: char,
        delay: &mut D,
    ) -> Result<()> {
        self.bus.write(data as u8, true, delay)?;

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

        Ok(())
    }

    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);

        /* Taken from Arduino's LiquidCrystal.cpp
        const LCD_FUNCTIONSET : u8 = 0x20;
        const LCD_2LINE : u8 = 0x08;
        const LCD_5X8DOTS : u8 = 0x00;
        let display_function = LCD_FUNCTIONSET | LCD_2LINE | LCD_5X8DOTS;
        self.bus.write(display_function, false, delay)?;
        delay.delay_ms(2);

        // turn the display on with no cursor or blinking default
        const LCD_DISPLAYCONTROL : u8 = 0x08;
        const LCD_DISPLAYON : u8 = 0x04;
        const LCD_BLINKOFF : u8 = 0x00;
        const LCD_CURSOROFF : u8 = 0x00;
        let display_control = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;
        self.bus.write(LCD_DISPLAYCONTROL | display_control, false, delay)?;
        delay.delay_ms(2);

        const LCD_ENTRYLEFT : u8 = 0x02;
        const LCD_ENTRYSHIFTDECREMENT : u8 = 0x00;
        const LCD_ENTRYMODESET : u8 = 0x04;
        self.bus.write(LCD_ENTRYMODESET | LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT, false, delay)?;
        delay.delay_ms(2);
        

        // Clear Display
        const LCD_CLEARDISPLAY : u8 = 0x01;
        self.bus.write(LCD_CLEARDISPLAY, false, delay)?;
        delay.delay_ms(2);
		*/

		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(())
    }

    pub fn write_str<D: DelayUs<u16> + DelayMs<u8>>(
        &mut self,
        string: &str,
        delay: &mut D,
    ) -> Result<()> {
        for c in string.chars() {
            self.write_char(c, delay)?;
        }
        Ok(())
    }

    // Send a byte to the HD44780 by setting the data on the bus and
    // also pulsing the enable pin
    /*fn send_byte(&mut self, data: u8) {
        // Pulse the enable pin
        self.set_bus_bits(data);
        self.pulse_enable();
    }*/

    // 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(())
//    }
//}