il0373 0.2.0

Driver for the IL0373 e-Paper display (EPD) controller, for use with embedded-graphics
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
use crate::command::BufCommand;
use core::fmt::Debug;
use hal;

// Sample code from Good Displays says to hold for 10ms
const RESET_DELAY_MS: u32 = 10;

/// Trait implemented by displays to provide implementation of core functionality.
pub trait DisplayInterface {
    type Error;

    /// Send a command to the controller.
    ///
    /// Prefer calling `execute` on a [Commmand](../command/enum.Command.html) over calling this
    /// directly.
    fn send_command(&mut self, command: u8) -> Result<(), Self::Error>;

    /// Send data for a command.
    fn send_data(&mut self, data: &[u8]) -> Result<(), Self::Error>;

    /// Reset the controller.
    fn reset<D: hal::delay::DelayNs>(&mut self, delay: &mut D);

    /// Wait for the controller to indicate it is not busy.
    fn busy_wait(&mut self);

    //----- Following is only for buffers in RAM
    /// copy display buffer data to epd
    fn epd_update_data(&mut self, layer: u8, nbytes: u16, buf: &[u8]) -> Result<(), Self::Error>;

    //----- Following is only for buffers in SRAM
    /// copy display buffer data to epd from sram
    #[cfg(feature = "sram")]
    fn sram_epd_update_data(
        &mut self,
        layer: u8,
        nbytes: u16,
        start_address: u16,
    ) -> Result<(), Self::Error>;

    /// read data from sram
    #[cfg(feature = "sram")]
    fn sram_read(&mut self, address: u16, data: &mut [u8]) -> Result<(), Self::Error>;

    /// write data to sram
    #[cfg(feature = "sram")]
    fn sram_write(&mut self, address: u16, data: &[u8]) -> Result<(), Self::Error>;

    /// set area in sram to a value, assume nbytes is divisible by 4
    #[cfg(feature = "sram")]
    fn sram_clear(&mut self, address: u16, nbytes: u16, val: u8) -> Result<(), Self::Error>;
}

/// The hardware interface to a display.
///
/// ### Example
///
/// This example uses the Linux implementation of the embedded HAL traits to build a display
/// interface. For a complete example see [the Raspberry Pi Inky pHAT example](https://github.com/wezm/ssd1675/blob/master/examples/raspberry_pi_inky_phat.rs).
///
/// ```ignore
/// extern crate linux_embedded_hal;
/// use linux_embedded_hal::spidev::{self, SpidevOptions};
/// use linux_embedded_hal::sysfs_gpio::Direction;
/// use linux_embedded_hal::Delay;
/// use linux_embedded_hal::{Pin, Spidev};
///
/// extern crate il0373;
/// use il0373::{Builder, Color, Dimensions, Display, GraphicDisplay, Rotation};
///
/// // Configure SPI
/// let mut spi = Spidev::open("/dev/spidev0.0").expect("SPI device");
/// let options = SpidevOptions::new()
///     .bits_per_word(8)
///     .max_speed_hz(4_000_000)
///     .mode(spidev::SPI_MODE_0)
///     .build();
/// spi.configure(&options).expect("SPI configuration");
///
/// // https://pinout.xyz/pinout/inky_phat
/// // Configure Digital I/O Pins
/// let cs = Pin::new(8); // BCM8
/// cs.export().expect("cs export");
/// while !cs.is_exported() {}
/// cs.set_direction(Direction::Out).expect("CS Direction");
/// cs.set_value(1).expect("CS Value set to 1");
///
/// let busy = Pin::new(17); // BCM17
/// busy.export().expect("busy export");
/// while !busy.is_exported() {}
/// busy.set_direction(Direction::In).expect("busy Direction");
///
/// let dc = Pin::new(22); // BCM22
/// dc.export().expect("dc export");
/// while !dc.is_exported() {}
/// dc.set_direction(Direction::Out).expect("dc Direction");
/// dc.set_value(1).expect("dc Value set to 1");
///
/// let reset = Pin::new(27); // BCM27
/// reset.export().expect("reset export");
/// while !reset.is_exported() {}
/// reset
///     .set_direction(Direction::Out)
///     .expect("reset Direction");
/// reset.set_value(1).expect("reset Value set to 1");
///
/// // Build the interface from the pins and SPI device
/// let controller = il0373::Interface::new(spi, cs, busy, dc, reset);

pub struct Interface<SPI, CS, BUSY, DC, RESET> {
    /// SPI interface
    spi: SPI,
    /// Chip Select, low active (output)
    cs: CS,
    /// Active low busy pin (input)
    busy: BUSY,
    /// Data/Command Control Pin (High for data, Low for command) (output)
    dc: DC,
    /// Pin for resetting the controller (output)
    reset: RESET,
}

impl<SPI, CS, BUSY, DC, RESET> Interface<SPI, CS, BUSY, DC, RESET>
where
    SPI: hal::spi::SpiBus,
    CS: hal::digital::OutputPin,
    BUSY: hal::digital::InputPin,
    DC: hal::digital::OutputPin,
    RESET: hal::digital::OutputPin,
{
    /// Create a new Interface from embedded hal traits.
    pub fn new(spi: SPI, pins: (CS, BUSY, DC, RESET)) -> Self {
        Self {
            spi,
            cs: pins.0,
            busy: pins.1,
            dc: pins.2,
            reset: pins.3,
        }
    }

    /// release the spi and pins
    pub fn release(self) -> (SPI, (CS, BUSY, DC, RESET)) {
        (self.spi, (self.cs, self.busy, self.dc, self.reset))
    }

    fn write(&mut self, data: &[u8]) -> Result<(), SPI::Error> {
        self.cs.set_low().ok();
        // Linux has a default limit of 4096 bytes per SPI transfer
        // https://github.com/torvalds/linux/blob/ccda4af0f4b92f7b4c308d3acc262f4a7e3affad/drivers/spi/spidev.c#L93
        if cfg!(target_os = "linux") {
            for data_chunk in data.chunks(4096) {
                self.spi.write(data_chunk)?;
            }
        } else {
            self.spi.write(data)?;
        }

        // Release the controller
        self.cs.set_high().ok();

        Ok(())
    }
}

impl<SPI, CS, BUSY, DC, RESET> DisplayInterface for Interface<SPI, CS, BUSY, DC, RESET>
where
    SPI: hal::spi::SpiBus,
    CS: hal::digital::OutputPin,
    CS::Error: Debug,
    BUSY: hal::digital::InputPin,
    DC: hal::digital::OutputPin,
    DC::Error: Debug,
    RESET: hal::digital::OutputPin,
    RESET::Error: Debug,
{
    type Error = SPI::Error;

    fn reset<D: hal::delay::DelayNs>(&mut self, delay: &mut D) {
        // do a hardware reset 3 times
        self.reset.set_low().unwrap();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_high().unwrap();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_low().unwrap();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_high().unwrap();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_low().unwrap();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_high().unwrap();
        delay.delay_ms(RESET_DELAY_MS);
    }

    fn send_command(&mut self, command: u8) -> Result<(), Self::Error> {
        self.dc.set_low().unwrap();
        self.write(&[command])?;
        self.dc.set_high().unwrap();
        Ok(())
    }

    fn send_data(&mut self, data: &[u8]) -> Result<(), Self::Error> {
        self.dc.set_high().unwrap();
        self.write(data)
    }

    #[cfg(feature = "sram")]
    fn sram_read(&mut self, _address: u16, _data: &mut [u8]) -> Result<(), Self::Error> {
        panic!()
    }

    #[cfg(feature = "sram")]
    fn sram_write(&mut self, _address: u16, _data: &[u8]) -> Result<(), Self::Error> {
        panic!()
    }

    #[cfg(feature = "sram")]
    fn sram_clear(&mut self, _address: u16, _nbytes: u16, _val: u8) -> Result<(), Self::Error> {
        panic!()
    }

    #[cfg(feature = "sram")]
    fn sram_epd_update_data(
        &mut self,
        _layer: u8,
        _nbytes: u16,
        _start_address: u16,
    ) -> Result<(), Self::Error> {
        panic!()
    }

    fn epd_update_data(&mut self, layer: u8, nbytes: u16, buf: &[u8]) -> Result<(), Self::Error> {
        let sz: usize = nbytes.into();
        if layer == 0 {
            BufCommand::WriteBlackData(&buf[..sz]).execute(self)
        } else {
            BufCommand::WriteRedData(&buf[..sz]).execute(self)
        }
    }

    fn busy_wait(&mut self) {
        while match self.busy.is_high() {
            Ok(x) => x,
            _ => false,
        } {}
    }
}

//const MCPSRAM_RDSR: u8 = 0x05;
#[cfg(feature = "sram")]
const MCPSRAM_READ: u8 = 0x03;
#[cfg(feature = "sram")]
const MCPSRAM_WRITE: u8 = 0x02;
#[cfg(feature = "sram")]
const MCPSRAM_WRSR: u8 = 0x01;
#[cfg(feature = "sram")]
const K640_SEQUENTIAL_MODE: u8 = 1 << 6;

#[cfg(feature = "sram")]
pub struct SpiSramBus<SPI, EPDCS, SRAMCS> {
    spi: SPI,
    epd_cs: EPDCS,
    sram_cs: SRAMCS,
}

#[cfg(feature = "sram")]
impl<SPI, EPDCS, SRAMCS> SpiSramBus<SPI, EPDCS, SRAMCS>
where
    SPI: hal::spi::SpiBus,
    EPDCS: hal::digital::OutputPin,
    SRAMCS: hal::digital::OutputPin,
{
    /// create a new SpiSramBus from embedded hal traits
    pub fn new(spi: SPI, mut pins: (EPDCS, SRAMCS)) -> SpiSramBus<SPI, EPDCS, SRAMCS> {
        pins.0.set_high().ok();
        pins.1.set_high().ok();
        SpiSramBus {
            spi,
            epd_cs: pins.0,
            sram_cs: pins.1,
        }
    }

    /// release the spi and cs pins
    pub fn release(self) -> (SPI, (EPDCS, SRAMCS)) {
        (self.spi, (self.epd_cs, self.sram_cs))
    }

    /// initialize sram device
    pub fn sram_init(&mut self) -> Result<(), SPI::Error> {
        self.sram_cs.set_low().ok();
        self.spi.write(&[0xFF, 0xFF, 0xFF])?;
        self.sram_cs.set_high().ok();
        Ok(())
    }

    /// set sram device to sequential
    pub fn sram_seq(&mut self) -> Result<(), SPI::Error> {
        self.sram_cs.set_low().ok();
        self.spi.write(&[MCPSRAM_WRSR, K640_SEQUENTIAL_MODE])?;
        self.sram_cs.set_high().ok();
        Ok(())
    }

    /// write to the sram
    pub fn sram_write(&mut self, address: u16, data: &[u8]) -> Result<(), SPI::Error> {
        self.sram_cs.set_low().ok();
        self.spi
            .write(&[MCPSRAM_WRITE, (address >> 8) as u8, (address & 0xFF) as u8])?;
        self.spi.write(data)?;
        self.sram_cs.set_high().ok();
        Ok(())
    }

    /// read the sram
    pub fn sram_read(&mut self, address: u16, data: &mut [u8]) -> Result<(), SPI::Error> {
        self.sram_cs.set_low().ok();
        self.spi
            .write(&[MCPSRAM_READ, (address >> 8) as u8, (address & 0xFF) as u8])?;
        self.spi.read(data)?;
        self.sram_cs.set_high().ok();
        Ok(())
    }

    /// erase buffer in sram, len is expected to be divisible by 4, panics otherwise
    pub fn sram_erase(&mut self, address: u16, len: u16, val: u8) -> Result<(), SPI::Error> {
        if len % 4 != 0 {
            panic!("sram_erase expects a len divisible by 4");
        }
        self.sram_cs.set_low().ok();
        self.spi
            .write(&[MCPSRAM_WRITE, (address >> 8) as u8, (address & 0xFF) as u8])?;
        for _i in 0..len / 4 {
            self.spi.write(&mut [val, val, val, val])?;
        }
        self.sram_cs.set_high().ok();
        Ok(())
    }

    /// start a buffer transfer from the SRAM to the EPD. This needs the beginning address
    /// in the SRAM, and the location where they will be sent in the EPD.
    /// While the location is sent to the EPD, the first byte will be pulled from
    /// the SRAM at the address specified, this is passed to the sram_epd_move_body fn
    pub fn sram_epd_move_header(
        &mut self,
        address: u16,
        epd_location: u8,
    ) -> Result<u8, SPI::Error> {
        self.sram_cs.set_low().ok();
        // send address and get first byte of data
        self.spi
            .write(&[MCPSRAM_READ, (address >> 8) as u8, (address & 0xFF) as u8])?;
        self.epd_cs.set_low().ok();
        let mut loc = [epd_location];
        self.spi.read(&mut loc)?;
        Ok(loc[0])
    }

    /// given the first byte from SRAM from sram_epd_move_header, transfer the rest
    /// of the bytes to the EPD. These functions are split up because another pin
    /// must be pulled low between them in the protocol
    pub fn sram_epd_move_body(&mut self, ch: u8, data_len: u16) -> Result<(), SPI::Error> {
        let mut c = [ch];
        // have to copy byte by byte
        for _i in 0..data_len {
            let recvd = c[0];
            self.spi.transfer(&mut c, &[recvd])?;
        }
        self.epd_cs.set_high().ok();
        self.sram_cs.set_high().ok();
        Ok(())
    }
    /// write to the epaper display
    pub fn epd_write(&mut self, data: &[u8]) -> Result<(), SPI::Error> {
        self.epd_cs.set_low().ok();
        self.spi.write(data)?;
        self.epd_cs.set_high().ok();
        Ok(())
    }
}

#[cfg(feature = "sram")]
pub struct SramDisplayInterface<SPI, EPDCS, SRAMCS, BUSY, DC, RESET> {
    spi_bus: SpiSramBus<SPI, EPDCS, SRAMCS>,
    busy: BUSY,
    dc: DC,
    reset: RESET,
}

#[cfg(feature = "sram")]
impl<SPI, EPDCS, SRAMCS, BUSY, DC, RESET> SramDisplayInterface<SPI, EPDCS, SRAMCS, BUSY, DC, RESET>
where
    SPI: hal::spi::SpiBus,
    EPDCS: hal::digital::OutputPin,
    SRAMCS: hal::digital::OutputPin,
    BUSY: hal::digital::InputPin,
    DC: hal::digital::OutputPin,
    RESET: hal::digital::OutputPin,
{
    /// create a display interface from the embedded hal
    pub fn new(
        spi_bus: SpiSramBus<SPI, EPDCS, SRAMCS>,
        mut pins: (BUSY, DC, RESET),
    ) -> SramDisplayInterface<SPI, EPDCS, SRAMCS, BUSY, DC, RESET> {
        // dc inactive low
        pins.1.set_low().ok();
        // reset inactive high
        pins.2.set_high().ok();
        SramDisplayInterface {
            spi_bus,
            busy: pins.0,
            dc: pins.1,
            reset: pins.2,
        }
    }

    /// release the spibus and all the associated pins
    pub fn release(self) -> (SpiSramBus<SPI, EPDCS, SRAMCS>, (BUSY, DC, RESET)) {
        (self.spi_bus, (self.busy, self.dc, self.reset))
    }
}

#[cfg(feature = "sram")]
impl<SPI, EPDCS, SRAMCS, BUSY, DC, RESET> DisplayInterface
    for SramDisplayInterface<SPI, EPDCS, SRAMCS, BUSY, DC, RESET>
where
    SPI: hal::spi::SpiBus,
    EPDCS: hal::digital::OutputPin,
    SRAMCS: hal::digital::OutputPin,
    BUSY: hal::digital::InputPin,
    DC: hal::digital::OutputPin,
    RESET: hal::digital::OutputPin,
{
    type Error = SPI::Error;

    fn send_command(&mut self, command: u8) -> Result<(), Self::Error> {
        self.dc.set_low().ok();
        self.spi_bus.epd_write(&mut [command])
    }

    fn send_data(&mut self, data: &[u8]) -> Result<(), Self::Error> {
        self.dc.set_high().ok();
        self.spi_bus.epd_write(data)
    }

    fn reset<D: hal::delay::DelayNs>(&mut self, delay: &mut D) {
        // setup the sram
        self.spi_bus.sram_init().ok();

        // do a hardware reset 3 times
        self.reset.set_low().ok();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_high().ok();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_low().ok();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_high().ok();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_low().ok();
        delay.delay_ms(RESET_DELAY_MS);
        self.reset.set_high().ok();
        delay.delay_ms(RESET_DELAY_MS);

        self.spi_bus.sram_seq().ok();
    }

    fn busy_wait(&mut self) {
        while match self.busy.is_high() {
            Ok(x) => x,
            _ => false,
        } {}
    }

    fn epd_update_data(
        &mut self,
        _layer: u8,
        _nbytes: u16,
        _buf: &[u8],
    ) -> Result<(), Self::Error> {
        panic!()
    }

    fn sram_read(&mut self, address: u16, data: &mut [u8]) -> Result<(), Self::Error> {
        self.spi_bus.sram_read(address, data)
    }

    fn sram_write(&mut self, address: u16, data: &[u8]) -> Result<(), Self::Error> {
        self.spi_bus.sram_write(address, data)
    }

    fn sram_clear(&mut self, address: u16, nbytes: u16, val: u8) -> Result<(), Self::Error> {
        self.spi_bus.sram_erase(address, nbytes, val)
    }

    fn sram_epd_update_data(
        &mut self,
        layer: u8,
        nbytes: u16,
        start_address: u16,
    ) -> Result<(), Self::Error> {
        let epd_location = if layer == 0 { 0x10 } else { 0x13 };
        self.dc.set_low().ok();
        let ch = self
            .spi_bus
            .sram_epd_move_header(start_address, epd_location)?;
        self.dc.set_high().ok();
        self.spi_bus.sram_epd_move_body(ch, nbytes)
    }
}