forked from sparkfun/SparkFun_Qwiic_OLED_Arduino_Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqwiic_grssd1306.cpp
1031 lines (871 loc) · 33.9 KB
/
qwiic_grssd1306.cpp
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
// qwiic_grssd1306.cpp
//
// This is a library written for SparkFun Qwiic OLED boards that use the
// SSD1306.
//
// SparkFun sells these at its website: www.sparkfun.com
//
// Do you like this library? Help support SparkFun. Buy a board!
//
// Micro OLED https://www.sparkfun.com/products/14532
// Transparent OLED https://www.sparkfun.com/products/15173
// "Narrow" OLED https://www.sparkfun.com/products/17153
//
//
// Written by Kirk Benell @ SparkFun Electronics, March 2022
//
// This library configures and draws graphics to OLED boards that use the
// SSD1306 display hardware. The library only supports I2C.
//
// Repository:
// https://github.com/sparkfun/SparkFun_Qwiic_OLED_Arduino_Library
//
// Documentation:
// https://sparkfun.github.io/SparkFun_Qwiic_OLED_Arduino_Library/
//
//
// SparkFun code, firmware, and software is released under the MIT
// License(http://opensource.org/licenses/MIT).
//
// SPDX-License-Identifier: MIT
//
// The MIT License (MIT)
//
// Copyright (c) 2022 SparkFun Electronics
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions: The
// above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
// NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "qwiic_grssd1306.h"
/////////////////////////////////////////////////////////////////////////////
// Class that implements graphics support for devices that use the SSD1306
//
/////////////////////////////////////////////////////////////////////////////
// Device Commands
//
// The commands are codes used to communicate with the SSD1306 device and are
// from the devices datasheet.
//
#define kCmdSetContrast 0x81
#define kCmdDisplayAllOnResume 0xA4
#define kCmdDisplayAllOn 0xA5
#define kCmdNormalDisplay 0xA6
#define kCmdInvertDisplay 0xA7
#define kCmdDisplayOff 0xAE
#define kCmdDisplayOn 0xAF
#define kCmdSetDisplayOffset 0xD3
#define kCmdSetComPins 0xDA
#define kCmdSetVComDeselect 0xDB
#define kCmdSetDisplayClockDiv 0xD5
#define kCmdSetPreCharge 0xD9
#define kCmdSetMultiplex 0xA8
#define kCmdSetLowColumn 0x00
#define kCmdSetHighColumn 0x10
#define kCmdSetStartLine 0x40
#define kCmdMemoryMode 0x20
#define kCmdComScanInc 0xC0
#define kCmdComScanDec 0xC8
#define kCmdSegRemap 0xA0
#define kCmdChargePump 0x8D
#define kCmdExternalVCC 0x01
#define kCmdSwitchCapVCC 0x02
#define kCmdPageAddress 0x22
#define kCmdColumnAddress 0x21
#define kCmdActivateScroll 0x2F
#define kCmdDeactivateScroll 0x2E
#define kCmdSetVerticalScrollArea 0xA3
#define kCmdRightHorizontalScroll 0x26
#define kCmdLeftHorizontalScroll 0x27
#define kCmdVerticalRightHorzScroll 0x29
#define kCmdVerticalLeftHorzScroll 0x2A
#define kCmdPageModePageBase 0xB0
#define kCmdPageModeColTopBase 0x10
#define kCmdPageModeColLowBase 0x0F
//////////////////////////////////////////////////////////////////////////////////
// Screen Buffer
//
// A key feature of this library is that it only sends "dirty" pixels to the
// device, minimizing data transfer over the I2C bus. To accomplish this, the
// dirty range of each graphics buffer page (see device memory layout in the
// datasheet) is maintained during drawing operation. Whe data is sent to the
// device, only the pixels in these regions are sent to the device, not the
// entire page of data.
//
// The below macros are used to manage the record keeping of dirty page ranges.
// Given that these actions are taking place in the draw loop, macros are used
// for performance considerations.
//
// These macros work with the pageState_t struct type.
//
// Define unique values just outside of the screen buffer (SSD1306) page range
// (0 base) Note: A page is 128 bits in length
#define kPageMin -1 // outside bounds - low value
#define kPageMax 128 // outside bounds - high value
// clean/ no settings in the page
#define pageIsClean(_page_) (_page_.xmin == kPageMax)
// Macro to reset page descriptor
#define pageSetClean(_page_) \
do { \
_page_.xmin = kPageMax; \
_page_.xmax = kPageMin; \
} while (false)
// Macro to check and adjust record bounds based on a single location
#define pageCheckBounds(_page_, _x_) \
do { \
if (_x_ < _page_.xmin) \
_page_.xmin = _x_; \
if (_x_ > _page_.xmax) \
_page_.xmax = _x_; \
} while (false)
// Macro to check and adjust record bounds using another page descriptor
#define pageCheckBoundsDesc(_page_, _page2_) \
do { \
if (_page2_.xmin < _page_.xmin) \
_page_.xmin = _page2_.xmin; \
if (_page2_.xmax > _page_.xmax) \
_page_.xmax = _page2_.xmax; \
} while (false)
// Macro to check and adjust record bounds using bounds values
#define pageCheckBoundsRange(_page_, _x0_, _x1_) \
do { \
if (_x0_ < _page_.xmin) \
_page_.xmin = _x0_; \
if (_x1_ > _page_.xmax) \
_page_.xmax = _x1_; \
} while (false)
//////////////////////////////////////////////////////////////////////////////////
// Communication
//
// When communicating with the device, you either send commands or data. Define
// our codes for these two options - these are basically i2c registers/offsets.
//
// See datasheet for details
//
#define kDeviceSendCommand 0x00
#define kDeviceSendData 0x40
////////////////////////////////////////////////////////////////////////////////////
// Pixel write/set operations
//
// Using LAMBDAs to create fast raster write/set operations. Using this pattern
// eleminates the need for switch/if statements in each draw routine. This is
// basically classic ROPs'
//
// NOTE - the order in the arrays is based on grRasterOp_t enum
//
// The Graphic operator functions (ROPS)
// - Copy - copy the pixel value in to the buffer (default)
// - Not Copy - copy the not of the pixel value to buffer
// - Not - Set the buffer value to not it's current value
// - XOR - XOR of color and current pixel value
// - Black - Set value to always be black
// - White - set value to always be white
typedef void (*rasterOPsFn)(uint8_t* dest, uint8_t src, uint8_t mask);
static const rasterOPsFn m_rasterOps[] = {
// COPY
[](uint8_t* dst, uint8_t src, uint8_t mask) -> void {
*dst = (~mask & *dst) | (src & mask);
},
// NOT COPY
[](uint8_t* dst, uint8_t src, uint8_t mask) -> void {
*dst = (~mask & *dst) | ((!src) & mask);
},
// NOT DEST
[](uint8_t* dst, uint8_t src, uint8_t mask) -> void {
*dst = (~mask & *dst) | ((!(*dst)) & mask);
},
// XOR
[](uint8_t* dst, uint8_t src, uint8_t mask) -> void {
*dst = (~mask & *dst) | ((*dst ^ src) & mask);
},
// Always Black
[](uint8_t* dst, uint8_t src, uint8_t mask) -> void {
*dst = ~mask & *dst;
},
// Always White
[](uint8_t* dst, uint8_t src, uint8_t mask) -> void {
*dst = mask | *dst;
}
};
////////////////////////////////////////////////////////////////////////////////////
// Constructor
//
// Just a bunch of member variable inits
QwGrSSD1306::QwGrSSD1306()
: default_address { 0 }
, m_pBuffer { nullptr }
, m_color { 1 }
, m_rop { grROPCopy }
, m_i2cBus { nullptr }
, m_i2cAddress { 0 }
, m_initHWComPins { kDefaultPinConfig }
, m_initPreCharge { kDefaultPreCharge }
, m_initVCOMDeselect { kDefaultVCOMDeselect }
, m_initContrast { kDefaultContrast }
, m_isInitialized { false }
{
}
////////////////////////////////////////////////////////////////////////////////////
// init()
//
// Called by user when the device/system is up and ready to be "initialized."
//
// This implementation performs the basic setup for the SSD1306 device
//
// The startup sequence is as follows:
//
// - Make sure a device is connected
// - Call super class
// - Shutdown the device (display off), initial device setup, turn on
// device
// - Init the local graphics buffers/system
//
// When this method is complete, the driver and device are ready for use
//
bool QwGrSSD1306::init(void)
{
if (m_isInitialized)
return true;
// do we have a bus yet? Buffer? Note - buffer is set by subclass of this
// object
if (!m_i2cBus || !m_i2cAddress || !m_pBuffer)
return false;
// Is the device connected?
if (!m_i2cBus->ping(m_i2cAddress))
return false;
// Super-class
if (!this->QwGrBufferDevice::init())
return false; // something isn't right
// setup the oled device
setupOLEDDevice();
// Finish up setting up this object
// Number of pages used for this device?
m_nPages = m_viewport.height / kByteNBits; // height / number of pixels per byte.
// TODO - support multiples != 8
// init the graphics buffers
initBuffers();
m_isInitialized = true; // we're ready to rock
return true;
}
////////////////////////////////////////////////////////////////////////////////////
// reset()
//
// Return the OLED system to its initial state
//
// Returns true on success, false on failure
bool QwGrSSD1306::reset(bool clearDisplay)
{
// If we are not in an init state, just call init
if (!m_isInitialized)
return init();
// is the device connected?
if (!m_i2cBus->ping(m_i2cAddress))
return false;
// setup oled
setupOLEDDevice(clearDisplay);
// Init internal/drawing buffers and device screen buffer
if(clearDisplay)
initBuffers();
return true;
}
////////////////////////////////////////////////////////////////////////////////////
// Configuration API
//
// This allows sub-classes to setup for their device, while preserving
// encapsulation.
//
// These should be called/set before calling init
//
// For details of each of these settings -- see the datasheet
//
void QwGrSSD1306::setCommPins(uint8_t pin_code)
{
m_initHWComPins = pin_code;
}
void QwGrSSD1306::setPreCharge(uint8_t pre_charge)
{
m_initPreCharge = pre_charge;
}
void QwGrSSD1306::setVcomDeselect(uint8_t vcom_d)
{
m_initVCOMDeselect = vcom_d;
}
void QwGrSSD1306::setContrast(uint8_t contrast)
{
if (!m_isInitialized)
m_initContrast = contrast;
else
sendDevCommand(kCmdSetContrast, contrast);
}
////////////////////////////////////////////////////////////////////////////////////
// setupOLEDDevice()
//
// Method sends the init/setup commands to the OLED device, placing
// it in a state for use by this driver/library.
void QwGrSSD1306::setupOLEDDevice(bool clearDisplay)
{
// Start the device setup - sending commands to device. See command defs in
// header, and device datasheet
if(clearDisplay)
sendDevCommand(kCmdDisplayOff);
sendDevCommand(kCmdSetDisplayClockDiv, 0x80);
sendDevCommand(kCmdSetMultiplex, m_viewport.height - 1);
sendDevCommand(kCmdSetDisplayOffset, 0x0);
sendDevCommand(kCmdSetStartLine | 0x0);
sendDevCommand(kCmdChargePump, 0x14);
sendDevCommand(kCmdMemoryMode, 0b10); // Page Addressing mode
sendDevCommand(kCmdNormalDisplay);
sendDevCommand(kCmdDisplayAllOnResume);
sendDevCommand(kCmdSegRemap | 0x1);
sendDevCommand(kCmdComScanDec);
sendDevCommand(kCmdSetComPins, m_initHWComPins);
sendDevCommand(kCmdSetContrast, m_initContrast);
sendDevCommand(kCmdSetPreCharge, m_initPreCharge);
sendDevCommand(kCmdSetVComDeselect, m_initVCOMDeselect);
sendDevCommand(kCmdDeactivateScroll);
if(clearDisplay)
sendDevCommand(kCmdDisplayOn);
}
////////////////////////////////////////////////////////////////////////////////////
// setCommBus()
//
// Method to set the bus object that is used to communicate with the device
//
// TODO - In the *future*, generalize to match SDK
void QwGrSSD1306::setCommBus(QwI2C& theBus, uint8_t id_bus)
{
m_i2cBus = &theBus;
m_i2cAddress = id_bus;
}
////////////////////////////////////////////////////////////////////////////////////
// setBuffer()
//
// Protected method - used by sub-class to set the graphics buffer array.
//
// The subclass knows the size of the specific device, so it statically defines
// the graphics buffer array. The buffer is often set in the subclasses
// on_initialize() method.
//
//
void QwGrSSD1306::setBuffer(uint8_t* pBuffer)
{
if (pBuffer)
m_pBuffer = pBuffer;
}
////////////////////////////////////////////////////////////////////////////////////
// clearScreenBuffer()
//
// Clear out all the on-device memory.
//
void QwGrSSD1306::clearScreenBuffer(void)
{
// Clear out the screen buffer on the device
uint8_t emptyPage[kPageMax] = { 0 };
for (int i = 0; i < kMaxPageNumber; i++) {
setScreenBufferAddress(i, 0); // start of page
sendDevData((uint8_t*)emptyPage, kPageMax); // clear out page
}
}
////////////////////////////////////////////////////////////////////////////////////
// initBuffers()
//
// Will clear the local graphics buffer, and the devices screen buffer. Also
// resets page state descriptors to a "clean" state.
void QwGrSSD1306::initBuffers(void)
{
int i;
// clear out the local graphics buffer
if (m_pBuffer)
memset(m_pBuffer, 0, m_viewport.width * m_nPages);
// Set page descs to "clean" state
for (i = 0; i < m_nPages; i++) {
pageSetClean(m_pageState[i]);
pageSetClean(m_pageErase[i]);
}
m_pendingErase = false;
// clear out the screen buffer
clearScreenBuffer();
}
////////////////////////////////////////////////////////////////////////////////////
// resendGraphics()
//
// Re-send the region in the graphics buffer (local) that contains drawn
// graphics. This region is defined by the contents of the m_pageErase
// descriptors.
//
// Copy these to the page state, and call display
//
void QwGrSSD1306::resendGraphics(void)
{
// Set the page state dirty bounds to the bounds of erase state
for (int i = 0; i < m_nPages; i++)
m_pageState[i] = m_pageErase[i];
display(); // push bits to screen buffer
}
////////////////////////////////////////////////////////////////////////////////////
// Screen Control
////////////////////////////////////////////////////////////////////////////////////
// flip_vert()
//
// Flip the onscreen graphics vertically.
void QwGrSSD1306::flipVert(bool bFlip)
{
sendDevCommand((bFlip ? kCmdComScanInc : kCmdComScanDec));
}
////////////////////////////////////////////////////////////////////////////////////
// flip_horz()
//
// Flip the onscreen graphcis horizontally. This requires a resend of the
// graphics data to the device/screen buffer.
//
void QwGrSSD1306::flipHorz(bool bFlip)
{
sendDevCommand(kCmdSegRemap | (bFlip ? 0x0 : 0x1));
clearScreenBuffer();
resendGraphics();
}
////////////////////////////////////////////////////////////////////////////////////
// invert()
//
// Inverts the display contents on device
//
void QwGrSSD1306::invert(bool bInvert)
{
sendDevCommand((bInvert ? kCmdInvertDisplay : kCmdNormalDisplay));
}
////////////////////////////////////////////////////////////////////////////////////
void QwGrSSD1306::stopScroll(void)
{
sendDevCommand(kCmdDeactivateScroll);
// After sending a deactivate command, the ram data in the device needs to be
// re-written. See datasheet
//
// First clear out the entire screen buffer (on device mem). The device uses
// this off screen area to scroll - if you don't erase it, when scroll starts
// back up, old graphics turds will appear ...
//
// Second - Send over the graphics again to the display
clearScreenBuffer();
resendGraphics();
}
////////////////////////////////////////////////////////////////////////////////////
// scroll()
//
// Set scroll parametes on the device and start scrolling
//
void QwGrSSD1306::scroll(uint16_t scroll_type, uint8_t start, uint8_t stop,
uint8_t interval)
{
// parameter sanity?
if (stop < start)
return;
// Setup a default command list
uint8_t n_commands = 7;
uint8_t commands[7] = {
kCmdRightHorizontalScroll, // default scroll right
0x00, // dummy byte
start, // start page address
interval, // interval between scroll steps - in terms of frame fequency
stop, // end page address
0x00, // dummy byte for non vert, for vert it's scroll offset
0xFF
}; // Dummy byte for non vert - set to FFX, not used for vert.
// Which way to scroll
switch (scroll_type) {
case SCROLL_RIGHT:
break; // set in initializer of command array
case SCROLL_LEFT:
commands[0] = kCmdLeftHorizontalScroll;
break;
case SCROLL_VERT_LEFT:
commands[0] = kCmdVerticalLeftHorzScroll;
break;
case SCROLL_VERT_RIGHT:
commands[0] = kCmdVerticalRightHorzScroll;
break;
}
// If we are scrolling vertically, modify the command list, and set the
// vertical scroll area on display
if (scroll_type & SCROLL_VERTICAL) {
commands[5] = 0x01; // set the scrolling offset
n_commands--; // don't use the last byte of command buffer
// Set on display scroll area
sendDevCommand(kCmdSetVerticalScrollArea, 0x00);
sendDevCommand(m_viewport.height);
}
// send the scroll commands to the device
// Do not use scroll_stop() - that method resets the display - memory ...etc -
// to it's start state - the graphics displayed before scrolling was initially
// started.
//
// Here, we just stop scrolling and keep device memory state as is. This
// allows scrolling to change paraterms during a scroll session - gives a
// smooth presentation on screen.
sendDevCommand(kCmdDeactivateScroll);
sendDevCommand(commands, n_commands);
sendDevCommand(kCmdActivateScroll);
}
////////////////////////////////////////////////////////////////////////////////////
// displayPower()
//
// Used to set the power of the screen.
void QwGrSSD1306::displayPower(bool enable)
{
if (!m_isInitialized)
return;
sendDevCommand((enable ? kCmdDisplayOn : kCmdDisplayOff));
}
////////////////////////////////////////////////////////////////////////////////////
// Drawing Methods
////////////////////////////////////////////////////////////////////////////////////
// erase()
//
// Erase the graphics that are on screen and anything that's been draw but
// haven't been sent to the screen.
//
void QwGrSSD1306::erase(void)
{
if (!m_pBuffer)
return;
// Cleanup the dirty parts of each page in the graphics buffer.
for (uint8_t i = 0; i < m_nPages; i++) {
// m_pageState
// The current "dirty" areas of the graphics [local] buffer.
// Areas that haven't been sent to the screen/device but are
// "dirty"
//
// Add the areas with pixels set and have been sent to the
// device - this is the contents of m_pageErase
pageCheckBoundsDesc(m_pageState[i], m_pageErase[i]);
// if this page is clean, there is nothing to update
if (pageIsClean(m_pageState[i]))
continue;
// clear out memory that is dirty on this page
memset(m_pBuffer + i * m_viewport.width + m_pageState[i].xmin, 0,
m_pageState[i].xmax - m_pageState[i].xmin + 1); // add one b/c values are 0 based
// clear out any pending dirty range for this page - it's erased
pageSetClean(m_pageState[i]);
}
// Indicate that the data transfer to the device should include the erase
// region
m_pendingErase = true;
}
////////////////////////////////////////////////////////////////////////////////////
//
// draw_pixel()
//
// Used to set a pixel in the graphics buffer - uses the current write operator
// function
//
void QwGrSSD1306::drawPixel(uint8_t x, uint8_t y, uint8_t clr)
{
// quick sanity check on range
if (x >= m_viewport.width || y >= m_viewport.height)
return; // out of bounds
uint8_t bit = byte_bits[mod_byte(y)];
m_rasterOps[m_rop](
m_pBuffer + x + y / kByteNBits * m_viewport.width, // pixel offset
(clr ? bit : 0), bit); // which bit to set in byte
pageCheckBounds(m_pageState[y / kByteNBits],
x); // update dirty range for page
}
////////////////////////////////////////////////////////////////////////////////////
// draw_line_horz()
//
// Fast horizontal line drawing routine
//
void QwGrSSD1306::drawLineHorz(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1,
uint8_t clr)
{
// Basically we set a bit within a range in a page of our graphics buffer.
// in range
if (y0 >= m_viewport.height)
return;
if (x0 > x1)
swap_int(x0, x1);
if (x1 >= m_viewport.width)
x1 = m_viewport.width - 1;
uint8_t bit = byte_bits[mod_byte(y0)]; // bit to set
rasterOPsFn curROP = m_rasterOps[m_rop]; // current raster op
// Get the start of this line in the graphics buffer
uint8_t* pBuffer = m_pBuffer + x0 + y0 / kByteNBits * m_viewport.width;
// walk up x and set the target pixel using the pixel operator function
for (int i = x0; i <= x1; i++, pBuffer++)
curROP(pBuffer, (clr ? bit : 0), bit);
// Mark the page dirty for the range drawn
pageCheckBoundsRange(m_pageState[y0 / kByteNBits], x0, x1);
}
////////////////////////////////////////////////////////////////////////////////////
// draw_line_vert()
//
// Fast vertical line drawing routine - also supports fast filled rects
//
void QwGrSSD1306::drawLineVert(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1,
uint8_t clr)
{
if (x0 >= m_viewport.width) // out of bounds
return;
// want an accending order
if (y0 > y1)
swap_int(y0, y1);
// keep on screen
if (y1 >= m_viewport.height)
y1 = m_viewport.height - 1;
uint8_t startBit, endBit, setBits;
// Get the start and end pages we are writing to
uint8_t page0 = y0 / kByteNBits;
uint8_t page1 = y1 / kByteNBits;
// loop over the pages. For each page determine the range of pixels
// to set in the target page byte and then set them using the current
// pixel operator function
// Note: This function can also be used to draw filled rects - just iterate
// in the x direction. The base rect fill (in grBuffer) calls this
// method x1-x0 times, and each of those calls has some overhead. So
// just iterating over each page - x1-x0 times here - saves overhead
// costs.
//
// To make this work, make sure x0 > x1. Also, this method is wired in
// as the draw_rect_filled entry in the draw interface. This is done
// above in the init process.
int xinc;
if (x0 > x1)
swap_int(x0, x1);
rasterOPsFn curROP = m_rasterOps[m_rop]; // current raster op
for (int i = page0; i <= page1; i++) {
startBit = mod_byte(y0); // start bit in this byte
// last bit of this byte to set? Does the line end in this byte, or continue
// on...
endBit = y0 + kByteNBits - startBit > y1 ? mod_byte(y1) : kByteNBits - 1;
// Set the bits from startBit to endBit
setBits = (0xFF >> ((kByteNBits - endBit) - 1))
<< startBit; // what bits are being set in this byte
// set the bits in the graphics buffer using the current byte operator
// function
// Note - We iterate over x to fill in a rect if specified.
for (xinc = x0; xinc <= x1; xinc++)
curROP(m_pBuffer + i * m_viewport.width + xinc, (clr ? setBits : 0),
setBits);
y0 += endBit - startBit + 1; // increment Y0 to next page
pageCheckBoundsRange(m_pageState[i], x0,
x1); // mark dirty range in page desc
}
}
////////////////////////////////////////////////////////////////////////////////////////
// draw_rect_fill()
//
// Does the actual drawing/logic
void QwGrSSD1306::drawRectFilled(uint8_t x0, uint8_t y0, uint8_t width,
uint8_t height, uint8_t clr)
{
uint8_t x1 = x0 + width - 1;
uint8_t y1 = y0 + height - 1;
// just call vert line
drawLineVert(x0, y0, x1, y1, clr);
}
////////////////////////////////////////////////////////////////////////////////////
// draw_bitmap()
//
// Draw a 8 bit encoded (aka same y layout as this device) bitmap to the screen
//
void QwGrSSD1306::drawBitmap(uint8_t x0, uint8_t y0, uint8_t dst_width,
uint8_t dst_height, uint8_t* pBitmap,
uint8_t bmp_width, uint8_t bmp_height)
{
// some simple checks
if (x0 >= m_viewport.width || y0 >= m_viewport.height || !bmp_width || !bmp_height)
return;
// Bounds check
if (x0 + dst_width > m_viewport.width) // out of bounds
dst_width = m_viewport.width - x0;
if (bmp_width < dst_width)
dst_width = bmp_width;
if (y0 + dst_height > m_viewport.height) // out of bounds
dst_height = m_viewport.height - y0;
if (bmp_height < dst_height)
dst_height = bmp_height;
// current position in the bitmap
uint8_t bmp_x = 0;
uint8_t bmp_y = 0;
uint8_t page0, page1;
uint8_t startBit, endBit, grSetBits, grStartBit;
uint8_t bmp_mask[2], bmp_data, bmpPage;
uint8_t remainingBits, neededBits;
uint8_t y1 = y0 + dst_height - 1;
page0 = y0 / kByteNBits;
page1 = y1 / kByteNBits;
rasterOPsFn curROP = m_rasterOps[m_rop]; // current raster op
// The Plan:
// - Walk down the graphics buffer range (y) one page at a time
// - For each page
// - Determine needed number of bits for the destination
// - Determine what bits to pull from the bitmap
// - Create a mask to pull out bits - from one or two bytes
// - Loop over the x dimension
// - pull bits from bitmap, build byte of data of bitmap bits, in
// right order for the destination (graphics buffer)
// - Write the bitmap bits to the graphis buffer using the
// current operator
// Loop over the memory pages in the graphics buffer
for (int iPage = page0; iPage <= page1; iPage++) {
// First, get the number of destination bits in the current page
grStartBit = mod_byte(y0); // start bit
// last bit of this byte to set? Does the copy region end in this byte, or
// continue on...
endBit = y0 + kByteNBits - grStartBit > y1 ? mod_byte(y1) : kByteNBits - 1;
// Set the bits from startBit to endBit
grSetBits = (0xFF >> (kByteNBits - endBit - 1))
<< grStartBit; // what bits are being set in this byte
// how many bits of data do we need to transfer from the bitmap?
neededBits = endBit - grStartBit + 1;
// Okay, we have how much data to transfer to the current page. Now build
// the data from the bitmap.
// First, build bit masks for pulling the data out of the bmp array. The
// data might straddle two bytes, so build two masks
// as above, get the start and end bites for the current position in the
// bmp.
startBit = mod_byte(bmp_y);
endBit = (kByteNBits - startBit > neededBits ? startBit + neededBits : kByteNBits) - 1;
// Set the bits from startBit to endBit
bmp_mask[0] = (0xFF >> (kByteNBits - endBit - 1)) << startBit;
// any remaining bits to get?
remainingBits = neededBits - (endBit - startBit + 1); // +1 - needsBits is 1's based
bmp_mask[1] = 0xFF >> (kByteNBits - remainingBits);
// What row in the source bitmap
bmpPage = bmp_y / kByteNBits;
// we have the mask for the bmp - loop over the width of the copy region,
// pulling out bmp data and writing it to the graphics buffer
for (bmp_x = 0; bmp_x < dst_width; bmp_x++) {
// get data bits out of current bitmap location and shift if needed
bmp_data = (pBitmap[bmp_width * bmpPage + bmp_x] & bmp_mask[0]) >> startBit;
if (remainingBits) // more data to add from the next byte in this column
bmp_data |= (pBitmap[bmp_width * (bmpPage + 1) + bmp_x] & bmp_mask[1])
<< (neededBits - remainingBits);
// Write the bmp data to the graphics buffer - using current write op.
// Note, if the location in the buffer didn't start at bit 0, we shift
// bmp_data
curROP(m_pBuffer + iPage * m_viewport.width + bmp_x + x0,
bmp_data << grStartBit, grSetBits);
}
// move up our y values (graphics buffer and bitmap) by the number of bits
// transferred
y0 += neededBits;
bmp_y += neededBits;
pageCheckBoundsRange(m_pageState[iPage], x0,
x0 + dst_width); // mark dirty range in page desc
}
}
////////////////////////////////////////////////////////////////////////////////////
// Device Update Methods
////////////////////////////////////////////////////////////////////////////////////
// setScreenBufferAddress()
//
// Sets the target screen buffer address for graphics buffer transfer to the
// device.
//
// The positon is specified by page and column
//
// The system runs in "page mode" - data is streamed along a page, based
// on the set starting position.
//
// This class takes advantage of this to just write the "dirty" ranges in a
// page.
//
bool QwGrSSD1306::setScreenBufferAddress(uint8_t page, uint8_t column)
{
if (page >= m_nPages || column >= m_viewport.width)
return false;
// send the page address
sendDevCommand(kCmdPageModePageBase | page);
// For the column start address, add the viewport x offset. Some devices
// (Micro OLED) don't start at column 0 in the screen buffer
sendDevCommand((kCmdPageModeColTopBase | (column >> 4)) + m_viewport.x);
sendDevCommand(kCmdPageModeColLowBase & column);
return true;
}
////////////////////////////////////////////////////////////////////////////////////
// display()
//
// Send the "dirty" areas of the graphics buffer to the device's screen buffer.
// Only send the areas that need to be updated. The update region is based on
// new graphics to display, and any currently displayed items that need to be
// erased.
void QwGrSSD1306::display()
{
// Loop over our page descriptors - if a page is dirty, send the graphics
// buffer dirty region to the device for the current page
pageState_t transferRange;
for (int i = 0; i < m_nPages; i++) {
// We keep the erase rect seperate from dirty rect. Make temp copy of
// dirty rect page range, expand to include erase rect page range.
transferRange = m_pageState[i];
// If an erase has happend, we need to transfer/include erase update range
if (m_pendingErase)
pageCheckBoundsDesc(transferRange, m_pageErase[i]);
if (pageIsClean(transferRange)) // both dirty and erase range for this
// page were null
continue; // next
// set the start address to write the updated data to the devices screen
// buffer
setScreenBufferAddress(i, transferRange.xmin);
// send the dirty data to the device
sendDevData(m_pBuffer + (i * m_viewport.width) + transferRange.xmin, // this page start + xmin
transferRange.xmax - transferRange.xmin + 1); // dirty region xmax - xmin. Add 1 b/c 0 based
// If we sent the erase bounds, zero out the erase bounds - this area is now
// clear
if (m_pendingErase)
pageSetClean(m_pageErase[i]);
// add the just send dirty range (non erase rec) to the erase rect
pageCheckBoundsDesc(m_pageErase[i], m_pageState[i]);
// this page is no longer dirty - mark it clean
pageSetClean(m_pageState[i]);
}
m_pendingErase = false; // no longer pending
}
////////////////////////////////////////////////////////////////////////////////////
// Device communication methods
////////////////////////////////////////////////////////////////////////////////////
// sendDeviceCommand()
//
// send a single command to the device via the current bus object
void QwGrSSD1306::sendDevCommand(uint8_t command)
{
m_i2cBus->writeRegisterByte(m_i2cAddress, kDeviceSendCommand, command);
}
////////////////////////////////////////////////////////////////////////////////////
// sendDeviceCommand()
//
// send a single command and value to the device via the current bus object.