-
Notifications
You must be signed in to change notification settings - Fork 12
/
ILI9341Driver.h
2221 lines (1699 loc) · 88.2 KB
/
ILI9341Driver.h
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
* ILI9341_T4 library for driving an ILI9341 screen via SPI with a Teensy 4/4.1
* Implements vsync and differential updates from a memory framebuffer.
*
* Copyright (c) 2020 Arvind Singh. All right reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*******************************************************************************/
/**
*CREDITS. Parts of this code is based on:
*
* (1) KurtE's highly optimized library for ILI9341: https://github.com/KurtE/ILI9341_t3n
* -> for SPI / DMA and all the fancy low level hardware stuff... beautiful !
*
* (2) PJRC's XPT2048 library https://github.com/PaulStoffregen/XPT2046_Touchscreen
* -> for all the touchscreen related methods.
**/
#ifndef _ILI9341_T4_ILI9341Driver_H_
#define _ILI9341_T4_ILI9341Driver_H_
// only c++, no plain c
#ifdef __cplusplus
#include <Arduino.h>
// This libray uses specify hardware features of IMXRT1062 and will not work with another MCU...
#if (!defined(__IMXRT1062__)) || (!defined(CORE_TEENSY))
#error "Library ILI9341_T4 only supports Teensy 4/4.1/micromod."
#endif
#include "StatsVar.h"
#include "DiffBuff.h"
#include <DMAChannel.h>
#include <SPI.h>
#include <stdint.h>
namespace ILI9341_T4
{
/** a few colors */
#define ILI9341_T4_COLOR_BLACK 0x0
#define ILI9341_T4_COLOR_WHITE 0xffff
#define ILI9341_T4_COLOR_RED 0xf800
#define ILI9341_T4_COLOR_BLUE 0x1f
#define ILI9341_T4_COLOR_GREEN 0x7e0
#define ILI9341_T4_COLOR_PURPLE 0x8010
#define ILI9341_T4_COLOR_ORANGE 0xfc20
#define ILI9341_T4_COLOR_CYAN 0x7ff
#define ILI9341_T4_COLOR_LIME 0x7e0
#define ILI9341_T4_COLOR_SALMON 0xfc0e
#define ILI9341_T4_COLOR_MAROON 0x8000
#define ILI9341_T4_COLOR_YELLOW 0xffe0
#define ILI9341_T4_COLOR_MAJENTA 0xf81f
#define ILI9341_T4_COLOR_OLIVE 0x8400
#define ILI9341_T4_COLOR_TEAL 0x410
#define ILI9341_T4_COLOR_GRAY 0x8410
#define ILI9341_T4_COLOR_SILVER 0xc618
#define ILI9341_T4_COLOR_NAVY 0x10
/** Configuration */
#define ILI9341_T4_DEFAULT_SPICLOCK 30000000 // default SPI write speed, some display can work up to 80Mhz...
#define ILI9341_T4_DEFAULT_SPICLOCK_READ 4000000 // default SPI read speed (much slower then write speed)
#define ILI9341_T4_DEFAULT_VSYNC_SPACING 0 // No VSync/Screen tearing protection by default.
#define ILI9341_T4_DEFAULT_DIFF_GAP 6 // default gap for diffs (typ. between 4 and 50)
#define ILI9341_T4_DEFAULT_LATE_START_RATIO 0.3f // default "proportion" of the frame admissible for late frame start when using vsync.
#define ILI9341_T4_TRANSACTION_DURATION 3 // number of pixels that could be uploaded during a typical CASET/PASET/RAWR sequence.
#define ILI9341_T4_RETRY_INIT 5 // number of times we try initialization in begin() before returning an error.
#define ILI9341_T4_TFTWIDTH 240 // screen dimension x (in default orientation 0)
#define ILI9341_T4_TFTHEIGHT 320 // screen dimension y (in default orientation 0)
#define ILI9341_T4_NB_SCANLINES ILI9341_T4_TFTHEIGHT// scanlines are mapped to the screen height
#define ILI9341_T4_MIN_WAIT_TIME 300 // minimum waiting time (in us) before drawing again when catching up with the scanline
#define ILI9341_T4_NB_PIXELS (ILI9341_T4_TFTWIDTH * ILI9341_T4_TFTHEIGHT) // total number of pixels
#define ILI9341_T4_MAX_VSYNC_SPACING 5 // maximum number of screen refresh between frames (for sync clock stability).
#define ILI9341_T4_DEFAULT_IRQ_PRIORITY 128 // default priority at which we run all irqs (dma, pit timer and spi interrupts).
#define ILI9341_T4_MAX_DELAY_MICROSECONDS 1000000 // maximum waiting time (1 second)
#define ILI9341_T4_TOUCH_Z_THRESHOLD 400 // for touch
#define ILI9341_T4_TOUCH_Z_THRESHOLD_INT 75 // same as https://github.com/PaulStoffregen/XPT2046_Touchscreen/blob/master/XPT2046_Touchscreen.cpp
#define ILI9341_T4_TOUCH_MSEC_THRESHOLD 3 //
#define ILI9341_T4_SELFDIAG_OK 0xC0 // value returned by selfDiagStatus() if everything is OK.
#define ILI9341_T4_DEFAULT_FPS_COUNTER_COLOR_FG ILI9341_T4_COLOR_WHITE // default values (color/opacity/position)
#define ILI9341_T4_DEFAULT_FPS_COUNTER_COLOR_BG ILI9341_T4_COLOR_BLUE // for the FPS counter
#define ILI9341_T4_DEFAULT_FPS_COUNTER_OPACITY 0.5f //
#define ILI9341_T4_DEFAULT_FPS_COUNTER_POSITION 0 //
#define ILI9341_T4_ALWAYS_INLINE __attribute__((always_inline))
/*************************************************************************************************************
* ILI9341 screen driver for Teensy 4/4.1.
*
* The driver performs fast blitting of a memory framebuffer onto the screen using SPI transfer (synchronous
* or asynchronous with DMA) with the following additional features:
*
* (1) Implements partial redraw where only the pixels that changes between frames are updated.
*
* (2) Implements 'vsync' to prevent screen tearing (pixels are updated behind the refresh scanline).
*
* (3) Adjustable screen refresh rate (40 - 120hz) and framerate (asap or locked with the refresh rate).
*
* (4) Multiple buffering mode: no buffering / double buffering
*
* (5) The object can also manage a XPT2046 touchscreen on the same SPI bus.
*
*
* The memory framebuffers should have the usual layout:
*
* SCREEN PIXEL(i,j) = framebuffer[i + (width * j)]
*
* for 0 <= i < width and 0 <= j < height
*
* with the 'width' and 'height' value depending on the chosen screen orientation and where the pixels color are
* given in uint16_t RGB565 format.
*
*RGB565 layout as uint16: bit 15 bit 0
* RRRRR GGGGGG BBBBB
*
* -> red bits [15-11]
* -> green bits [10-5]
* -> blue bits [4-0]
*
****************************************************************************************************************/
class ILI9341Driver
{
public:
/***************************************************************************************************
****************************************************************************************************
*
* Initialization and general settings
*
****************************************************************************************************
****************************************************************************************************/
/**
* Constructor. Set the hardware pins but do not initialize anything yet.
*
* Pin not set are given default value 255.
*
* - cs : Pin connected to the CS pin on the display. Mandatory if present.
* Can be any digital pin on the teensy: it does not need to be an hardware accelerated CCS pin...
* --> Some display do not have a CS pin, in the case, set cs=255.
*
* - dc : Pin connected to the DC pin on the display. Mandatory.
* Can be any digital pin on the teensy BUT USING A HARDWARE ACCELERATED CS PIN FOR DC WILL PROVIDE
* A IMPORTANT SPEEDUP !!!
*
* - sclk: Pin connected to the SCK pin on the display. Mandatory.
* Must be a hardware SCK pin for the SPI bus used on the Teensy.
*
* - mosi: Pin connected to the SDI(MOSI) pin on the display. Mandatory.
* Must be a hardware MOSI pin for the SPI bus used on the Teensy.
*
* - miso: Pin connected to the SDO(MISO) pin on the display. Mandatory.
* Must be a hardware MISO pin for the SPI bus used on the Teensy.
* -> The MISO pin can be left unconnected (by setting it to 255) but in this case VSync (screen tearing protection)
* is disabled and the screen status and refresh rates cannot be queried...
*
* - rst: Pin connected to the RESET pin on the display. Optional but recommended.
* -> if not connected to the teensy, set rst=255 and do not forget the pull
* the RST pin to +3.3V the display
*
* If the screen has an XPT2046 touchscreen ON THE SAME SPI BUS:
*
* - touch_cs : Pin connected to the T_CS pin on the display. Mandatory to use the touchscreen.
* Can be any digital pin.
*
* - touch_irq: Pin connected to the T_IRQ pin on the display. Optional.
* Can be any digital pin.
*
* --> When using the touchscreen (with this driver), the T_CLK, T_DIN and T_DO pin from the screen
* must be connected to the same pin as SCK, SDI and SDO (i.e. the screen and touchscreen share the same SPI bus)
*
* --------------------------------------------------------------------------------------------
* THE SPI BUS SHOULD BE DEDICATED TO THE SCREEN (AND POSSIBLY THE XPT2046 TOUCHSCREEN)
* DO NOT CONNECT ANY OTHER DEVICE ON THAT SPI BUS !!!
* --------------------------------------------------------------------------------------------
*
**/
ILI9341Driver(uint8_t cs, uint8_t dc, uint8_t sclk, uint8_t mosi, uint8_t miso, uint8_t rst = 255, uint8_t touch_cs = 255, uint8_t touch_irq = 255);
/**
* Set the output Stream used by the driver for displaying infos.
*
* Set this to nullptr to prevent any output.debugging.
*
* The stream is used, in particular by the following methods:
*
* - `begin()` for debugging/displaying debug information.
* - `printStatus()` to check the the driver status.
* - `printRefreshMode()` to display available refresh rates/modes.
* - `printStats()` to print statistics about frame uploads.
* - `calibrateTouch()` to provide instruction for calibration.
*
* Typical usage: output(&Serial)
**/
void output(Stream * outputStream = nullptr) { _outputStream = outputStream; }
/**
* Initialize the screen (and optionally set the speed for read/write SPI transfers).
*
* THis method should be called only once. There is no associated end() method.
*
* Return true if initialization is OK, false if an error occurred.
*
* NOTE: if an output stream is set with the `output()` method, then debug information
* are sent to this stream.
**/
bool begin(uint32_t spi_clock = ILI9341_T4_DEFAULT_SPICLOCK, uint32_t spi_clock_read = ILI9341_T4_DEFAULT_SPICLOCK_READ);
/**
* Query the value of the self-diagnostic register.
*
* Should return ILI9341_T4_SELFDIAG_OK = 0xC0 if everything is fine.
*
* Returns 0 if the MISO line is not connected (PIN_MISO=255) and the screen cannot be queried.
**/
int selfDiagStatus();
/**
* Print some info about the screen status (for debug purpose).
*
* Output is sent to the stream set with the `output()` method.
*
* Use printStats() instead to get statistics for optimization purposes.
**/
void printStatus();
/**
* Set the speed for subsequent SPI writes.
*
* Remark: calling this method reset all statistics.
**/
void setSpiClock(int spi_clock = ILI9341_T4_DEFAULT_SPICLOCK);
/**
* Query the spi speed for SPI writes.
**/
int getSpiClock() const { return _spi_clock; }
/**
* Set the speed for subsequent SPI reads.
*
* Remark: calling this method reset the statistics.
**/
void setSpiClockRead(int spi_clock = ILI9341_T4_DEFAULT_SPICLOCK_READ);
/**
* Query the spi speed for SPI reads.
**/
int getSpiClockRead() const { return _spi_clock_read; }
/**
* Set the priority at which all the driver interrupts run (dma, pit-timer and SPI).
*
* ADVANCED METHOD: do not change the default value unless you know what you are doing.
* The default value should be good for most use case...
*
* - the default value is ILI9341_T4_DEFAULT_IRQ_PRIORITY = 128.
*
* - Setting a smaller value (eg 64 or 32) increases the priority hence it will make
* the framerate more stable by prioritizing the screen driver interrupts over
* other ones (but, although unlikely, this could slow down/interfere with other operations).
*
* - Setting a larger value (eg 192) will insure that the driver does not interrupt/interfere
* with other operations with higher priorities but the framerate may oscillate a little more
* if servicing the other interrupts takes a long time.
**/
void setIRQPriority(int irq_priority = ILI9341_T4_DEFAULT_IRQ_PRIORITY);
/**
* Return the priority at which the driver's interrupt are currently running.
**/
int getIRQPriority() const { return _irq_priority; }
/***************************************************************************************************
****************************************************************************************************
*
* Misc commands
*
****************************************************************************************************
****************************************************************************************************/
/**
* Enter/exit sleep mode.
**/
void sleep(bool enable);
/**
* Invert the display colors.
**/
void invertDisplay(bool i);
/**
* Set the vertical scroll offset.
*
* Default value is 0 (no scroll). When an offset is set, the framebuffer is shifted vertically on
* the screen by the given offset. This means that the following (hardware) mapping is performed:
*
* - framebuffer line i => drawn at scanline (i - offset) mod TFT_HEIGHT.
*
* offset can be any value (positive or negative) so that incrementing / decrementing it enables
* to scroll up or down continuously.
**/
void setScroll(int offset = 0);
/***************************************************************************************************
****************************************************************************************************
*
* Screen Orientation
*
* -> these methods determine the screen orientation which affects the framebuffer dimensions and its
* layout.
*
****************************************************************************************************
****************************************************************************************************/
/** The 4 possible orientations */
enum
{
PORTRAIT_240x320 = 0,
LANDSCAPE_320x240 = 1,
PORTRAIT_240x320_FLIPPED = 2,
LANDSCAPE_320x240_FLIPPED = 3,
};
/**
* Set the screen Orientation (between 0 and 3)
*
* The default start up orientation is 0.
*
* The framebuffer layout depend on whether the display is in portrait or landscape mode.
*
* - orientation 0 and 2 in portrait mode : 240x320.
* - orientation 1 and 3 in landscape mode : 320x240.
*
* NOTE: Orientation 0 the the only one for with pixels refresh order coincide with the framebuffer
* ordering. Using this orientation may provide a marginal increase in the driver speed.
*
* Remark: calling this method resets the statistics (if the orientation changes).
**/
void setRotation(uint8_t r);
/**
* Return the current screen orientation (between 0 and 3)
*
* The default start up orientation is 0.
*
* The framebuffer layout depends on whether the display is in portrait or landscape mode:
*
* SCREEN_PIXEL(i,j) = framebuffer[i + width*j]
*
* with width = 240 if orientation is 0 or 2
* = 320 if orientation is 1 or 3.
**/
int getRotation() const { return _rotation; }
/**
* Return the screen witdh (w.r.t the current orientation).
**/
int width() const { return _width; }
/**
* Return the screen height (w.r.t the current orientation).
**/
int height() const { return _height; }
/***************************************************************************************************
****************************************************************************************************
*
* Screen refresh rate.
*
* -> these methods are used to set the screen refresh rate (number of times the display is refreshed
* per second). This rate is important because it is related to the actual framerate via the
* vsync_spacing parameter (c.f. the vsync setting section).
*
****************************************************************************************************
****************************************************************************************************/
/**
* set the refresh mode between 0 and 31.
*
* - 0 : fastest refresh rate (around than 120/140hz).
* - 31 : slowest refresh rate (around 30/40hz).
*
* NOTE: the exact refresh rate for a given mode varies from display to display.
* Once the mode set, use getRefreshRate() to find out the refresh rate.
*
* By default the refresh mode selected is 0 (fastest possible).
*
* Remark: calling this method resets the statistics.
**/
void setRefreshMode(int mode);
/**
* Return the current refresh mode.
*
* - 0 : fastest refresh rate (around than 120/140Hz).
* - 31 : slowest refresh rate (around 30/40Hz).
*
**/
int getRefreshMode() const { return _refreshmode; }
/**
* Set the refresh mode for the display to match the requested refresh rate (in Hz).
* as close as possible.
*
* After this method returns. Use getRefreshMode() and getRefreshRate() to find
* out the actual mode and exact refresh rate set. Note that these values will varies
* from display to display.
*
* Remark: calling this method resets the statistics.
*
* Remark: If PIN_MISO=255, the exact refresh rates of the display cannot be queried and
* values for a 'typical' ILI9341 display are used instead.
**/
void setRefreshRate(float refreshrate_hz);
/**
* Get the refresh rate of the display (in Hz) corresponding to the current
* refresh mode set.
*
* Remark: If PIN_MISO=255, the exact refresh rate cannot be queried and the returned value
* is the average refresh rate of the current mode for a 'typical' ILI9341 display..
**/
float getRefreshRate() const { return (_period == 0) ? 0.0f : 1000000.0f / _period; }
/**
* Display all the possible screen refresh mode with the corresponding refresh rates.
*
* The infos are sent to the output stream set with the `output()` method.
*
* This method is will take a few seconds as its cycles through all the modes
* and must sample the exact refresh rate each time.
*
* Remark: If PIN_MISO=255, the real refresh rates cannot be queried and the displayed values are
* those of a 'typical' ILI9341 display..
**/
void printRefreshMode();
/***************************************************************************************************
****************************************************************************************************
*
* VSync settings and framerate locking.
*
* -> these methods decide how updates are carried out and whether operations are synced with the
* display refresh rate or, on the contrary, are pushed as fast as possible.
*
****************************************************************************************************
****************************************************************************************************/
/**
* This parameter defines the upload strategy and determines how the actual framerate relates
* to the display refresh rate.
*
* This number must be between -1 and 5 = ILI9341_T4_MAX_VSYNC_SPACING.
*
* - vsync_spacing = -1. In this case, screen updates occur as soon as possible and some frames
* may even be dropped when using double buffering if they are pushed to
* update() faster than they can be uploaded to the screen. This mode will
* provide the fastest 'apparent' framerate but at the expanse of picture
* quality and will also induce screen tearing (no VSync)
* This mode also does not insure any framerate control/stability.
*
* - vsync_spacing = 0. Again, screen updates are pushed to the screen as fast as possible but
* frames are not dropped so the driver will wait if an update is already
* in progress.
* Again, this mode provides no guaranty concerning screen tearing nor
* framerate stability.
*
* - vsync_spacing > 0. The updates are synchronized with the screen refresh. This approach has
* two advantages:
* 1) It prevents screen tearing.
* 2) It insure a constant framerate.
*
* vsync_spacing is the number of screen refresh between two consecutive
* updates. Thus, the real framerate is given by:
*
* real_framerate = screen_refresh_rate / vsync_spacing
*
* vsync_spacing should be set to either:
* 1 (framerate = refresh_rate) or 2 (framerate = half refresh rate).
*
* --> Larger values are not really useful except for special cases.
*
* NOTE 1: In order to insure that screen tearing cannot occur, the upload must be done fast
* enough so that the refresh 'scanline' does not catch up with the pixels currently
* being updated. This is possible if the upload takes less than 2 refresh periods.
* For this reason, vsync_spacing = 2 is the optimal choice in most case. However,
* if the diff is simple enough so that the frame upload rate is faster than the
* screen refresh rate, then it may be worth setting vsync_spacing = 1 ...
*
* ADVICE : USE vsync_spacing = 2 AND ADJUST THE DISPLAY REFRESH RATE WITH setRefreshRate()
* TO GET A CONSISTENT FRAMERATE WITHOUT SCREEN TEARING
*
* Remark: calling this method resets the statistics.
*
* Remark: If PIN_MISO=255, then VSync spacing cannot be enalbed and therefore it will revert to
* vsync_spacing = 0 (or -1 if requested)
**/
void setVSyncSpacing(int vsync_spacing = ILI9341_T4_DEFAULT_VSYNC_SPACING);
/**
* Return the current vsync_spacing parameter.
**/
int getVSyncSpacing() const { return _vsync_spacing; }
/**
* Set how late we can be behind the scan line and still start uploading a frame without
* waiting for the next refresh for synchronization. Set a value in [0.1f, 0.9f]
*
* - Choosing a small value will reduce screen tearing but may make the framerate oscillate more
* when the timing is tight.
*
* - Choosing a large value will stabilize the framerate but at the expense of more screen tearing
* when the timing is tight.
*
* Remark: calling this method resets the statistics.
**/
void setLateStartRatio(float ratio = ILI9341_T4_DEFAULT_LATE_START_RATIO);
/**
* Return the value of the "late start ratio" parameter.
**/
float getLateStartRatio() const { return _late_start_ratio; }
/**
* Force a re-synchronization with the screen scanline on the next frame upload.
* This command has no effect when not in vsync mode (ie when vsync_spacing <= 0).
*
* This method should not be used under normal circumstance.
**/
void resync() { _late_start_ratio_override = true; }
/***************************************************************************************************
****************************************************************************************************
*
* Buffering mode
*
* -> these methods decide whether update operations are carried immediately or if an internal
* framebuffer is used for double buffering and asynchronous upload via DMA.
*
****************************************************************************************************
****************************************************************************************************/
/**
* Set/remove the internal framebuffer.
*
* The mode of operation of the update() method depends on whether an internal framebuffer is set.
*
* - no internal framebuffer : all updates operations are performed immediately.
* - internal framebuffer set : double buffering and asynchronous transfer in background via DMA.
*
* ----------------------------------------------------------------------------------------------
* THE INTERNAL FRAMEBUFFER IS GIVEN FOR INTERNAL USE BY THE CLASS AND SHOULD NOT BE MODIFIED ONCE
* SET (except if you know what you are doing :-))
* ----------------------------------------------------------------------------------------------
*
* Remarks:
*
* 1. Calling the method with empty parameter/nullptr removes any previously set framebuffer.
*
* 2. Calling this method resets the statistics.
**/
void setFramebuffer(uint16_t* fb1 = nullptr);
/**
* Alias for the SetFrameBuffer() method.
*
* For compatibility with previous library version only: the second framebuffer fb2 is ignored.
**/
void setFramebuffers(uint16_t* fb1 = nullptr, uint16_t* fb2 = nullptr) { setFramebuffer(fb1 ? fb1 : fb2); }
/** Buffering mode*/
enum
{
NO_BUFFERING = 0,
DOUBLE_BUFFERING = 2,
};
/**
* Return the current buffering mode:
*
* - 0 = NO_BUFFERING : no internal framebuffer. All updates operations are carried immediately.
* - 2 = DOUBLE_BUFFERING : internal framebuffer set. Double buffering using asynchronous transfer via DMA.
*
**/
int bufferingMode() const { return ((_fb1) ? DOUBLE_BUFFERING : NO_BUFFERING);}
/***************************************************************************************************
****************************************************************************************************
*
* Differential updates settings
*
****************************************************************************************************
****************************************************************************************************/
/**
* Set/remove one (or two) internal diff buffers used for performing differential updates.
*
* When diff buffers are set. They will be used whenever possible to create 'diff' between the current
* screen content and the new framebuffer to be uploaded so that only pixels that change color will be
* uploaded, drastically reducing the upload time and therefore providing a boost on the effective
* framerate.
*
* In order to use differential update, the driver must 'know' the current screen content which means
* that an internal frmaebuffer must be set (ie double buffering enabled). To enable differential updates
* you must both set at least 1 diff buffer AND the internal framebuffer.
*
* Setting a second diff buffer is optional but will increase the framerate as it allows the driver to
* compute the diff of the next frame while still performing the asynchronous transfer of the previous
* frame.
*
* ----------------------------------------------------------------------------------------------
* ONCE SET, THE DIFFBUFFER BELONG TO THIS OBJECT AND MUST NOT BE TOUCHED FOR CREATING OR READING
* DIFFS OR THE WHOLE PROGRAM MAY CRASH !!!
*
* HOWEVER, IT IS STILL POSSIBLE TO CALL ALL THE STATSXXX() METHODS OF THE DIFFS TO CHECK MEMORY
* CONSUMPTION / CPU USAGE...
*
* IF YOU WANT THE DIFF BUFFER BACK, JUST CALL THE METHOD AGAIN WITH EMPTY PARAMETERS TO REMOVE THEM
* FROM THE DRIVER
* ----------------------------------------------------------------------------------------------
*
* Remark:
*
* - Calling this method resets the stats (if the buffering mode changes).
* - Use 2 diff buffers whenever possible !
**/
void setDiffBuffers(DiffBuffBase* diff1 = nullptr, DiffBuffBase* diff2 = nullptr);
/**
* Query whether the driver performs full screen transfer or differential updates.
*
* Differential updates are enabled as soon as the following two conditions are meet:
*
* 1. An internal framebuffer has been set (ie DOUBLE_BUFFERING is active)
* 2. At least one diff buffer has been set.
*
* NOTE: Use 2 diff buffers whenever possible !
**/
bool diffUpdateActive() const { return ((bufferingMode() == DOUBLE_BUFFERING) && (_diff1 != nullptr)); }
/**
* Set the gap used when creating diffs.
*
* [See the DiffBuff class for more detail on the gap parameter].
* This parameter correspond to the number of consecutive unchanged pixels needed to break a SPI
* transaction. A smaller value will give results in less pixels being uploaded but will, on the
* other hand create larger diffs... The optimal value should be between 4 and 20 and will depend
* on the kind of graphics drawn.
*
* As a rule of thumb:
*
* - Gap larger than 10 for diff buffer with less than 4K of memory
* - Gap between 6 to 10 for diff buffers with size between 4K to 8K.
* - Gap between 4 to 6 for diff buffers with size larger then 8K.
*
* You can use the printStats() to check how much memory the diff buffer typically consume. If the
* diffs buffers overflow too often, you should either increase the gap or increase their size.
*
* Remark: calling this method resets the statistics.
**/
void setDiffGap(int gap = ILI9341_T4_DEFAULT_DIFF_GAP);
/**
* Return the current gap parameter used when creating diffs.
**/
int getDiffGap() const { return _diff_gap; }
/**
* Set the mask used when creating a diff to check is a pixel is the same in both framebuffers.
* If the mask set is non-zero, then only the bits set in the mask are used for the comparison
* so pixels with different values may be considered equal and may not redrawn.
*
* Setting a mask may be useful when the framebuffer being uploaded to the screen comes from
* a camera or another source that introduces random noise that would prevent the diff from
* finding large region of identical pixels (hence making the diff pretty useless) but when
* it does not really matter to have a 'perfect' copy of the framebuffer on the screen.
*
* Typically, one wants to set the lower bits on each channel color to 0 so that color that
* are 'close' are not always redrawn (see the other method version below).
*
* If called without argument, the compare mask is set to 0 hence disabled and strict equality
* is enforced when creating diffs (default behavior).
*
* -> RGB565 layout as uint16: bit 15 bit 0
* RRRRR GGGGGG BBBBB
**/
void setDiffCompareMask(uint16_t mask = 0);
/**
* Set the compare mask by specifying for each color channel the number of lower bits
* that should be ignored.
*
* Recall that there are 5 bits for the blue and red channel and 6 bits for the green
* channel.
*
* -> RGB565 layout as uint16: bit 15 bit 0
* RRRRR GGGGGG BBBBB
**/
void setDiffCompareMask(int bitskip_red, int bitskip_green, int bitskip_blue);
/**
* Return the value of the current compare_mask.
*
* Return 0 if the mask is not set and strict comparison of pixel colors is enforced
* (which is the default value).
**/
uint16_t getCompareMask() const { return _compare_mask; }
/***************************************************************************************************
****************************************************************************************************
*
* Screen updates
*
****************************************************************************************************
****************************************************************************************************/
/**
* Clear the screen to a single color (default black).
*
* This operation is done immediately (i.e. not async) so the screen is cleared on return.
**/
void clear(uint16_t color = 0);
/**
* MAIN SCREEN UPDATE METHOD
*
* Push a framebuffer to be displayed on the screen. The behavior of the method depend on the
* current buffering mode and the vsync_spacing parameter.
*
* - fb : the framebuffer to draw unto the screen.
*
* - force_full_redraw: If set to true, then differential update is disabled for this particular
* frame and the whole screen is updated (even when a diff could have been used).
* Normally, this option should not be needed except in the very special cases
* where one knows for sure that the diff will be useless so disabling it saves
* some CPU times that would have been used for creating the diff (around 1us
* normally).
*
* WHEN THE METHOD RETURNS, THE FRAME MAY OR MAY NOT ALREADY BE DISPLAYED ONT THE SCREEN BUT
* THE INPUT FRAMEBUFFER fb CAN STILL BE REUSED IMMEDIATELY IN ANY CASE. (when using async updates,
* the internal framebuffer is used to save a copy of the framebuffer).
*
*
* The exact behavior of the method depends on bufferingMode():
*
*
* -> NO_BUFFERING (i.e. no internal framebuffer set):
*
* The framebuffer is pushed to the screen immediately and the method returns only when upload is
* complete. In this mode, differential upload are always disabled: the whole screen is updated
* and diff buffers, if present, are ignored.
*
* - if vsync_spacing <= 0, upload to the screen start immediately (no VSync).
*
* - if vsync_spacing >= 1, screen upload is synchronized with the screen refresh (VSync) and the
* method waits until vsync_spacing refreshes have occurred since the previous update to insure
* a constant framerate equal to (refresh_rate/vsync_spacing).
*
*
* -> DOUBLE_BUFFERING (internal framebuffer set)
*
* All updates are done asynchronously via DMA and the method returns asap. If 1 or 2 diff buffers
* are present, they are automatically used to perform differential update: only the portion of
* the screen whose content has changed is redrawn.
*
* - if vsync_spacing = -1, upload to the screen starts immediately unless there is already a
* transfer in progress in which case the frame is simply dropped and the method return without
* doing anything (no VSync).
*
* - if vsync_spacing = 0, upload to the screen start immediately unless there is already a
* transfer in progress in which case the method waits until the transfer completes and then
* starts another async transfer immediately (no VSync).
*
* - if vsync_spacing > 0. screen upload is synchronized with the screen refresh and the
* method waits until vsync_spacing refreshes have occurred since the previous update to
* insure a constant framerate equal to (refresh_rate/vsync_spacing). If a transfer is
* already in progress, it waits for it to complete before scheduling the next transfer
* via DMA and returning.
*
*
* NOTE:
* (1) double buffering give a HUGE improvement over the no buffering method at the
* expense of an additional internal memory framebuffer (150Kb).
*
* (2) Setting two diffs buffers instead of one cost only a few additional kilobytes
* yet will usually improve the max framerate significantly since it enables the
* driver to compute the next diff while the previous update is still ongoing.
*
*
* ADVICE: US AN INTERNAL FRAMEBUFFER + 2 DIFF BUFFERS (WITH SIZE RANGING FROM 5K TO 10K).
*
**/
void update(const uint16_t* fb, bool force_full_redraw = false);
/**
* PARTIAL SCREEN UPDATE METHOD
*
* Update only part of the screen. The behavior of the method depend on the current buffering
* mode and the vsync_spacing parameter.
*
* WHEN THE METHOD RETURNS, THE FRAME MAY OR MAY NOT ALREADY BE DISPLAYED ON THE SCREEN BUT
* THE INPUT FRAMEBUFFER fb CAN STILL BE REUSED IMMEDIATELY IN ANY CASE (A COPY IS MADE WHEN
* USING ASYNC UPDATES).
*
* Parameters:
*
* - fb : framebuffer to the rectangular region to update.
*
* - [xmin, xmax] x [ymin, ymax] : region of the screen to update
*
* - stride : stride for the supplied framebuffer fb
*
* The layout of fb is such that,
*
* screen pixel(xmin + i, ymin + j) = fb[i + stride*j]
*
* -> If stride is not specified, it defaults to (xmax - xmin + 1) which is the
* width of the rectangular region.
*
* - redrawNow: - If set to true, the screen is redrawn immediately (async if an internal
* - framebuffer is set).
* - If set to false and an internal framebuffer is available, then the changes
* are stored in the internal framebuffer but are not drawn on the screen.
* This permits to call regionUpdate() several times without drawing onto the
* screen and then draw all the changes simultaneously when needed. This is
* particularly convenient when using the lvgl library.
*
*
* NOTE: (1) Similarly to the 'update()' method, this method will use VSync when enabled
* depending on the value of the vsync_spacing parameter
*
* (2) In there is no internal buffer, then screen is updated immediately even if
* redrawNow=false.
*
* (3) For this method, TWO DIFF BUFFERS ARE REQUIRED FOR DIFFERENTIAL UPDATE !
* Setting only one diff buffer will disable differential updates :(
*
**/
void updateRegion(bool redrawNow, const uint16_t* fb, int xmin, int xmax, int ymin, int ymax, int stride = -1);
/**
* Wait until any currently ongoing async update completes.
*
* Returns immediately if no update is ongoing.
*
* NOTE: This method should not be called normally it will create a
"busy wait" and wastes precious CPU time...
**/
void waitUpdateAsyncComplete() { _waitUpdateAsyncComplete(); }
/**
* Return true if an Async update is currently ongoing and false otherwise.
**/
bool asyncUpdateActive() const { return (_dma_state != ILI9341_T4_DMA_IDLE); }
/***************************************************************************************************
****************************************************************************************************
*
* Statistics
*
* The driver monitor many stats which are useful for performance optimization. Two methods are
* particularly useful:
*
* - overlayFPS() : add an FPS counter on a corner of the screen
* - printStats() : Print out all the statistics on the output stream.
*
* Note: Some methods return a 'StatsVar' object which is a class that holds stats about a sequence
* of values: c.f. StatsVar.h for more info.
*