weact-studio-epd 0.1.2

Unofficial driver for WeAct Studio E-paper modules
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
use core::iter;

#[cfg(not(feature = "blocking"))]
use display_interface::AsyncWriteOnlyDataCommand;
#[cfg(feature = "blocking")]
use display_interface::WriteOnlyDataCommand;

#[cfg(feature = "blocking")]
use embedded_hal::delay::DelayNs;
#[cfg(not(feature = "blocking"))]
use embedded_hal_async::{delay::DelayNs, digital::Wait};

use display_interface::DataFormat;
use embedded_hal::digital::{InputPin, OutputPin};

#[cfg(feature = "graphics")]
use crate::graphics::Display;
use crate::{
    color::{self, ColorType},
    command, flag, lut, Color, Result, TriColor,
};

/// Display driver for the WeAct Studio 2.9 inch B/W display.
pub type WeActStudio290BlackWhiteDriver<DI, BSY, RST, DELAY> =
    DisplayDriver<DI, BSY, RST, DELAY, 128, 128, 296, Color>;
/// Display driver for the WeAct Studio 2.9 inch Tri-Color display.
pub type WeActStudio290TriColorDriver<DI, BSY, RST, DELAY> =
    DisplayDriver<DI, BSY, RST, DELAY, 128, 128, 296, TriColor>;
/// Display driver for the WeAct Studio 2.13 inch B/W display.
pub type WeActStudio213BlackWhiteDriver<DI, BSY, RST, DELAY> =
    DisplayDriver<DI, BSY, RST, DELAY, 128, 122, 250, Color>;
/// Display driver for the WeAct Studio 2.13 inch Tri-Color display.
pub type WeActStudio213TriColorDriver<DI, BSY, RST, DELAY> =
    DisplayDriver<DI, BSY, RST, DELAY, 128, 122, 250, TriColor>;

/// The main driver struct that manages the communication with the display.
///
/// You probably want to use one of the display-specific type aliases instead.
pub struct DisplayDriver<
    DI,
    BSY,
    RST,
    DELAY,
    const WIDTH: u32,
    const VISIBLE_WIDTH: u32,
    const HEIGHT: u32,
    C,
> {
    _color: core::marker::PhantomData<C>,
    interface: DI,
    busy: BSY,
    reset: RST,
    delay: DELAY,
    // State
    using_partial_mode: bool,
    initial_full_refresh_done: bool,
}

#[maybe_async_cfg::maybe(
    sync(
        feature = "blocking",
        keep_self,
        idents(
            AsyncWriteOnlyDataCommand(sync = "WriteOnlyDataCommand"),
            Wait(sync = "InputPin")
        )
    ),
    async(not(feature = "blocking"), keep_self)
)]
impl<DI, BSY, RST, DELAY, const WIDTH: u32, const VISIBLE_WIDTH: u32, const HEIGHT: u32, C>
    DisplayDriver<DI, BSY, RST, DELAY, WIDTH, VISIBLE_WIDTH, HEIGHT, C>
where
    DI: AsyncWriteOnlyDataCommand,
    BSY: InputPin + Wait,
    RST: OutputPin,
    DELAY: DelayNs,
    C: ColorType,
{
    const RESET_DELAY_MS: u32 = 50;

    /// Create a new display driver.
    ///
    /// Use [`Self::init`] to initialize the display.
    pub fn new(interface: DI, busy: BSY, reset: RST, delay: DELAY) -> Self {
        Self {
            _color: core::marker::PhantomData,
            interface,
            busy,
            reset,
            delay,
            using_partial_mode: false,
            initial_full_refresh_done: false,
        }
    }

    /// Initialize the display
    pub async fn init(&mut self) -> Result<()> {
        self.hw_reset().await;
        self.command(command::SW_RESET).await?;
        self.delay.delay_ms(10).await;
        self.wait_until_idle().await;
        self.command_with_data(
            command::DRIVER_CONTROL,
            &[(HEIGHT - 1) as u8, ((HEIGHT - 1) >> 8) as u8, 0x00],
        )
        .await?;
        self.command_with_data(command::DATA_ENTRY_MODE, &[flag::DATA_ENTRY_INCRY_INCRX])
            .await?;
        self.command_with_data(
            command::BORDER_WAVEFORM_CONTROL,
            &[flag::BORDER_WAVEFORM_FOLLOW_LUT | flag::BORDER_WAVEFORM_LUT1],
        )
        .await?;
        self.command_with_data(command::DISPLAY_UPDATE_CONTROL, &[0x00, 0x80])
            .await?;
        self.command_with_data(command::TEMP_CONTROL, &[flag::INTERNAL_TEMP_SENSOR])
            .await?;
        self.use_full_frame().await?;
        self.wait_until_idle().await;
        Ok(())
    }

    /// Perform a hardware reset of the display.
    pub async fn hw_reset(&mut self) {
        self.reset.set_low().unwrap();
        self.delay.delay_ms(Self::RESET_DELAY_MS).await;
        self.reset.set_high().unwrap();
        self.delay.delay_ms(Self::RESET_DELAY_MS).await;
    }

    /// Write to the B/W buffer.
    pub async fn write_bw_buffer(&mut self, buffer: &[u8]) -> Result<()> {
        self.use_full_frame().await?;
        self.command_with_data(command::WRITE_BW_DATA, buffer)
            .await?;
        Ok(())
    }

    /// Write to the red buffer.
    ///
    /// On B/W displays this buffer is used for fast refreshes.
    pub async fn write_red_buffer(&mut self, buffer: &[u8]) -> Result<()> {
        self.use_full_frame().await?;
        self.command_with_data(command::WRITE_RED_DATA, buffer)
            .await?;
        Ok(())
    }

    /// Write to the B/W buffer at the given position.
    ///
    /// `x`, and `width` must be multiples of 8.
    pub async fn write_partial_bw_buffer(
        &mut self,
        buffer: &[u8],
        x: u32,
        y: u32,
        width: u32,
        height: u32,
    ) -> Result<()> {
        self.use_partial_frame(x, y, width, height).await?;
        self.command_with_data(command::WRITE_BW_DATA, buffer)
            .await?;
        Ok(())
    }

    /// Write to the red buffer at the given position.
    ///
    /// `x`, and `width` must be multiples of 8.
    ///
    /// On B/W displays this buffer is used for fast refreshes.
    pub async fn write_partial_red_buffer(
        &mut self,
        buffer: &[u8],
        x: u32,
        y: u32,
        width: u32,
        height: u32,
    ) -> Result<()> {
        self.use_partial_frame(x, y, width, height).await?;
        self.command_with_data(command::WRITE_RED_DATA, buffer)
            .await?;
        Ok(())
    }

    /// Make the whole black and white frame on the display driver white.
    pub async fn clear_bw_buffer(&mut self) -> Result<()> {
        self.use_full_frame().await?;

        // TODO: allow non-white background color
        let color = color::Color::White.byte_value().0;

        self.command(command::WRITE_BW_DATA).await?;
        self.data_x_times(color, WIDTH / 8 * HEIGHT).await?;
        Ok(())
    }

    /// Make the whole red frame on the display driver white.
    ///
    /// On B/W displays this buffer is used for fast refreshes.
    pub async fn clear_red_buffer(&mut self) -> Result<()> {
        self.use_full_frame().await?;

        // TODO: allow non-white background color
        let color = color::Color::White.byte_value().1;

        self.command(command::WRITE_RED_DATA).await?;
        self.data_x_times(color, WIDTH / 8 * HEIGHT).await?;
        Ok(())
    }

    /// Start a full refresh of the display.
    pub async fn full_refresh(&mut self) -> Result<()> {
        self.initial_full_refresh_done = true;
        self.using_partial_mode = false;

        self.command_with_data(command::UPDATE_DISPLAY_CTRL2, &[flag::DISPLAY_MODE_1])
            .await?;
        self.command(command::MASTER_ACTIVATE).await?;
        self.wait_until_idle().await;
        Ok(())
    }

    /// Put the device into deep-sleep mode.
    /// You will need to call [`Self::wake_up`] before you can draw to the screen again.
    pub async fn sleep(&mut self) -> Result<()> {
        // We can't use send_with_data, because the data function will also wait_until_idle,
        // but after sending the deep sleep command, busy will not be cleared,
        // maybe as a feature to signal the device won't be able to process further instuctions until woken again.
        self.interface
            .send_commands(DataFormat::U8(&[command::DEEP_SLEEP]))
            .await?;
        self.interface
            .send_data(DataFormat::U8(&[flag::DEEP_SLEEP_MODE_1]))
            .await?;
        Ok(())
    }

    /// Wake the device up from deep-sleep mode.
    pub async fn wake_up(&mut self) -> Result<()> {
        // HW reset seems to be enough in deep sleep mode 1, no need to call init again
        self.hw_reset().await;
        Ok(())
    }

    async fn use_full_frame(&mut self) -> Result<()> {
        self.use_partial_frame(0, 0, WIDTH, HEIGHT).await?;
        Ok(())
    }

    async fn use_partial_frame(&mut self, x: u32, y: u32, width: u32, height: u32) -> Result<()> {
        // TODO: make sure positions are byte-aligned
        self.set_ram_area(x, y, x + width - 1, y + height - 1)
            .await?;
        self.set_ram_counter(x, y).await?;
        Ok(())
    }

    async fn set_ram_area(
        &mut self,
        start_x: u32,
        start_y: u32,
        end_x: u32,
        end_y: u32,
    ) -> Result<()> {
        assert!(start_x < end_x);
        assert!(start_y < end_y);

        self.command_with_data(
            command::SET_RAMXPOS,
            &[(start_x >> 3) as u8, (end_x >> 3) as u8],
        )
        .await?;

        self.command_with_data(
            command::SET_RAMYPOS,
            &[
                start_y as u8,
                (start_y >> 8) as u8,
                end_y as u8,
                (end_y >> 8) as u8,
            ],
        )
        .await?;
        Ok(())
    }

    async fn set_ram_counter(&mut self, x: u32, y: u32) -> Result<()> {
        // x is positioned in bytes, so the last 3 bits which show the position inside a byte in the ram
        // aren't relevant
        self.command_with_data(command::SET_RAMX_COUNTER, &[(x >> 3) as u8])
            .await?;

        // 2 Databytes: A[7:0] & 0..A[8]
        self.command_with_data(command::SET_RAMY_COUNTER, &[y as u8, (y >> 8) as u8])
            .await?;
        Ok(())
    }

    /// Send a command to the display.
    async fn command(&mut self, command: u8) -> Result<()> {
        self.interface
            .send_commands(DataFormat::U8(&[command]))
            .await?;
        Ok(())
    }

    /// Send an array of bytes to the display.
    async fn data(&mut self, data: &[u8]) -> Result<()> {
        self.interface.send_data(DataFormat::U8(data)).await?;
        self.wait_until_idle().await;
        Ok(())
    }

    /// Waits until device isn't busy anymore (busy == HIGH).
    async fn wait_until_idle(&mut self) {
        #[cfg(feature = "blocking")]
        while self.busy.is_high().unwrap_or(true) {
            self.delay.delay_ms(1)
        }

        #[cfg(not(feature = "blocking"))]
        let _ = self.busy.wait_for_low().await;
    }

    /// Sending a command and the data belonging to it.
    async fn command_with_data(&mut self, command: u8, data: &[u8]) -> Result<()> {
        self.command(command).await?;
        self.data(data).await?;
        Ok(())
    }

    /// Send a byte to the display mutiple times.
    async fn data_x_times(&mut self, data: u8, repetitions: u32) -> Result<()> {
        let mut iter = iter::repeat(data).take(repetitions as usize);
        self.interface
            .send_data(DataFormat::U8Iter(&mut iter))
            .await?;
        Ok(())
    }
}

/// Functions available only for B/W displays
#[maybe_async_cfg::maybe(
    sync(
        feature = "blocking",
        keep_self,
        idents(
            AsyncWriteOnlyDataCommand(sync = "WriteOnlyDataCommand"),
            Wait(sync = "InputPin")
        )
    ),
    async(not(feature = "blocking"), keep_self)
)]
impl<DI, BSY, RST, DELAY, const WIDTH: u32, const VISIBLE_WIDTH: u32, const HEIGHT: u32>
    DisplayDriver<DI, BSY, RST, DELAY, WIDTH, VISIBLE_WIDTH, HEIGHT, Color>
where
    DI: AsyncWriteOnlyDataCommand,
    BSY: InputPin + Wait,
    RST: OutputPin,
    DELAY: DelayNs,
{
    /// Start a fast refresh of the display using the current in-screen buffers.
    ///
    /// If the display hasn't done a [`Self::full_refresh`] yet, it will do that first.
    pub async fn fast_refresh(&mut self) -> Result<()> {
        if !self.initial_full_refresh_done {
            // There a bug here which causes the new image to overwrite the existing image which then
            // fades out over several updates.
            self.full_refresh().await?;
        }

        if !self.using_partial_mode {
            self.command_with_data(command::WRITE_LUT, &lut::LUT_PARTIAL_UPDATE)
                .await?;
            self.using_partial_mode = true;
        }
        self.command_with_data(command::UPDATE_DISPLAY_CTRL2, &[flag::UNDOCUMENTED])
            .await?;
        self.command(command::MASTER_ACTIVATE).await?;
        self.wait_until_idle().await;
        Ok(())
    }

    /// Update the screen with the provided full frame buffer using a full refresh.
    pub async fn full_update_from_buffer(&mut self, buffer: &[u8]) -> Result<()> {
        self.write_red_buffer(buffer).await?;
        self.write_bw_buffer(buffer).await?;
        self.full_refresh().await?;
        self.write_red_buffer(buffer).await?;
        self.write_bw_buffer(buffer).await?;
        Ok(())
    }

    /// Update the screen with the provided full frame buffer using a fast refresh.
    pub async fn fast_update_from_buffer(&mut self, buffer: &[u8]) -> Result<()> {
        self.write_bw_buffer(buffer).await?;
        self.fast_refresh().await?;
        self.write_red_buffer(buffer).await?;
        self.write_bw_buffer(buffer).await?;
        Ok(())
    }

    /// Update the screen with the provided partial frame buffer at the given position using a fast refresh.
    ///
    /// `x`, and `width` must be multiples of 8.
    pub async fn fast_partial_update_from_buffer(
        &mut self,
        buffer: &[u8],
        x: u32,
        y: u32,
        width: u32,
        height: u32,
    ) -> Result<()> {
        self.write_partial_bw_buffer(buffer, x, y, width, height)
            .await?;
        self.fast_refresh().await?;
        self.write_partial_red_buffer(buffer, x, y, width, height)
            .await?;
        self.write_partial_bw_buffer(buffer, x, y, width, height)
            .await?;
        Ok(())
    }

    /// Update the screen with the provided [`Display`] using a full refresh.
    #[cfg_attr(docsrs, doc(cfg(feature = "graphics")))]
    #[cfg(feature = "graphics")]
    pub async fn full_update<const BUFFER_SIZE: usize>(
        &mut self,
        display: &Display<WIDTH, HEIGHT, BUFFER_SIZE, Color>,
    ) -> Result<()> {
        self.full_update_from_buffer(display.buffer()).await
    }

    /// Update the screen with the provided [`Display`] using a fast refresh.
    #[cfg_attr(docsrs, doc(cfg(feature = "graphics")))]
    #[cfg(feature = "graphics")]
    pub async fn fast_update<const BUFFER_SIZE: usize>(
        &mut self,
        display: &Display<WIDTH, HEIGHT, BUFFER_SIZE, Color>,
    ) -> Result<()> {
        self.fast_update_from_buffer(display.buffer()).await
    }

    /// Update the screen with the provided partial [`Display`] at the given position using a fast refresh.
    ///
    /// `x` and the display width `W` must be multiples of 8.
    #[cfg_attr(docsrs, doc(cfg(feature = "graphics")))]
    #[cfg(feature = "graphics")]
    pub async fn fast_partial_update<const W: u32, const H: u32, const BUFFER_SIZE: usize>(
        &mut self,
        display: &Display<W, H, BUFFER_SIZE, Color>,
        x: u32,
        y: u32,
    ) -> Result<()> {
        self.fast_partial_update_from_buffer(display.buffer(), x, y, W, H)
            .await
    }
}

/// Functions available only for tri-color displays
#[maybe_async_cfg::maybe(
    sync(
        feature = "blocking",
        keep_self,
        idents(
            AsyncWriteOnlyDataCommand(sync = "WriteOnlyDataCommand"),
            Wait(sync = "InputPin")
        )
    ),
    async(not(feature = "blocking"), keep_self)
)]
impl<DI, BSY, RST, DELAY, const WIDTH: u32, const VISIBLE_WIDTH: u32, const HEIGHT: u32>
    DisplayDriver<DI, BSY, RST, DELAY, WIDTH, VISIBLE_WIDTH, HEIGHT, TriColor>
where
    DI: AsyncWriteOnlyDataCommand,
    BSY: InputPin + Wait,
    RST: OutputPin,
    DELAY: DelayNs,
{
    /// Update the screen with the provided full frame buffers using a full refresh.
    pub async fn full_update_from_buffer(
        &mut self,
        bw_buffer: &[u8],
        red_buffer: &[u8],
    ) -> Result<()> {
        self.write_red_buffer(red_buffer).await?;
        self.write_bw_buffer(bw_buffer).await?;
        self.full_refresh().await?;
        Ok(())
    }

    /// Update the screen with the provided [`Display`] using a full refresh.
    #[cfg_attr(docsrs, doc(cfg(feature = "graphics")))]
    #[cfg(feature = "graphics")]
    pub async fn full_update<const BUFFER_SIZE: usize>(
        &mut self,
        display: &Display<WIDTH, HEIGHT, BUFFER_SIZE, TriColor>,
    ) -> Result<()> {
        self.full_update_from_buffer(display.bw_buffer(), display.red_buffer())
            .await
    }

    // TODO: check if partial updates with full refresh are supported
}