gdeh0154d67 0.3.0

Driver for the GDEH0154D67 E-Paper display.
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
//! Simple SPI driver for the GDEH0154D67 E-Paper display.
//! This crate is a `no_std` library that provides an interface compatible with [embedded-hal-1.0.0-rc.1](https://docs.rs/embedded-hal/1.0.0-rc.1/embedded_hal/).
//! It is also designed to be used together with [embedded-graphics](https://docs.rs/embedded-graphics/latest/embedded_graphics/).
//! It ensures a correct initialization and a consistent state at every moment by enforcing design
//! constrains at compile time using zero cost abstractions.
//!
//! The crate has a `std` feature for use in fully `std` environments, the only effect of which is that [`error::Error`] implements `std:error::Error`.
//! There is also the `heap_buffer` feature, which allocates the internal graphics buffer on the heap, preventing stack overflows on more limited platorms.
//! This feature of course requires an allocator.
#![no_std]

#[cfg(feature = "heap_buffer")]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "heap_buffer")]
use alloc::boxed::Box;

mod command;
pub mod error;

use command::*;
use error::Error;

use embedded_graphics::{
    draw_target::DrawTarget, geometry::OriginDimensions, geometry::Size, pixelcolor::BinaryColor,
    Pixel,
};

use embedded_hal::digital::{InputPin, OutputPin};
#[cfg(feature = "async")]
use embedded_hal_async::{spi::SpiDevice, digital::Wait};
#[cfg(feature = "async")]
use embedded_hal_async::delay::DelayNs;
#[cfg(not(feature = "async"))]
use embedded_hal::spi::SpiDevice;
#[cfg(not(feature = "async"))]
use embedded_hal::delay::DelayNs;

/// Main structure of the library, used to initialize and control de display.
pub struct GDEH0154D67<SPI, DC, RST, BSY, DLY, S> {
    interface: SPI,
    #[cfg(feature = "heap_buffer")]
    buffer: Box<Buffer>,
    #[cfg(not(feature = "heap_buffer"))]
    buffer: Buffer,
    dc: DC,
    reset: RST,
    busy: BSY,
    delay: DLY,
    #[allow(dead_code)]
    state: S,
}

/// Sets the display as initialized, only after calling the method `init()`
/// the display is considered initialized.
pub struct Initialized;
/// Sets the display as not initialized. This state occurs when acquiring
/// a new instance of `GDEH0154D67` or after doing a `reset()` of the display.
pub struct NotInitialized;

const PIXELS_X: usize = 200;
const PIXELS_Y: usize = 200;
/// Struct that stores the binary color of the pixels that will be set when the
/// next display update is performed
struct Buffer {
    pixels: [u8; PIXELS_X*PIXELS_Y/8],
    flags: [u8; PIXELS_X*PIXELS_Y/8],
}

impl<SPI, DC, RST, BSY, DLY> GDEH0154D67<SPI, DC, RST, BSY, DLY, NotInitialized>
where
    SPI: SpiDevice,
    DC: OutputPin,
    RST: OutputPin,
    BSY: InputPin,
    DLY: DelayNs,
{
    /// Acquires the SPI interface and the control GPIO pins. It also performs
    /// a hardware reset on the device.
    pub fn new(interface: SPI, dc: DC, reset: RST, busy: BSY, delay: DLY) -> Result<Self, Error> {
        Ok(Self {
            interface,
            #[cfg(feature = "heap_buffer")]
            buffer: Box::new(Buffer {
                pixels: [0; PIXELS_X*PIXELS_Y/8],
                flags: [0; PIXELS_X*PIXELS_Y/8],
            }),
            #[cfg(not(feature = "heap_buffer"))]
            buffer: Buffer {
                pixels: [0; PIXELS_X*PIXELS_Y/8],
                flags: [0; PIXELS_X*PIXELS_Y/8],
            },
            dc,
            reset,
            busy,
            delay,
            state: NotInitialized,
        })
    }

    /// Releases SPI interface and control pins.
    pub fn release(self) -> Result<(SPI, DC, RST, BSY), Error> {
        Ok((self.interface, self.dc, self.reset, self.busy))
    }
}

#[cfg(not(feature = "async"))]
mod blocking {
    use super::*;
    use embedded_hal::spi::SpiDevice;

    impl<SPI, DC, RST, BSY, DLY> GDEH0154D67<SPI, DC, RST, BSY, DLY, NotInitialized>
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
        BSY: InputPin,
        DLY: DelayNs,
    {
        /// Sets the display into an initialized state. It is required to call this
        /// method once before any display update can be done.
        pub fn init(mut self) -> Result<GDEH0154D67<SPI, DC, RST, BSY, DLY, Initialized>, Error> {
            // First toggle the hardware reset line
            self.reset()?;
    
            // 000 -> normal
            // 011 -> upside down
            DriverOutputControl([0xc7, 0x00, 0b000])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            DataEntryModeSetting([0b011])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            SetRamXAddressStartEndPosition([0x00, 0x18])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            SetRamYAddressStartEndPosition([0x00, 0x00, 0xc7, 0x00])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            TemperatureSensorWrite([0x43, 0x20])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            DisplayUpdateControl2([0xb1])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            MasterActivation
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            self.busy_block().unwrap();
            Ok(GDEH0154D67 {
                interface: self.interface,
                buffer: self.buffer,
                dc: self.dc,
                reset: self.reset,
                busy: self.busy,
                delay: self.delay,
                state: Initialized,
            })
        }
    
    }
    
    impl<SPI, DC, RST, BSY, DLY> GDEH0154D67<SPI, DC, RST, BSY, DLY, Initialized>
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
        BSY: InputPin,
        DLY: DelayNs,
    {
        /// Writes into the display's RAM only those contents of `Buffer`
        /// that have been modified.
        pub fn partial_update(&mut self) -> Result<(), Error> {
            for (idx, val) in self
                .buffer
                .flags
                .chunks_mut(1)
                .enumerate()
                .filter(|(_, val)| val[0] != 0)
            {
                let idx = idx as usize;
                let (x, y) = index2address(idx);
                SetRamXAddressPosition([x])
                    .send(&mut self.interface, &mut self.dc)
                    .unwrap();
                SetRamYAddressPosition([y, 0x00])
                    .send(&mut self.interface, &mut self.dc)
                    .unwrap();
    
                let raw_data = self.buffer.pixels;
                WriteRam(&[raw_data[idx]])
                    .send(&mut self.interface, &mut self.dc)
                    .unwrap();
    
                val[0] = 0;
            }
    
            DisplayUpdateControl2([0xc7])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            MasterActivation
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            
            self.busy_block()
        }
    
        /// Writes all the contents of the `Buffer` into the RAM of the display and
        /// performs a display update.
        pub fn full_update(&mut self) -> Result<(), Error> {
            SetRamXAddressPosition([0x00])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            SetRamYAddressPosition([0x00, 0x00])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            WriteRam(&self.buffer.pixels)
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            DisplayUpdateControl2([0xc7])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            MasterActivation
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            self.busy_block()
        }
    
        /// Releases SPI interface and control pins.
        pub fn release(self) -> Result<(SPI, DC, RST, BSY), Error> {
            let display = self.turn_off().unwrap();
            Ok((display.interface, display.dc, display.reset, display.busy))
        }
    }
    
    impl<SPI, DC, RST, BSY, DLY, S> GDEH0154D67<SPI, DC, RST, BSY, DLY, S>
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
        BSY: InputPin,
        DLY: DelayNs,
    {
        /// Sends the display into deep sleep mode.
        pub fn turn_off(mut self) -> Result<GDEH0154D67<SPI, DC, RST, BSY, DLY, NotInitialized>, Error> {
            DeepSleepMode([0x1])
                .send(&mut self.interface, &mut self.dc)
                .unwrap();
            Ok(GDEH0154D67 {
                interface: self.interface,
                buffer: self.buffer,
                dc: self.dc,
                reset: self.reset,
                busy: self.busy,
                delay: self.delay,
                state: NotInitialized,
            })
        }
    
        /// Performs a hardware reset of the display.
        fn reset(&mut self) -> Result<(), Error> {
            self.reset.set_low().unwrap();
            DelayNs::delay_ms(&mut self.delay, 10);
            self.reset.set_high().unwrap();
            DelayNs::delay_ms(&mut self.delay, 10);
            SwReset.send(&mut self.interface, &mut self.dc).unwrap();
            self.busy_block()
        }
    
        /// Blocks while the display is updating.
        fn busy_block(&mut self) -> Result<(), Error> {
            while self.busy.is_high().unwrap() {
                DelayNs::delay_ms(&mut self.delay, 10);
            }
            Ok(())
        }
    }
}

#[cfg(feature = "async")]
mod asynchronous {
    use super::*;

    impl<SPI, DC, RST, BSY, DLY> GDEH0154D67<SPI, DC, RST, BSY, DLY, NotInitialized>
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
        BSY: InputPin + Wait,
        DLY: DelayNs,
    {
        /// Sets the display into an initialized state. It is required to call this
        /// method once before any display update can be done.
        pub async fn init(mut self) -> Result<GDEH0154D67<SPI, DC, RST, BSY, DLY, Initialized>, Error> {
            // First toggle the hardware reset line
            self.reset().await?;
    
            // 000 -> normal
            // 011 -> upside down
            DriverOutputControl([0xc7, 0x00, 0b000])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            DataEntryModeSetting([0b011])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            SetRamXAddressStartEndPosition([0x00, 0x18])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            SetRamYAddressStartEndPosition([0x00, 0x00, 0xc7, 0x00])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            TemperatureSensorWrite([0x43, 0x20])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            DisplayUpdateControl2([0xb1])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            MasterActivation
                .send(&mut self.interface, &mut self.dc)
                .await?;
            self.busy_block().await?;
            Ok(GDEH0154D67 {
                interface: self.interface,
                buffer: self.buffer,
                dc: self.dc,
                reset: self.reset,
                busy: self.busy,
                delay: self.delay,
                state: Initialized,
            })
        }
    }
    
    impl<SPI, DC, RST, BSY, DLY> GDEH0154D67<SPI, DC, RST, BSY, DLY, Initialized>
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
        BSY: InputPin + Wait,
        DLY: DelayNs,
    {
        /// Writes into the display's RAM only those contents of `Buffer`
        /// that have been modified.
        pub async fn partial_update(&mut self) -> Result<(), Error> {
            for (idx, val) in self
                .buffer
                .flags
                .chunks_mut(1)
                .enumerate()
                .filter(|(_, val)| val[0] != 0)
            {
                let idx = idx as usize;
                let (x, y) = index2address(idx);
                SetRamXAddressPosition([x])
                    .send(&mut self.interface, &mut self.dc)
                    .await?;
                SetRamYAddressPosition([y, 0x00])
                    .send(&mut self.interface, &mut self.dc)
                    .await?;
    
                let raw_data = self.buffer.pixels;
                WriteRam(&[raw_data[idx]])
                    .send(&mut self.interface, &mut self.dc)
                    .await?;
    
                val[0] = 0;
            }
    
            DisplayUpdateControl2([0xc7])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            MasterActivation
                .send(&mut self.interface, &mut self.dc)
                .await?;
            self.busy_block().await
        }
    
        /// Writes all the contents of the `Buffer` into the RAM of the display and
        /// performs a display update.
        pub async fn full_update(&mut self) -> Result<(), Error> {
            SetRamXAddressPosition([0x00])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            SetRamYAddressPosition([0x00, 0x00])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            WriteRam(&self.buffer.pixels)
                .send(&mut self.interface, &mut self.dc)
                .await?;
            DisplayUpdateControl2([0xc7])
                .send(&mut self.interface, &mut self.dc)
                .await?;
            MasterActivation
                .send(&mut self.interface, &mut self.dc)
                .await?;
            self.busy_block().await
        }
    
        /// Releases SPI interface and control pins.
        pub async fn release(self) -> Result<(SPI, DC, RST, BSY), Error> {
            let display = self.turn_off().await?;
            Ok((display.interface, display.dc, display.reset, display.busy))
        }
    }
    
    impl<SPI, DC, RST, BSY, DLY, S> GDEH0154D67<SPI, DC, RST, BSY, DLY, S>
    where
        SPI: SpiDevice,
        DC: OutputPin,
        RST: OutputPin,
        BSY: InputPin + Wait,
        DLY: DelayNs,
    {
        /// Sends the display into deep sleep mode.
        pub async fn turn_off(mut self) -> Result<GDEH0154D67<SPI, DC, RST, BSY, DLY, NotInitialized>, Error> {
            DeepSleepMode([0x1])
                .send(&mut self.interface, &mut self.dc)
                .await.unwrap();
            Ok(GDEH0154D67 {
                interface: self.interface,
                buffer: self.buffer,
                dc: self.dc,
                reset: self.reset,
                busy: self.busy,
                delay: self.delay,
                state: NotInitialized,
            })
        }
    
        /// Performs a hardware reset of the display.
        async fn reset(&mut self) -> Result<(), Error> {
            self.reset.set_low().unwrap();
            DelayNs::delay_ms(&mut self.delay, 10).await;
            self.reset.set_high().unwrap();
            DelayNs::delay_ms(&mut self.delay, 10).await;
            SwReset.send(&mut self.interface, &mut self.dc).await?;
            self.busy_block().await
        }
    
        /// Blocks while the display is updating.
        async fn busy_block(&mut self) -> Result<(), Error> {
            self.busy.wait_for_low().await.unwrap();
            Ok(())
        }
    }
}

impl<SPI, DC, RST, BSY, DLY> DrawTarget for GDEH0154D67<SPI, DC, RST, BSY, DLY, Initialized>
where
    SPI: SpiDevice,
    DC: OutputPin,
    RST: OutputPin,
    BSY: InputPin,
    DLY: DelayNs,
{
    type Color = BinaryColor;
    type Error = Error;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = Pixel<Self::Color>>,
    {
        for Pixel(coord, color) in pixels.into_iter() {
            // Check if the pixel coordinates are out of bounds (negative or greater than
            // (PIXELS_X, PIXELS_Y)). `DrawTarget` implementation are required to discard any out of bounds
            // pixels without returning an error or causing a panic.
            const MAX_X_IDX: u32 = PIXELS_X as u32 - 1;
            const MAX_Y_IDX: u32 = PIXELS_Y as u32 - 1;
            if let Ok((x @ 0..=MAX_X_IDX, y @ 0..=MAX_Y_IDX)) = coord.try_into() {
                // Calculate the index in the buffer.
                let index = pixel2buffer(x, y);
                let bit_index = index%8;
                let mask = 0b10000000 >> bit_index;
                let byte_index = index/8;
                let color_val_u8 = u8::from(color.is_on()) << 7;

                self.buffer.pixels[byte_index] = (self.buffer.pixels[byte_index] & !mask) | color_val_u8 >> bit_index;
                self.buffer.flags[byte_index] = (self.buffer.flags[byte_index] & !mask) | 0b10000000 >> bit_index;
            }
        }
        
        Ok(())
    }
}

impl<SPI, DC, RST, BSY, DLY> OriginDimensions for GDEH0154D67<SPI, DC, RST, BSY, DLY, Initialized> {
    fn size(&self) -> Size {
        Size::new(PIXELS_X as u32, PIXELS_Y as u32)
    }
}

fn pixel2buffer(x: u32, y: u32) -> usize {
    (x + y * PIXELS_X as u32).try_into().unwrap()
}

fn index2address(i: usize) -> (u8, u8) {
    ((i % (PIXELS_Y/8)).try_into().unwrap(), (i / (PIXELS_Y/8)).try_into().unwrap())
}