2 Copyright 2019 Ryan Caltabiano <https://github.com/XScorpion2>
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "i2c_master.h"
18 #include "oled_driver.h"
27 #include <avr/pgmspace.h>
28 #elif defined(ESP8266)
30 #else // defined(ESP8266)
32 #define memcpy_P(des, src, len) memcpy(des, src, len)
33 #endif // defined(__AVR__)
35 // Used commands from spec sheet: https://cdn-shop.adafruit.com/datasheets/SSD1306.pdf
36 // for SH1106: https://www.velleman.eu/downloads/29/infosheets/sh1106_datasheet.pdf
38 // Fundamental Commands
40 #define DISPLAY_ALL_ON 0xA5
41 #define DISPLAY_ALL_ON_RESUME 0xA4
42 #define NORMAL_DISPLAY 0xA6
43 #define DISPLAY_ON 0xAF
44 #define DISPLAY_OFF 0xAE
48 #define ACTIVATE_SCROLL 0x2F
49 #define DEACTIVATE_SCROLL 0x2E
50 #define SCROLL_RIGHT 0x26
51 #define SCROLL_LEFT 0x27
52 #define SCROLL_RIGHT_UP 0x29
53 #define SCROLL_LEFT_UP 0x2A
55 // Addressing Setting Commands
56 #define MEMORY_MODE 0x20
57 #define COLUMN_ADDR 0x21
58 #define PAGE_ADDR 0x22
59 #define PAM_SETCOLUMN_LSB 0x00
60 #define PAM_SETCOLUMN_MSB 0x10
61 #define PAM_PAGE_ADDR 0xB0 // 0xb0 -- 0xb7
63 // Hardware Configuration Commands
64 #define DISPLAY_START_LINE 0x40
65 #define SEGMENT_REMAP 0xA0
66 #define SEGMENT_REMAP_INV 0xA1
67 #define MULTIPLEX_RATIO 0xA8
68 #define COM_SCAN_INC 0xC0
69 #define COM_SCAN_DEC 0xC8
70 #define DISPLAY_OFFSET 0xD3
72 #define COM_PINS_SEQ 0x02
73 #define COM_PINS_ALT 0x12
74 #define COM_PINS_SEQ_LR 0x22
75 #define COM_PINS_ALT_LR 0x32
77 // Timing & Driving Commands
78 #define DISPLAY_CLOCK 0xD5
79 #define PRE_CHARGE_PERIOD 0xD9
80 #define VCOM_DETECT 0xDB
82 // Charge Pump Commands
83 #define CHARGE_PUMP 0x8D
86 #define OLED_TIMEOUT 60000
87 #define OLED_BLOCK_COUNT (sizeof(OLED_BLOCK_TYPE) * 8)
88 #define OLED_BLOCK_SIZE (OLED_MATRIX_SIZE / OLED_BLOCK_COUNT)
94 // already defined on ARM
95 #define I2C_TIMEOUT 100
96 #define I2C_TRANSMIT_P(data) i2c_transmit_P((OLED_DISPLAY_ADDRESS << 1), &data[0], sizeof(data), I2C_TIMEOUT)
97 #else // defined(__AVR__)
98 #define I2C_TRANSMIT_P(data) i2c_transmit((OLED_DISPLAY_ADDRESS << 1), &data[0], sizeof(data), I2C_TIMEOUT)
99 #endif // defined(__AVR__)
100 #define I2C_TRANSMIT(data) i2c_transmit((OLED_DISPLAY_ADDRESS << 1), &data[0], sizeof(data), I2C_TIMEOUT)
101 #define I2C_WRITE_REG(mode, data, size) i2c_writeReg((OLED_DISPLAY_ADDRESS << 1), mode, data, size, I2C_TIMEOUT)
103 #define HAS_FLAGS(bits, flags) ((bits & flags) == flags)
105 // Display buffer's is the same as the OLED memory layout
106 // this is so we don't end up with rounding errors with
107 // parts of the display unusable or don't get cleared correctly
108 // and also allows for drawing & inverting
109 uint8_t oled_buffer[OLED_MATRIX_SIZE];
110 uint8_t* oled_cursor;
111 OLED_BLOCK_TYPE oled_dirty = 0;
112 bool oled_initialized = false;
113 bool oled_active = false;
114 bool oled_scrolling = false;
115 uint8_t oled_rotation = 0;
116 uint8_t oled_rotation_width = 0;
117 #if !defined(OLED_DISABLE_TIMEOUT)
118 uint16_t oled_last_activity;
121 // Internal variables to reduce math instructions
124 // identical to i2c_transmit, but for PROGMEM since all initialization is in PROGMEM arrays currently
125 // probably should move this into i2c_master...
126 static i2c_status_t i2c_transmit_P(uint8_t address, const uint8_t* data, uint16_t length, uint16_t timeout) {
127 i2c_status_t status = i2c_start(address | I2C_WRITE, timeout);
129 for (uint16_t i = 0; i < length && status >= 0; i++) {
130 status = i2c_write(pgm_read_byte((const char*)data++), timeout);
140 // Flips the rendering bits for a character at the current cursor position
141 static void InvertCharacter(uint8_t *cursor)
143 const uint8_t *end = cursor + OLED_FONT_WIDTH;
144 while (cursor < end) {
145 *cursor = ~(*cursor);
150 bool oled_init(uint8_t rotation) {
151 oled_rotation = oled_init_user(rotation);
152 if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
153 oled_rotation_width = OLED_DISPLAY_WIDTH;
155 oled_rotation_width = OLED_DISPLAY_HEIGHT;
159 static const uint8_t PROGMEM display_setup1[] = {
163 MULTIPLEX_RATIO, OLED_DISPLAY_HEIGHT - 1,
164 DISPLAY_OFFSET, 0x00,
165 DISPLAY_START_LINE | 0x00,
167 #if (OLED_IC != OLED_IC_SH1106)
168 // MEMORY_MODE is unsupported on SH1106 (Page Addressing only)
169 MEMORY_MODE, 0x00, // Horizontal addressing mode
172 if (I2C_TRANSMIT_P(display_setup1) != I2C_STATUS_SUCCESS) {
173 print("oled_init cmd set 1 failed\n");
177 if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_180)) {
178 static const uint8_t PROGMEM display_normal[] = {
182 if (I2C_TRANSMIT_P(display_normal) != I2C_STATUS_SUCCESS) {
183 print("oled_init cmd normal rotation failed\n");
187 static const uint8_t PROGMEM display_flipped[] = {
191 if (I2C_TRANSMIT_P(display_flipped) != I2C_STATUS_SUCCESS) {
192 print("display_flipped failed\n");
197 static const uint8_t PROGMEM display_setup2[] = {
199 COM_PINS, OLED_COM_PINS,
201 PRE_CHARGE_PERIOD, 0xF1,
203 DISPLAY_ALL_ON_RESUME,
207 if (I2C_TRANSMIT_P(display_setup2) != I2C_STATUS_SUCCESS) {
208 print("display_setup2 failed\n");
213 oled_initialized = true;
215 oled_scrolling = false;
219 __attribute__((weak))
220 oled_rotation_t oled_init_user(oled_rotation_t rotation) {
224 void oled_clear(void) {
225 memset(oled_buffer, 0, sizeof(oled_buffer));
226 oled_cursor = &oled_buffer[0];
227 oled_dirty = -1; // -1 will be max value as long as display_dirty is unsigned type
230 static void calc_bounds(uint8_t update_start, uint8_t* cmd_array)
232 // Calculate commands to set memory addressing bounds.
233 uint8_t start_page = OLED_BLOCK_SIZE * update_start / OLED_DISPLAY_WIDTH;
234 uint8_t start_column = OLED_BLOCK_SIZE * update_start % OLED_DISPLAY_WIDTH;
235 #if (OLED_IC == OLED_IC_SH1106)
236 // Commands for Page Addressing Mode. Sets starting page and column; has no end bound.
237 // Column value must be split into high and low nybble and sent as two commands.
238 cmd_array[0] = PAM_PAGE_ADDR | start_page;
239 cmd_array[1] = PAM_SETCOLUMN_LSB | ((OLED_COLUMN_OFFSET + start_column) & 0x0f);
240 cmd_array[2] = PAM_SETCOLUMN_MSB | ((OLED_COLUMN_OFFSET + start_column) >> 4 & 0x0f);
245 // Commands for use in Horizontal Addressing mode.
246 cmd_array[1] = start_column;
247 cmd_array[4] = start_page;
248 cmd_array[2] = (OLED_BLOCK_SIZE + OLED_DISPLAY_WIDTH - 1) % OLED_DISPLAY_WIDTH + cmd_array[1];
249 cmd_array[5] = (OLED_BLOCK_SIZE + OLED_DISPLAY_WIDTH - 1) / OLED_DISPLAY_WIDTH - 1;
253 static void calc_bounds_90(uint8_t update_start, uint8_t* cmd_array)
255 cmd_array[1] = OLED_BLOCK_SIZE * update_start / OLED_DISPLAY_HEIGHT * 8;
256 cmd_array[4] = OLED_BLOCK_SIZE * update_start % OLED_DISPLAY_HEIGHT;
257 cmd_array[2] = (OLED_BLOCK_SIZE + OLED_DISPLAY_HEIGHT - 1) / OLED_DISPLAY_HEIGHT * 8 - 1 + cmd_array[1];;
258 cmd_array[5] = (OLED_BLOCK_SIZE + OLED_DISPLAY_HEIGHT - 1) % OLED_DISPLAY_HEIGHT / 8;
261 uint8_t crot(uint8_t a, int8_t n)
263 const uint8_t mask = 0x7;
265 return a << n | a >> (-n & mask);
268 static void rotate_90(const uint8_t* src, uint8_t* dest)
270 for (uint8_t i = 0, shift = 7; i < 8; ++i, --shift) {
271 uint8_t selector = (1 << i);
272 for (uint8_t j = 0; j < 8; ++j) {
273 dest[i] |= crot(src[j] & selector, shift - (int8_t)j);
278 void oled_render(void) {
279 // Do we have work to do?
280 if (!oled_dirty || oled_scrolling) {
284 // Find first dirty block
285 uint8_t update_start = 0;
286 while (!(oled_dirty & (1 << update_start))) { ++update_start; }
288 // Set column & page position
289 static uint8_t display_start[] = {
291 COLUMN_ADDR, 0, OLED_DISPLAY_WIDTH - 1,
292 PAGE_ADDR, 0, OLED_DISPLAY_HEIGHT / 8 - 1 };
293 if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
294 calc_bounds(update_start, &display_start[1]); // Offset from I2C_CMD byte at the start
296 calc_bounds_90(update_start, &display_start[1]); // Offset from I2C_CMD byte at the start
299 // Send column & page position
300 if (I2C_TRANSMIT(display_start) != I2C_STATUS_SUCCESS) {
301 print("oled_render offset command failed\n");
305 if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
306 // Send render data chunk as is
307 if (I2C_WRITE_REG(I2C_DATA, &oled_buffer[OLED_BLOCK_SIZE * update_start], OLED_BLOCK_SIZE) != I2C_STATUS_SUCCESS) {
308 print("oled_render data failed\n");
312 // Rotate the render chunks
313 const static uint8_t source_map[] = OLED_SOURCE_MAP;
314 const static uint8_t target_map[] = OLED_TARGET_MAP;
316 static uint8_t temp_buffer[OLED_BLOCK_SIZE];
317 memset(temp_buffer, 0, sizeof(temp_buffer));
318 for(uint8_t i = 0; i < sizeof(source_map); ++i) {
319 rotate_90(&oled_buffer[OLED_BLOCK_SIZE * update_start + source_map[i]], &temp_buffer[target_map[i]]);
322 // Send render data chunk after rotating
323 if (I2C_WRITE_REG(I2C_DATA, &temp_buffer[0], OLED_BLOCK_SIZE) != I2C_STATUS_SUCCESS) {
324 print("oled_render data failed\n");
329 // Turn on display if it is off
333 oled_dirty &= ~(1 << update_start);
336 void oled_set_cursor(uint8_t col, uint8_t line) {
337 uint16_t index = line * oled_rotation_width + col * OLED_FONT_WIDTH;
340 if (index >= OLED_MATRIX_SIZE) {
344 oled_cursor = &oled_buffer[index];
347 void oled_advance_page(bool clearPageRemainder) {
348 uint16_t index = oled_cursor - &oled_buffer[0];
349 uint8_t remaining = oled_rotation_width - (index % oled_rotation_width);
351 if (clearPageRemainder) {
352 // Remaining Char count
353 remaining = remaining / OLED_FONT_WIDTH;
355 // Write empty character until next line
357 oled_write_char(' ', false);
359 // Next page index out of bounds?
360 if (index + remaining >= OLED_MATRIX_SIZE) {
365 oled_cursor = &oled_buffer[index + remaining];
369 void oled_advance_char(void) {
370 uint16_t nextIndex = oled_cursor - &oled_buffer[0] + OLED_FONT_WIDTH;
371 uint8_t remainingSpace = oled_rotation_width - (nextIndex % oled_rotation_width);
373 // Do we have enough space on the current line for the next character
374 if (remainingSpace < OLED_FONT_WIDTH) {
375 nextIndex += remainingSpace;
378 // Did we go out of bounds
379 if (nextIndex >= OLED_MATRIX_SIZE) {
383 // Update cursor position
384 oled_cursor = &oled_buffer[nextIndex];
387 // Main handler that writes character data to the display buffer
388 void oled_write_char(const char data, bool invert) {
389 // Advance to the next line if newline
391 // Old source wrote ' ' until end of line...
392 oled_advance_page(true);
396 // copy the current render buffer to check for dirty after
397 static uint8_t oled_temp_buffer[OLED_FONT_WIDTH];
398 memcpy(&oled_temp_buffer, oled_cursor, OLED_FONT_WIDTH);
400 // set the reder buffer data
401 uint8_t cast_data = (uint8_t)data; // font based on unsigned type for index
402 if (cast_data < OLED_FONT_START || cast_data > OLED_FONT_END) {
403 memset(oled_cursor, 0x00, OLED_FONT_WIDTH);
405 const uint8_t *glyph = &font[(cast_data - OLED_FONT_START) * OLED_FONT_WIDTH];
406 memcpy_P(oled_cursor, glyph, OLED_FONT_WIDTH);
411 InvertCharacter(oled_cursor);
415 if (memcmp(&oled_temp_buffer, oled_cursor, OLED_FONT_WIDTH)) {
416 uint16_t index = oled_cursor - &oled_buffer[0];
417 oled_dirty |= (1 << (index / OLED_BLOCK_SIZE));
418 // Edgecase check if the written data spans the 2 chunks
419 oled_dirty |= (1 << ((index + OLED_FONT_WIDTH) / OLED_BLOCK_SIZE));
422 // Finally move to the next char
426 void oled_write(const char *data, bool invert) {
427 const char *end = data + strlen(data);
429 oled_write_char(*data, invert);
434 void oled_write_ln(const char *data, bool invert) {
435 oled_write(data, invert);
436 oled_advance_page(true);
440 void oled_write_P(const char *data, bool invert) {
441 uint8_t c = pgm_read_byte(data);
443 oled_write_char(c, invert);
444 c = pgm_read_byte(++data);
448 void oled_write_ln_P(const char *data, bool invert) {
449 oled_write_P(data, invert);
450 oled_advance_page(true);
452 #endif // defined(__AVR__)
455 #if !defined(OLED_DISABLE_TIMEOUT)
456 oled_last_activity = timer_read();
459 static const uint8_t PROGMEM display_on[] = { I2C_CMD, DISPLAY_ON };
461 if (I2C_TRANSMIT_P(display_on) != I2C_STATUS_SUCCESS) {
462 print("oled_on cmd failed\n");
470 bool oled_off(void) {
471 static const uint8_t PROGMEM display_off[] = { I2C_CMD, DISPLAY_OFF };
473 if (I2C_TRANSMIT_P(display_off) != I2C_STATUS_SUCCESS) {
474 print("oled_off cmd failed\n");
482 bool oled_scroll_right(void) {
483 // Dont enable scrolling if we need to update the display
484 // This prevents scrolling of bad data from starting the scroll too early after init
485 if (!oled_dirty && !oled_scrolling) {
486 static const uint8_t PROGMEM display_scroll_right[] = {
487 I2C_CMD, SCROLL_RIGHT, 0x00, 0x00, 0x00, 0x0F, 0x00, 0xFF, ACTIVATE_SCROLL };
488 if (I2C_TRANSMIT_P(display_scroll_right) != I2C_STATUS_SUCCESS) {
489 print("oled_scroll_right cmd failed\n");
490 return oled_scrolling;
492 oled_scrolling = true;
494 return oled_scrolling;
497 bool oled_scroll_left(void) {
498 // Dont enable scrolling if we need to update the display
499 // This prevents scrolling of bad data from starting the scroll too early after init
500 if (!oled_dirty && !oled_scrolling) {
501 static const uint8_t PROGMEM display_scroll_left[] = {
502 I2C_CMD, SCROLL_LEFT, 0x00, 0x00, 0x00, 0x0F, 0x00, 0xFF, ACTIVATE_SCROLL };
503 if (I2C_TRANSMIT_P(display_scroll_left) != I2C_STATUS_SUCCESS) {
504 print("oled_scroll_left cmd failed\n");
505 return oled_scrolling;
507 oled_scrolling = true;
509 return oled_scrolling;
512 bool oled_scroll_off(void) {
513 if (oled_scrolling) {
514 static const uint8_t PROGMEM display_scroll_off[] = { I2C_CMD, DEACTIVATE_SCROLL };
515 if (I2C_TRANSMIT_P(display_scroll_off) != I2C_STATUS_SUCCESS) {
516 print("oled_scroll_off cmd failed\n");
517 return oled_scrolling;
519 oled_scrolling = false;
521 return !oled_scrolling;
524 uint8_t oled_max_chars(void) {
525 if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
526 return OLED_DISPLAY_WIDTH / OLED_FONT_WIDTH;
528 return OLED_DISPLAY_HEIGHT / OLED_FONT_WIDTH;
531 uint8_t oled_max_lines(void) {
532 if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
533 return OLED_DISPLAY_HEIGHT / OLED_FONT_HEIGHT;
535 return OLED_DISPLAY_WIDTH / OLED_FONT_HEIGHT;
538 void oled_task(void) {
539 if (!oled_initialized) {
543 oled_set_cursor(0, 0);
547 // Smart render system, no need to check for dirty
550 // Display timeout check
551 #if !defined(OLED_DISABLE_TIMEOUT)
552 if (oled_active && timer_elapsed(oled_last_activity) > OLED_TIMEOUT) {
558 __attribute__((weak))
559 void oled_task_user(void) {