]> git.donarmstrong.com Git - qmk_firmware.git/blob - drivers/oled/oled_driver.c
[Keyboard] fixed pins for numpad_5x4 layout (#6311)
[qmk_firmware.git] / drivers / oled / oled_driver.c
1 /*
2 Copyright 2019 Ryan Caltabiano <https://github.com/XScorpion2>
3
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.
8
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.
13
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/>.
16 */
17 #include "i2c_master.h"
18 #include "oled_driver.h"
19 #include OLED_FONT_H
20 #include "timer.h"
21 #include "print.h"
22
23 #include <string.h>
24
25 #if defined(__AVR__)
26   #include <avr/io.h>
27   #include <avr/pgmspace.h>
28 #elif defined(ESP8266)
29   #include <pgmspace.h>
30 #else // defined(ESP8266)
31   #define PROGMEM
32   #define memcpy_P(des, src, len) memcpy(des, src, len)
33 #endif // defined(__AVR__)
34
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
37
38 // Fundamental Commands
39 #define CONTRAST                0x81
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
45 #define NOP                     0xE3
46
47 // Scrolling Commands
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
54
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
62
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
71 #define COM_PINS                0xDA
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
76
77 // Timing & Driving Commands
78 #define DISPLAY_CLOCK           0xD5
79 #define PRE_CHARGE_PERIOD       0xD9
80 #define VCOM_DETECT             0xDB
81
82 // Charge Pump Commands
83 #define CHARGE_PUMP             0x8D
84
85 // Misc defines
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)
89
90 // i2c defines
91 #define I2C_CMD 0x00
92 #define I2C_DATA 0x40
93 #if defined(__AVR__)
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)
102
103 #define HAS_FLAGS(bits, flags) ((bits & flags) == flags)
104
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;
119 #endif
120
121 // Internal variables to reduce math instructions
122
123 #if defined(__AVR__)
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);
128
129   for (uint16_t i = 0; i < length && status >= 0; i++) {
130     status = i2c_write(pgm_read_byte((const char*)data++), timeout);
131     if (status) break;
132   }
133
134   i2c_stop();
135
136   return status;
137 }
138 #endif
139
140 // Flips the rendering bits for a character at the current cursor position
141 static void InvertCharacter(uint8_t *cursor)
142 {
143   const uint8_t *end = cursor + OLED_FONT_WIDTH;
144   while (cursor < end) {
145     *cursor = ~(*cursor);
146     cursor++;
147   }
148 }
149
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;
154   } else {
155     oled_rotation_width = OLED_DISPLAY_HEIGHT;
156   }
157   i2c_init();
158
159   static const uint8_t PROGMEM display_setup1[] = {
160     I2C_CMD,
161     DISPLAY_OFF,
162     DISPLAY_CLOCK, 0x80,
163     MULTIPLEX_RATIO, OLED_DISPLAY_HEIGHT - 1,
164     DISPLAY_OFFSET, 0x00,
165     DISPLAY_START_LINE | 0x00,
166     CHARGE_PUMP, 0x14,
167 #if (OLED_IC != OLED_IC_SH1106)
168     // MEMORY_MODE is unsupported on SH1106 (Page Addressing only)
169     MEMORY_MODE, 0x00, // Horizontal addressing mode
170 #endif
171   };
172   if (I2C_TRANSMIT_P(display_setup1) != I2C_STATUS_SUCCESS) {
173     print("oled_init cmd set 1 failed\n");
174     return false;
175   }
176
177   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_180)) {
178     static const uint8_t PROGMEM display_normal[] = {
179       I2C_CMD,
180       SEGMENT_REMAP_INV,
181       COM_SCAN_DEC };
182     if (I2C_TRANSMIT_P(display_normal) != I2C_STATUS_SUCCESS) {
183       print("oled_init cmd normal rotation failed\n");
184       return false;
185     }
186   } else {
187     static const uint8_t PROGMEM display_flipped[] = {
188       I2C_CMD,
189       SEGMENT_REMAP,
190       COM_SCAN_INC };
191     if (I2C_TRANSMIT_P(display_flipped) != I2C_STATUS_SUCCESS) {
192       print("display_flipped failed\n");
193       return false;
194     }
195   }
196
197   static const uint8_t PROGMEM display_setup2[] = {
198     I2C_CMD,
199     COM_PINS, OLED_COM_PINS,
200     CONTRAST, 0x8F,
201     PRE_CHARGE_PERIOD, 0xF1,
202     VCOM_DETECT, 0x40,
203     DISPLAY_ALL_ON_RESUME,
204     NORMAL_DISPLAY,
205     DEACTIVATE_SCROLL,
206     DISPLAY_ON };
207   if (I2C_TRANSMIT_P(display_setup2) != I2C_STATUS_SUCCESS) {
208     print("display_setup2 failed\n");
209     return false;
210   }
211
212   oled_clear();
213   oled_initialized = true;
214   oled_active = true;
215   oled_scrolling = false;
216   return true;
217 }
218
219 __attribute__((weak))
220 oled_rotation_t oled_init_user(oled_rotation_t rotation) {
221   return rotation;
222 }
223
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
228 }
229
230 static void calc_bounds(uint8_t update_start, uint8_t* cmd_array)
231 {
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);
241   cmd_array[3] = NOP;
242   cmd_array[4] = NOP;
243   cmd_array[5] = NOP;
244 #else
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;
250 #endif
251 }
252
253 static void calc_bounds_90(uint8_t update_start, uint8_t* cmd_array)
254 {
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;
259 }
260
261 uint8_t crot(uint8_t a, int8_t n)
262 {
263   const uint8_t mask = 0x7;
264   n &= mask;
265   return a << n | a >> (-n & mask);
266 }
267
268 static void rotate_90(const uint8_t* src, uint8_t* dest)
269 {
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);
274     }
275   }
276 }
277
278 void oled_render(void) {
279   // Do we have work to do?
280   if (!oled_dirty || oled_scrolling) {
281     return;
282   }
283
284   // Find first dirty block
285   uint8_t update_start = 0;
286   while (!(oled_dirty & (1 << update_start))) { ++update_start; }
287
288   // Set column & page position
289   static uint8_t display_start[] = {
290     I2C_CMD,
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
295   } else {
296     calc_bounds_90(update_start, &display_start[1]); // Offset from I2C_CMD byte at the start
297   }
298
299   // Send column & page position
300   if (I2C_TRANSMIT(display_start) != I2C_STATUS_SUCCESS) {
301     print("oled_render offset command failed\n");
302     return;
303   }
304
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");
309       return;
310     }
311   } else {
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;
315
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]]);
320     }
321
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");
325       return;
326     }
327   }
328
329   // Turn on display if it is off
330   oled_on();
331
332   // Clear dirty flag
333   oled_dirty &= ~(1 << update_start);
334 }
335
336 void oled_set_cursor(uint8_t col, uint8_t line) {
337   uint16_t index = line * oled_rotation_width + col * OLED_FONT_WIDTH;
338
339   // Out of bounds?
340   if (index >= OLED_MATRIX_SIZE) {
341     index = 0;
342   }
343
344   oled_cursor = &oled_buffer[index];
345 }
346
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);
350
351   if (clearPageRemainder) {
352     // Remaining Char count
353     remaining = remaining / OLED_FONT_WIDTH;
354
355     // Write empty character until next line
356     while (remaining--)
357       oled_write_char(' ', false);
358   } else {
359     // Next page index out of bounds?
360     if (index + remaining >= OLED_MATRIX_SIZE) {
361       index = 0;
362       remaining = 0;
363     }
364
365     oled_cursor = &oled_buffer[index + remaining];
366   }
367 }
368
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);
372
373   // Do we have enough space on the current line for the next character
374   if (remainingSpace < OLED_FONT_WIDTH) {
375     nextIndex += remainingSpace;
376   }
377
378   // Did we go out of bounds
379   if (nextIndex >= OLED_MATRIX_SIZE) {
380     nextIndex = 0;
381   }
382
383   // Update cursor position
384   oled_cursor = &oled_buffer[nextIndex];
385 }
386
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
390   if (data == '\n') {
391     // Old source wrote ' ' until end of line...
392     oled_advance_page(true);
393     return;
394   }
395
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);
399
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);
404   } else {
405     const uint8_t *glyph = &font[(cast_data - OLED_FONT_START) * OLED_FONT_WIDTH];
406     memcpy_P(oled_cursor, glyph, OLED_FONT_WIDTH);
407   }
408
409   // Invert if needed
410   if (invert) {
411     InvertCharacter(oled_cursor);
412   }
413
414   // Dirty check
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));
420   }
421
422   // Finally move to the next char
423   oled_advance_char();
424 }
425
426 void oled_write(const char *data, bool invert) {
427   const char *end = data + strlen(data);
428   while (data < end) {
429     oled_write_char(*data, invert);
430     data++;
431   }
432 }
433
434 void oled_write_ln(const char *data, bool invert) {
435   oled_write(data, invert);
436   oled_advance_page(true);
437 }
438
439 #if defined(__AVR__)
440 void oled_write_P(const char *data, bool invert) {
441   uint8_t c = pgm_read_byte(data);
442   while (c != 0) {
443     oled_write_char(c, invert);
444     c = pgm_read_byte(++data);
445   }
446 }
447
448 void oled_write_ln_P(const char *data, bool invert) {
449   oled_write_P(data, invert);
450   oled_advance_page(true);
451 }
452 #endif // defined(__AVR__)
453
454 bool oled_on(void) {
455 #if !defined(OLED_DISABLE_TIMEOUT)
456   oled_last_activity = timer_read();
457 #endif
458
459   static const uint8_t PROGMEM display_on[] = { I2C_CMD, DISPLAY_ON };
460   if (!oled_active) {
461     if (I2C_TRANSMIT_P(display_on) != I2C_STATUS_SUCCESS) {
462       print("oled_on cmd failed\n");
463       return oled_active;
464     }
465     oled_active = true;
466   }
467   return oled_active;
468 }
469
470 bool oled_off(void) {
471   static const uint8_t PROGMEM display_off[] = { I2C_CMD, DISPLAY_OFF };
472   if (oled_active) {
473     if (I2C_TRANSMIT_P(display_off) != I2C_STATUS_SUCCESS) {
474       print("oled_off cmd failed\n");
475       return oled_active;
476     }
477     oled_active = false;
478   }
479   return !oled_active;
480 }
481
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;
491     }
492     oled_scrolling = true;
493   }
494   return oled_scrolling;
495 }
496
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;
506     }
507     oled_scrolling = true;
508   }
509   return oled_scrolling;
510 }
511
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;
518     }
519     oled_scrolling = false;
520   }
521   return !oled_scrolling;
522 }
523
524 uint8_t oled_max_chars(void) {
525   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
526     return OLED_DISPLAY_WIDTH / OLED_FONT_WIDTH;
527   }
528   return OLED_DISPLAY_HEIGHT / OLED_FONT_WIDTH;
529 }
530
531 uint8_t oled_max_lines(void) {
532   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
533     return OLED_DISPLAY_HEIGHT / OLED_FONT_HEIGHT;
534   }
535   return OLED_DISPLAY_WIDTH / OLED_FONT_HEIGHT;
536 }
537
538 void oled_task(void) {
539   if (!oled_initialized) {
540     return;
541   }
542
543   oled_set_cursor(0, 0);
544
545   oled_task_user();
546
547   // Smart render system, no need to check for dirty
548   oled_render();
549
550   // Display timeout check
551 #if !defined(OLED_DISABLE_TIMEOUT)
552   if (oled_active && timer_elapsed(oled_last_activity) > OLED_TIMEOUT) {
553     oled_off();
554   }
555 #endif
556 }
557
558 __attribute__((weak))
559 void oled_task_user(void) {
560 }