gc9d01 0.0.1

A no_std async/sync driver for GC9D01 LCD displays with embedded-graphics support
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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
#![no_std]

// NOTE: Due to limitations in mocking interactions with ownership and the `Drop` trait
// when using `embedded-hal-mock` (specifically with its `DoneCallDetector`),
// stable and consistently passing unit/integration tests for the SPI interactions
// are not provided with this library version. Users are advised to perform
// thorough integration testing in their target hardware environment.
//
// Previous attempts to create robust mock-based tests for synchronous SPI operations
// encountered persistent issues with `DoneCallDetector` panics, stemming from
// the inability to call the mock's `.done()` method before it's dropped when
// owned by the driver struct, a common pattern in embedded drivers.

// Assuming "async" feature is always on for this simplified test
use core::marker::PhantomData;

use embedded_graphics_core::pixelcolor::raw::RawData;
use embedded_graphics_core::pixelcolor::Rgb565;
use embedded_graphics_core::prelude::{DrawTarget, OriginDimensions, Size};
use embedded_graphics_core::Pixel as EgPixel;
use embedded_hal::digital::OutputPin;
use embedded_hal::spi::Error as SpiError; // Directly use async SpiBus

#[cfg(not(feature = "async"))]
use embedded_hal::spi::SpiDevice;
#[cfg(feature = "async")]
use embedded_hal_async::spi::SpiDevice;

// Timer trait now only needs async version for this test

#[maybe_async_cfg::maybe(
    sync(cfg(not(feature = "async")), self = "Timer",),
    async(feature = "async", keep_self)
)]
pub trait Timer {
    /// Expire after the specified number of milliseconds.
    fn after_millis(milliseconds: u64) -> impl core::future::Future<Output = ()>;
}

// Frame buffer size for full-screen rendering (160x40x2 bytes)
pub const FRAME_BUF_SIZE: usize = 160 * 40 * 2;
pub const MAX_FRAME_PIXELS: usize = FRAME_BUF_SIZE / 2;

#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
pub enum Instruction {
    Nop = 0x00,
    SwReset = 0x01,
    ReadDisplayId = 0x04,
    ReadDisplayStatus = 0x09,
    ReadDisplayPowerMode = 0x0A,
    ReadDisplayMadctl = 0x0B,
    ReadDisplayPixelFormat = 0x0C,
    ReadDisplayImageMode = 0x0D,
    ReadDisplaySignalMode = 0x0E,
    ReadDisplaySelfDiagnosticResult = 0x0F,
    SleepIn = 0x10,
    SleepOut = 0x11,
    PartialModeOn = 0x12,
    NormalDisplayOn = 0x13,
    DisplayInversionOff = 0x20,
    DisplayInversionOn = 0x21,
    DisplayOff = 0x28,
    DisplayOn = 0x29,
    ColumnAddressSet = 0x2A,
    RowAddressSet = 0x2B,
    MemoryWrite = 0x2C,
    MemoryRead = 0x2E,
    PartialArea = 0x30,
    VerticalScrollingDefinition = 0x33,
    TearingEffectLineOff = 0x34,
    TearingEffectLineOn = 0x35,
    MemoryAccessControl = 0x36,
    VerticalScrollingStartAddress = 0x37,
    IdleModeOff = 0x38,
    IdleModeOn = 0x39,
    PixelFormatSet = 0x3A,
    WriteMemoryContinue = 0x3C,
    ReadMemoryContinue = 0x3E,
    SetTearScanline = 0x44,
    GetScanline = 0x45,
    WriteDisplayBrightness = 0x51,
    ReadDisplayBrightness = 0x52,
    WriteCtrlDisplay = 0x53,
    ReadCtrlDisplay = 0x54,
    WriteCabc = 0x55,
    ReadCabc = 0x56,
    WriteCabcMinBrightness = 0x5E,
    ReadCabcMinBrightness = 0x5F,
    RgbInterfaceSignalControl = 0xB0,
    Spi2DataControl = 0xB1,
    TearingEffectControl = 0xB4,
    BlankingPorchControl = 0xB5,
    DisplayFunctionControl = 0xB6,
    DualSingleGateSelect = 0xBF,
    PowerControl1 = 0xC1,
    PowerControl2 = 0xC3,
    PowerControl3 = 0xC4,
    PowerControl4 = 0xC9,
    ReadId1 = 0xDA,
    ReadId2 = 0xDB,
    ReadId3 = 0xDC,
    Inversion = 0xEC,
    InterRegisterEnable2 = 0xEF,
    SetGamma1 = 0xF0,
    SetGamma2 = 0xF1,
    SetGamma3 = 0xF2,
    SetGamma4 = 0xF3,
    InterfaceControl = 0xF6,
    InterRegisterEnable1 = 0xFE,
    Cmd80 = 0x80,
    Cmd81 = 0x81,
    Cmd82 = 0x82,
    Cmd83 = 0x83,
    Cmd84 = 0x84,
    Cmd85 = 0x85,
    Cmd86 = 0x86,
    Cmd87 = 0x87,
    Cmd88 = 0x88,
    Cmd89 = 0x89,
    Cmd8A = 0x8A,
    Cmd8B = 0x8B,
    Cmd8C = 0x8C,
    Cmd8D = 0x8D,
    Cmd8E = 0x8E,
    Cmd8F = 0x8F,
    Cmd7E = 0x7E,
    Cmd74 = 0x74,
    Cmd98 = 0x98,
    Cmd99 = 0x99,
    Cmd60 = 0x60,
    Cmd63 = 0x63,
    Cmd64 = 0x64,
    Cmd66 = 0x66,
    Cmd6A = 0x6A,
    Cmd68 = 0x68,
    Cmd6C = 0x6C,
    Cmd6E = 0x6E,
    CmdA9 = 0xA9,
    CmdA8 = 0xA8,
    CmdA7 = 0xA7,
    CmdAD = 0xAD,
    CmdAF = 0xAF,
    CmdAC = 0xAC,
    CmdA3 = 0xA3,
    CmdCB = 0xCB,
    CmdCD = 0xCD,
    CmdC2 = 0xC2,
    CmdC5 = 0xC5,
    CmdC6 = 0xC6,
    CmdC7 = 0xC7,
    CmdC8 = 0xC8,
    CmdF9 = 0xF9,
    Cmd9B = 0x9B,
    Cmd93 = 0x93,
    Cmd70 = 0x70,
    Cmd71 = 0x71,
    Cmd91 = 0x91,
}

#[derive(Clone, Copy)]
pub enum Orientation {
    Portrait = 0x00,
    Landscape = 0x60,
    PortraitSwapped = 0x80,
    LandscapeSwapped = 0xA0,
}

#[derive(Clone, Copy)]
pub struct Config {
    pub rgb: bool,
    pub inverted: bool,
    pub orientation: Orientation,
    pub height: u16,
    pub width: u16,
    pub dx: u16,
    pub dy: u16,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            rgb: false,
            inverted: false,
            orientation: Orientation::Landscape,
            height: 160,
            width: 60,
            dx: 0,
            dy: 0,
        }
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error<BusE, PinE>
where
    BusE: core::fmt::Debug,
    PinE: core::fmt::Debug,
{
    Bus(BusE),
    Pin(PinE),
}

pub struct GC9D01<'b, BUS, DC, RST, TIMER>
where
    BUS: SpiDevice, // Will be async SpiBus
    DC: OutputPin,
    RST: OutputPin,
    TIMER: crate::Timer, // Timer trait is now always async
{
    bus: BUS,
    dc: DC,
    rst: RST,
    config: Config,
    frame_buffer: &'b mut [Rgb565], // Required frame buffer for full-screen rendering
    _timer: PhantomData<TIMER>,
}

#[maybe_async_cfg::maybe(
    sync(cfg(not(feature = "async")), self = "GC9D01",),
    async(feature = "async", keep_self)
)]
impl<'b, BUS, DC, RST, TIMER, BusE, PinE> GC9D01<'b, BUS, DC, RST, TIMER>
where
    BUS: SpiDevice<Error = BusE>,
    DC: OutputPin<Error = PinE>,
    RST: OutputPin<Error = PinE>,
    TIMER: crate::Timer,
    BusE: core::fmt::Debug + SpiError,
    PinE: core::fmt::Debug,
{
    /// Convert Rgb565 color to correct byte order for GC9D01 display
    /// GC9D01 expects RGB565 data in big-endian format (high byte first)
    fn convert_color_byte_order(color: Rgb565) -> Rgb565 {
        // Convert Rgb565 to RawU16 to get the raw u16 value
        let raw_pixel: embedded_graphics_core::pixelcolor::raw::RawU16 = color.into();
        let pixel_value: u16 = raw_pixel.into_inner();

        // Swap bytes: convert from little-endian to big-endian
        let swapped_value = pixel_value.swap_bytes();

        // Convert back to Rgb565
        embedded_graphics_core::pixelcolor::raw::RawU16::new(swapped_value).into()
    }
    /// Create a new GC9D01 instance with frame buffer support for full-screen rendering
    pub fn new(config: Config, bus: BUS, dc: DC, rst: RST, frame_buffer: &'b mut [Rgb565]) -> Self {
        Self {
            bus,
            dc,
            rst,
            config,
            frame_buffer,
            _timer: PhantomData,
        }
    }

    pub async fn init(&mut self) -> Result<(), Error<BusE, PinE>> {
        self.reset().await?; // 标准硬件复位

        self.write_command(Instruction::InterRegisterEnable1, &[])
            .await?; // 0xFE
        self.write_command(Instruction::InterRegisterEnable2, &[])
            .await?; // 0xEF

        // 内部寄存器使能 80~8Fh
        self.write_command(Instruction::Cmd80, &[0xFF]).await?;
        self.write_command(Instruction::Cmd81, &[0xFF]).await?;
        self.write_command(Instruction::Cmd82, &[0xFF]).await?;
        self.write_command(Instruction::Cmd83, &[0xFF]).await?;
        self.write_command(Instruction::Cmd84, &[0xFF]).await?;
        self.write_command(Instruction::Cmd85, &[0xFF]).await?;
        self.write_command(Instruction::Cmd86, &[0xFF]).await?;
        self.write_command(Instruction::Cmd87, &[0xFF]).await?;
        self.write_command(Instruction::Cmd88, &[0xFF]).await?;
        self.write_command(Instruction::Cmd89, &[0xFF]).await?;
        self.write_command(Instruction::Cmd8A, &[0xFF]).await?;
        self.write_command(Instruction::Cmd8B, &[0xFF]).await?;
        self.write_command(Instruction::Cmd8C, &[0xFF]).await?;
        self.write_command(Instruction::Cmd8D, &[0xFF]).await?;
        self.write_command(Instruction::Cmd8E, &[0xFF]).await?;
        self.write_command(Instruction::Cmd8F, &[0xFF]).await?;

        self.write_command(Instruction::PixelFormatSet, &[0x05])
            .await?; // 0x3A

        self.write_command(Instruction::Cmd7E, &[0x7A]).await?; // VGL大小

        // 修改帧频
        self.write_command(
            Instruction::Cmd74,
            &[0x02, 0x0E, 0x00, 0x00, 0x28, 0x00, 0x00],
        )
        .await?;

        // 内部电压调整
        self.write_command(Instruction::Cmd98, &[0x3E]).await?;
        self.write_command(Instruction::Cmd99, &[0x3E]).await?;

        // 内部porch设置
        self.write_command(Instruction::BlankingPorchControl, &[0x0E, 0x0E])
            .await?; // 0xB5

        // gip timing start
        self.write_command(Instruction::Cmd60, &[0x38, 0x09, 0x6D, 0x67])
            .await?;
        self.write_command(Instruction::Cmd63, &[0x38, 0xAD, 0x6D, 0x67, 0x05])
            .await?;
        self.write_command(Instruction::Cmd64, &[0x38, 0x0B, 0x70, 0xAB, 0x6D, 0x67])
            .await?;
        self.write_command(Instruction::Cmd66, &[0x38, 0x0F, 0x70, 0xAF, 0x6D, 0x67])
            .await?;
        self.write_command(Instruction::Cmd6A, &[0x00, 0x00])
            .await?;
        self.write_command(
            Instruction::Cmd68,
            &[0x3B, 0x08, 0x04, 0x00, 0x04, 0x64, 0x67],
        )
        .await?;
        self.write_command(
            Instruction::Cmd6C,
            &[0x22, 0x02, 0x22, 0x02, 0x22, 0x22, 0x50],
        )
        .await?;
        self.write_command(
            Instruction::Cmd6E,
            &[
                0x00, 0x00, 0x00, 0x00, 0x07, 0x01, 0x13, 0x11, 0x0B, 0x09, 0x16, 0x15, 0x1D, 0x1E,
                0x00, 0x00, 0x00, 0x00, 0x1E, 0x1D, 0x15, 0x16, 0x0A, 0x0C, 0x12, 0x14, 0x02, 0x08,
                0x00, 0x00, 0x00, 0x00,
            ],
        )
        .await?;
        // gip timing end

        // 内部电压设定开始
        self.write_command(Instruction::CmdA9, &[0x1B]).await?;
        self.write_command(Instruction::CmdA8, &[0x6B]).await?; // 第一次 A8
        self.write_command(Instruction::CmdA8, &[0x6D]).await?; // 第二次 A8
        self.write_command(Instruction::CmdA7, &[0x40]).await?;
        self.write_command(Instruction::CmdAD, &[0x47]).await?;
        self.write_command(Instruction::CmdAF, &[0x73]).await?; // 第一次 AF
        self.write_command(Instruction::CmdAF, &[0x73]).await?; // 第二次 AF
        self.write_command(Instruction::CmdAC, &[0x44]).await?;
        self.write_command(Instruction::CmdA3, &[0x6C]).await?;
        self.write_command(Instruction::CmdCB, &[0x00]).await?;
        self.write_command(Instruction::CmdCD, &[0x22]).await?;
        self.write_command(Instruction::CmdC2, &[0x10]).await?;
        self.write_command(Instruction::CmdC5, &[0x00]).await?;
        self.write_command(Instruction::CmdC6, &[0x0E]).await?;
        self.write_command(Instruction::CmdC7, &[0x1F]).await?;
        self.write_command(Instruction::CmdC8, &[0x0E]).await?;
        // 内部电压设定结束

        // Dual-Single gate select (BFh) - Set to Single gate mode (0x00) - Reverting for test
        self.write_command(Instruction::DualSingleGateSelect, &[0x00])
            .await?; // 0xBF, 选择single gate mode

        // SOU相关调整
        self.write_command(Instruction::CmdF9, &[0x20]).await?;

        // vreg电压调整
        self.write_command(Instruction::Cmd9B, &[0x3B]).await?;
        self.write_command(Instruction::Cmd93, &[0x33, 0x7F, 0x00])
            .await?;

        // VGH/VGL CLK调整 70, 71h
        self.write_command(Instruction::Cmd70, &[0x0E, 0x0F, 0x03, 0x0E, 0x0F, 0x03])
            .await?;
        self.write_command(Instruction::Cmd71, &[0x0E, 0x16, 0x03])
            .await?;

        // 内部电压调整
        self.write_command(Instruction::Cmd91, &[0x0E, 0x09])
            .await?;

        // vreg电压调整
        self.write_command(Instruction::PowerControl2, &[0x2C])
            .await?; // 0xC3
        self.write_command(Instruction::PowerControl3, &[0x1A])
            .await?; // 0xC4

        // gamma F0~F3h (注意伪代码中F0, F2, F1, F3的顺序)
        self.write_command(
            Instruction::SetGamma1,
            &[0x51, 0x13, 0x0C, 0x06, 0x00, 0x2F],
        )
        .await?; // 0xF0
        self.write_command(
            Instruction::SetGamma3,
            &[0x51, 0x13, 0x0C, 0x06, 0x00, 0x33],
        )
        .await?; // 0xF2
        self.write_command(
            Instruction::SetGamma2,
            &[0x3C, 0x94, 0x4F, 0x33, 0x34, 0xCF], // Corrected 0CF to 0xCF
        )
        .await?; // 0xF1
        self.write_command(
            Instruction::SetGamma4,
            &[0x4D, 0x94, 0x4F, 0x33, 0x34, 0xCF],
        )
        .await?; // 0xF3

        // Memory access control - use fixed value as in working example
        // This ensures consistent behavior regardless of orientation
        // Orientation will be handled by coordinate transformation
        self.write_command(Instruction::MemoryAccessControl, &[0x40]) // Fixed value as in reference document
            .await?; // 0x36

        self.write_command(
            Instruction::DisplayFunctionControl,
            &[0x0A, 0x80, 0x27, 0x00],
        ) // Set Source Driver Output Scan Direction to Reverse, Gate Driver to Normal (0x80)
        .await?; // 0xB6

        self.write_command(Instruction::SleepOut, &[]).await?; // 0x11
        #[allow(unused_must_use)]
        {
            TIMER::after_millis(200).await;
        }
        self.write_command(Instruction::DisplayOn, &[]).await?; // 0x29

        // Memory write command - ready for pixel data (as in working example)
        self.write_command(Instruction::MemoryWrite, &[]).await?; // 0x2C
        #[allow(unused_must_use)]
        {
            TIMER::after_millis(100).await;
        }

        Ok(()) // init function ends here
    }

    pub async fn reset(&mut self) -> Result<(), Error<BusE, PinE>> {
        // 硬件复位序列: RST 拉低 -> 延时10ms -> RST 拉高 -> 延时120ms
        self.rst.set_low().map_err(Error::Pin)?;
        #[allow(unused_must_use)]
        {
            TIMER::after_millis(10).await;
        }
        self.rst.set_high().map_err(Error::Pin)?;
        #[allow(unused_must_use)]
        {
            TIMER::after_millis(120).await;
        }
        Ok(())
    }

    async fn write_command(
        &mut self,
        instruction: Instruction,
        params: &[u8],
    ) -> Result<(), Error<BusE, PinE>> {
        self.dc.set_low().map_err(Error::Pin)?;

        let cmd_bytes = [instruction as u8];
        let cmd_res = self.bus.write(&cmd_bytes).await.map_err(Error::Bus);

        if cmd_res.is_ok() && !params.is_empty() {
            self.dc.set_high().map_err(Error::Pin)?;
            let param_res = self.bus.write(params).await.map_err(Error::Bus);
            if param_res.is_err() {
                param_res
            } else {
                Ok(())
            }
        } else if cmd_res.is_err() {
            cmd_res
        } else {
            Ok(())
        }
    }

    fn start_data_internal(&mut self) -> Result<(), PinE> {
        self.dc.set_high()
    }

    /// Transform logical coordinates to physical coordinates based on orientation
    fn transform_coordinates(&self, x: u16, y: u16) -> (u16, u16) {
        match self.config.orientation {
            Orientation::Portrait => {
                // Apply 90°+180° rotation to match the working reference example
                // For 160x40 logical -> 40x160 physical: logical(x,y) -> physical(39-y, 159-x)
                // This matches the coordinate transformation in stm32g4-direct-spi-90-complex-patterns
                (39 - y, 159 - x)
            }
            Orientation::Landscape => {
                // 90° clockwise rotation: logical(x,y) -> physical(y, width-1-x)
                // For 160x40 logical -> 40x160 physical: logical(x,y) -> physical(y, 159-x)
                (y, 159 - x)
            }
            Orientation::PortraitSwapped => {
                // This becomes the "normal" portrait (no rotation needed)
                (x, y)
            }
            Orientation::LandscapeSwapped => {
                // 270° rotation
                (y, self.config.width - 1 - x)
            }
        }
    }

    pub async fn set_address_window(
        &mut self,
        sx: u16,
        sy: u16,
        ex: u16,
        ey: u16,
    ) -> Result<(), Error<BusE, PinE>> {
        // Apply coordinate transformation based on orientation
        let (phys_sx, phys_sy) = self.transform_coordinates(sx, sy);
        let (phys_ex, phys_ey) = self.transform_coordinates(ex, ey);

        // Apply offset adjustments
        let final_sx = phys_sx + self.config.dx;
        let final_ex = phys_ex + self.config.dx;
        let final_sy = phys_sy + self.config.dy;
        let final_ey = phys_ey + self.config.dy;

        // Ensure coordinates are in correct order
        let (min_x, max_x) = if final_sx <= final_ex {
            (final_sx, final_ex)
        } else {
            (final_ex, final_sx)
        };
        let (min_y, max_y) = if final_sy <= final_ey {
            (final_sy, final_ey)
        } else {
            (final_ey, final_sy)
        };

        #[cfg(feature = "defmt")]
        defmt::debug!(
            "Address window: logical ({},{}) to ({},{}) -> physical ({},{}) to ({},{})",
            sx,
            sy,
            ex,
            ey,
            min_x,
            min_y,
            max_x,
            max_y
        );

        self.write_command(
            Instruction::RowAddressSet,
            &[
                (min_x >> 8) as u8,
                min_x as u8,
                (max_x >> 8) as u8,
                max_x as u8,
            ],
        )
        .await?;
        self.write_command(
            Instruction::ColumnAddressSet,
            &[
                (min_y >> 8) as u8,
                min_y as u8,
                (max_y >> 8) as u8,
                max_y as u8,
            ],
        )
        .await
    }

    // Frame buffer operations

    /// Clear the frame buffer with a solid color
    pub fn clear_frame_buffer(&mut self, color: Rgb565) {
        // Convert color to correct byte order for GC9D01 display
        let converted_color = Self::convert_color_byte_order(color);
        for pixel in self.frame_buffer.iter_mut() {
            *pixel = converted_color;
        }
    }

    /// Set a pixel in the frame buffer
    pub fn set_pixel(&mut self, x: u16, y: u16, color: Rgb565) {
        if x < self.config.width && y < self.config.height {
            // Convert color to correct byte order for GC9D01 display
            let converted_color = Self::convert_color_byte_order(color);

            // Apply coordinate transformation matching the working reference example
            // For 90°+180° rotation: logical(x,y) -> physical(39-y, 159-x)
            // This matches the coordinate transformation in stm32g4-direct-spi-90-complex-patterns
            let physical_x = 39 - y;
            let physical_y = 159 - x;

            // Calculate index in frame buffer using physical coordinates
            // Frame buffer is organized as physical screen: 40 width × 160 height
            let index = (physical_y as usize) * 40 + (physical_x as usize);
            if index < self.frame_buffer.len() {
                self.frame_buffer[index] = converted_color;
            }
        }
    }

    /// Fill a rectangular area in the frame buffer
    pub fn fill_rect(&mut self, x: u16, y: u16, width: u16, height: u16, color: Rgb565) {
        // Convert color to correct byte order for GC9D01 display
        let converted_color = Self::convert_color_byte_order(color);

        for row in y..(y + height) {
            for col in x..(x + width) {
                if col < self.config.width && row < self.config.height {
                    // Apply coordinate transformation matching the working reference example
                    // For 90°+180° rotation: logical(x,y) -> physical(39-y, 159-x)
                    // This matches the coordinate transformation in stm32g4-direct-spi-90-complex-patterns
                    let physical_x = 39 - row;
                    let physical_y = 159 - col;

                    // Calculate index in frame buffer using physical coordinates
                    // Frame buffer is organized as physical screen: 40 width × 160 height
                    let index = (physical_y as usize) * 40 + (physical_x as usize);
                    if index < self.frame_buffer.len() {
                        self.frame_buffer[index] = converted_color;
                    }
                }
            }
        }
    }

    /// Write pixel data to a rectangular area in the frame buffer
    pub fn write_rect(&mut self, x: u16, y: u16, width: u16, height: u16, data: &[Rgb565]) {
        let mut data_index = 0;
        for row in y..(y + height) {
            for col in x..(x + width) {
                if col < self.config.width && row < self.config.height && data_index < data.len() {
                    // Convert color to correct byte order for GC9D01 display
                    let converted_color = Self::convert_color_byte_order(data[data_index]);

                    // Apply coordinate transformation matching the working reference example
                    // For 90°+180° rotation: logical(x,y) -> physical(39-y, 159-x)
                    // This matches the coordinate transformation in stm32g4-direct-spi-90-complex-patterns
                    let physical_x = 39 - row;
                    let physical_y = 159 - col;

                    // Calculate index in frame buffer using physical coordinates
                    // Frame buffer is organized as physical screen: 40 width × 160 height
                    let index = (physical_y as usize) * 40 + (physical_x as usize);
                    if index < self.frame_buffer.len() {
                        self.frame_buffer[index] = converted_color;
                    }
                    data_index += 1;
                }
            }
        }
    }

    /// Flush the frame buffer to the display
    pub async fn flush(&mut self) -> Result<(), Error<BusE, PinE>> {
        // Set address window for the entire physical screen (40x160)
        // Use physical coordinates directly, not logical coordinates
        // ColumnAddressSet (0x2A) sets X coordinates (0 to 39 for physical width)
        // RowAddressSet (0x2B) sets Y coordinates (0 to 159 for physical height)
        self.write_command(
            Instruction::ColumnAddressSet,
            &[0, 0, 0, 39], // Physical X: 0 to 39
        )
        .await?;
        self.write_command(
            Instruction::RowAddressSet,
            &[0, 0, 0, 159], // Physical Y: 0 to 159
        )
        .await?;
        self.write_command(Instruction::MemoryWrite, &[]).await?;

        // Start data transmission
        self.start_data_internal().map_err(Error::Pin)?;

        // Send frame buffer data in chunks to respect DMA limitations
        // Convert frame_buffer to bytes view without copying
        let frame_bytes = unsafe {
            core::slice::from_raw_parts(
                self.frame_buffer.as_ptr() as *const u8,
                self.frame_buffer.len() * 2,
            )
        };

        // Send in chunks respecting DMA 16-bit counter limit (max 65535 bytes)
        // Use conservative 4096 bytes (2048 pixels) for safety
        const CHUNK_SIZE: usize = 4096;
        let mut offset = 0;

        while offset < frame_bytes.len() {
            let chunk_end = core::cmp::min(offset + CHUNK_SIZE, frame_bytes.len());
            self.bus
                .write(&frame_bytes[offset..chunk_end])
                .await
                .map_err(Error::Bus)?;
            offset = chunk_end;
        }

        Ok(())
    }

    pub fn fill_color(&mut self, color: Rgb565) {
        // Only operate on frame buffer - no hardware operations
        // clear_frame_buffer already handles color conversion
        self.clear_frame_buffer(color);
    }

    pub fn write_area(&mut self, x: u16, y: u16, width: u16, height: u16, data: &[Rgb565]) {
        // Only operate on frame buffer - no hardware operations
        // write_rect already handles color conversion
        self.write_rect(x, y, width, height, data);
    }
}

// Embedded Graphics trait implementations
impl<BUS, DC, RST, TIMER, BusE, PinE> OriginDimensions for GC9D01<'_, BUS, DC, RST, TIMER>
where
    BUS: SpiDevice<Error = BusE>,
    DC: OutputPin<Error = PinE>,
    RST: OutputPin<Error = PinE>,
    TIMER: crate::Timer,
    BusE: core::fmt::Debug + SpiError,
    PinE: core::fmt::Debug,
{
    fn size(&self) -> Size {
        Size::new(self.config.width as u32, self.config.height as u32)
    }
}

impl<BUS, DC, RST, TIMER, BusE, PinE> DrawTarget for GC9D01<'_, BUS, DC, RST, TIMER>
where
    BUS: SpiDevice<Error = BusE>,
    DC: OutputPin<Error = PinE>,
    RST: OutputPin<Error = PinE>,
    TIMER: crate::Timer,
    BusE: core::fmt::Debug + SpiError,
    PinE: core::fmt::Debug,
{
    type Color = Rgb565;
    type Error = core::convert::Infallible;

    fn draw_iter<I>(&mut self, pixels: I) -> Result<(), Self::Error>
    where
        I: IntoIterator<Item = EgPixel<Self::Color>>,
    {
        for EgPixel(point, color) in pixels {
            if point.x >= 0 && point.y >= 0 {
                let x = point.x as u16;
                let y = point.y as u16;
                if x < self.config.width && y < self.config.height {
                    self.set_pixel(x, y, color);
                }
            }
        }
        Ok(())
    }

    fn clear(&mut self, color: Self::Color) -> Result<(), Self::Error> {
        self.clear_frame_buffer(color);
        Ok(())
    }
}