]> git.donarmstrong.com Git - qmk_firmware.git/blob - drivers/oled/oled_driver.c
643e5289465cad8a097bc0eefd74e0b6fc49ae8b
[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 // Fundamental Commands
37 #define CONTRAST                0x81
38 #define DISPLAY_ALL_ON          0xA5
39 #define DISPLAY_ALL_ON_RESUME   0xA4
40 #define NORMAL_DISPLAY          0xA6
41 #define DISPLAY_ON              0xAF
42 #define DISPLAY_OFF             0xAE
43
44 // Scrolling Commands
45 #define ACTIVATE_SCROLL         0x2F
46 #define DEACTIVATE_SCROLL       0x2E
47 #define SCROLL_RIGHT            0x26
48 #define SCROLL_LEFT             0x27
49 #define SCROLL_RIGHT_UP         0x29
50 #define SCROLL_LEFT_UP          0x2A
51
52 // Addressing Setting Commands
53 #define MEMORY_MODE             0x20
54 #define COLUMN_ADDR             0x21
55 #define PAGE_ADDR               0x22
56
57 // Hardware Configuration Commands
58 #define DISPLAY_START_LINE      0x40
59 #define SEGMENT_REMAP           0xA0
60 #define SEGMENT_REMAP_INV       0xA1
61 #define MULTIPLEX_RATIO         0xA8
62 #define COM_SCAN_INC            0xC0
63 #define COM_SCAN_DEC            0xC8
64 #define DISPLAY_OFFSET          0xD3
65 #define COM_PINS                0xDA
66 #define COM_PINS_SEQ            0x02
67 #define COM_PINS_ALT            0x12
68 #define COM_PINS_SEQ_LR         0x22
69 #define COM_PINS_ALT_LR         0x32
70
71 // Timing & Driving Commands
72 #define DISPLAY_CLOCK           0xD5
73 #define PRE_CHARGE_PERIOD       0xD9
74 #define VCOM_DETECT             0xDB
75
76 // Charge Pump Commands
77 #define CHARGE_PUMP             0x8D
78
79 // Misc defines
80 #define OLED_TIMEOUT 60000
81 #define OLED_BLOCK_COUNT (sizeof(OLED_BLOCK_TYPE) * 8)
82 #define OLED_BLOCK_SIZE (OLED_MATRIX_SIZE / OLED_BLOCK_COUNT)
83
84 // i2c defines
85 #define I2C_CMD 0x00
86 #define I2C_DATA 0x40
87 #if defined(__AVR__)
88   // already defined on ARM
89   #define I2C_TIMEOUT 100
90   #define I2C_TRANSMIT_P(data) i2c_transmit_P((OLED_DISPLAY_ADDRESS << 1), &data[0], sizeof(data), I2C_TIMEOUT)
91 #else // defined(__AVR__)
92   #define I2C_TRANSMIT_P(data) i2c_transmit((OLED_DISPLAY_ADDRESS << 1), &data[0], sizeof(data), I2C_TIMEOUT)
93 #endif // defined(__AVR__)
94 #define I2C_TRANSMIT(data) i2c_transmit((OLED_DISPLAY_ADDRESS << 1), &data[0], sizeof(data), I2C_TIMEOUT)
95 #define I2C_WRITE_REG(mode, data, size) i2c_writeReg((OLED_DISPLAY_ADDRESS << 1), mode, data, size, I2C_TIMEOUT)
96
97 #define HAS_FLAGS(bits, flags) ((bits & flags) == flags)
98
99 // Display buffer's is the same as the OLED memory layout
100 // this is so we don't end up with rounding errors with
101 // parts of the display unusable or don't get cleared correctly
102 // and also allows for drawing & inverting
103 uint8_t          oled_buffer[OLED_MATRIX_SIZE];
104 uint8_t*         oled_cursor;
105 OLED_BLOCK_TYPE  oled_dirty = 0;
106 bool             oled_initialized = false;
107 bool             oled_active = false;
108 bool             oled_scrolling = false;
109 uint8_t          oled_rotation = 0;
110 uint8_t          oled_rotation_width = 0;
111 #if !defined(OLED_DISABLE_TIMEOUT)
112   uint16_t         oled_last_activity;
113 #endif
114
115 // Internal variables to reduce math instructions
116
117 #if defined(__AVR__)
118 // identical to i2c_transmit, but for PROGMEM since all initialization is in PROGMEM arrays currently
119 // probably should move this into i2c_master...
120 static i2c_status_t i2c_transmit_P(uint8_t address, const uint8_t* data, uint16_t length, uint16_t timeout) {
121   i2c_status_t status = i2c_start(address | I2C_WRITE, timeout);
122
123   for (uint16_t i = 0; i < length && status >= 0; i++) {
124     status = i2c_write(pgm_read_byte((const char*)data++), timeout);
125     if (status) break;
126   }
127
128   i2c_stop();
129
130   return status;
131 }
132 #endif
133
134 // Flips the rendering bits for a character at the current cursor position
135 static void InvertCharacter(uint8_t *cursor)
136 {
137   const uint8_t *end = cursor + OLED_FONT_WIDTH;
138   while (cursor < end) {
139     *cursor = ~(*cursor);
140     cursor++;
141   }
142 }
143
144 bool oled_init(uint8_t rotation) {
145   oled_rotation = oled_init_user(rotation);
146   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
147     oled_rotation_width = OLED_DISPLAY_WIDTH;
148   } else {
149     oled_rotation_width = OLED_DISPLAY_HEIGHT;
150   }
151   i2c_init();
152
153   static const uint8_t PROGMEM display_setup1[] = {
154     I2C_CMD,
155     DISPLAY_OFF,
156     DISPLAY_CLOCK, 0x80,
157     MULTIPLEX_RATIO, OLED_DISPLAY_HEIGHT - 1,
158     DISPLAY_OFFSET, 0x00,
159     DISPLAY_START_LINE | 0x00,
160     CHARGE_PUMP, 0x14,
161     MEMORY_MODE, 0x00, }; // Horizontal addressing mode
162   if (I2C_TRANSMIT_P(display_setup1) != I2C_STATUS_SUCCESS) {
163     print("oled_init cmd set 1 failed\n");
164     return false;
165   }
166
167   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_180)) {
168     static const uint8_t PROGMEM display_normal[] = {
169       I2C_CMD,
170       SEGMENT_REMAP_INV,
171       COM_SCAN_DEC };
172     if (I2C_TRANSMIT_P(display_normal) != I2C_STATUS_SUCCESS) {
173       print("oled_init cmd normal rotation failed\n");
174       return false;
175     }
176   } else {
177     static const uint8_t PROGMEM display_flipped[] = {
178       I2C_CMD,
179       SEGMENT_REMAP,
180       COM_SCAN_INC };
181     if (I2C_TRANSMIT_P(display_flipped) != I2C_STATUS_SUCCESS) {
182       print("display_flipped failed\n");
183       return false;
184     }
185   }
186
187   static const uint8_t PROGMEM display_setup2[] = {
188     I2C_CMD,
189     COM_PINS, OLED_COM_PINS,
190     CONTRAST, 0x8F,
191     PRE_CHARGE_PERIOD, 0xF1,
192     VCOM_DETECT, 0x40,
193     DISPLAY_ALL_ON_RESUME,
194     NORMAL_DISPLAY,
195     DEACTIVATE_SCROLL,
196     DISPLAY_ON };
197   if (I2C_TRANSMIT_P(display_setup2) != I2C_STATUS_SUCCESS) {
198     print("display_setup2 failed\n");
199     return false;
200   }
201
202   oled_clear();
203   oled_initialized = true;
204   oled_active = true;
205   oled_scrolling = false;
206   return true;
207 }
208
209 __attribute__((weak))
210 oled_rotation_t oled_init_user(oled_rotation_t rotation) {
211   return rotation;
212 }
213
214 void oled_clear(void) {
215   memset(oled_buffer, 0, sizeof(oled_buffer));
216   oled_cursor = &oled_buffer[0];
217   oled_dirty = -1; // -1 will be max value as long as display_dirty is unsigned type
218 }
219
220 static void calc_bounds(uint8_t update_start, uint8_t* cmd_array)
221 {
222   cmd_array[1] = OLED_BLOCK_SIZE * update_start % OLED_DISPLAY_WIDTH;
223   cmd_array[4] = OLED_BLOCK_SIZE * update_start / OLED_DISPLAY_WIDTH;
224   cmd_array[2] = (OLED_BLOCK_SIZE + OLED_DISPLAY_WIDTH - 1) % OLED_DISPLAY_WIDTH + cmd_array[1];
225   cmd_array[5] = (OLED_BLOCK_SIZE + OLED_DISPLAY_WIDTH - 1) / OLED_DISPLAY_WIDTH - 1;
226 }
227
228 static void calc_bounds_90(uint8_t update_start, uint8_t* cmd_array)
229 {
230   cmd_array[1] = OLED_BLOCK_SIZE * update_start / OLED_DISPLAY_HEIGHT * 8;
231   cmd_array[4] = OLED_BLOCK_SIZE * update_start % OLED_DISPLAY_HEIGHT;
232   cmd_array[2] = (OLED_BLOCK_SIZE + OLED_DISPLAY_HEIGHT - 1) / OLED_DISPLAY_HEIGHT * 8 - 1 + cmd_array[1];;
233   cmd_array[5] = (OLED_BLOCK_SIZE + OLED_DISPLAY_HEIGHT - 1) % OLED_DISPLAY_HEIGHT / 8;
234 }
235
236 uint8_t crot(uint8_t a, int8_t n)
237 {
238   const uint8_t mask = 0x7;
239   n &= mask;
240   return a << n | a >> (-n & mask);
241 }
242
243 static void rotate_90(const uint8_t* src, uint8_t* dest)
244 {
245   for (uint8_t i = 0, shift = 7; i < 8; ++i, --shift) {
246     uint8_t selector = (1 << i);
247     for (uint8_t j = 0; j < 8; ++j) {
248       dest[i] |= crot(src[j] & selector, shift - (int8_t)j);
249     }
250   }
251 }
252
253 void oled_render(void) {
254   // Do we have work to do?
255   if (!oled_dirty || oled_scrolling) {
256     return;
257   }
258
259   // Find first dirty block
260   uint8_t update_start = 0;
261   while (!(oled_dirty & (1 << update_start))) { ++update_start; }
262
263   // Set column & page position
264   static uint8_t display_start[] = {
265     I2C_CMD,
266     COLUMN_ADDR, 0, OLED_DISPLAY_WIDTH - 1,
267     PAGE_ADDR, 0, OLED_DISPLAY_HEIGHT / 8 - 1 };
268   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
269     calc_bounds(update_start, &display_start[1]); // Offset from I2C_CMD byte at the start
270   } else {
271     calc_bounds_90(update_start, &display_start[1]); // Offset from I2C_CMD byte at the start
272   }
273
274   // Send column & page position
275   if (I2C_TRANSMIT(display_start) != I2C_STATUS_SUCCESS) {
276     print("oled_render offset command failed\n");
277     return;
278   }
279
280   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
281     // Send render data chunk as is
282     if (I2C_WRITE_REG(I2C_DATA, &oled_buffer[OLED_BLOCK_SIZE * update_start], OLED_BLOCK_SIZE) != I2C_STATUS_SUCCESS) {
283       print("oled_render data failed\n");
284       return;
285     }
286   } else {
287     // Rotate the render chunks
288     const static uint8_t source_map[] = OLED_SOURCE_MAP;
289     const static uint8_t target_map[] = OLED_TARGET_MAP;
290
291     static uint8_t temp_buffer[OLED_BLOCK_SIZE];
292     memset(temp_buffer, 0, sizeof(temp_buffer));
293     for(uint8_t i = 0; i < sizeof(source_map); ++i) {
294       rotate_90(&oled_buffer[OLED_BLOCK_SIZE * update_start + source_map[i]], &temp_buffer[target_map[i]]);
295     }
296
297     // Send render data chunk after rotating
298     if (I2C_WRITE_REG(I2C_DATA, &temp_buffer[0], OLED_BLOCK_SIZE) != I2C_STATUS_SUCCESS) {
299       print("oled_render data failed\n");
300       return;
301     }
302   }
303
304   // Turn on display if it is off
305   oled_on();
306
307   // Clear dirty flag
308   oled_dirty &= ~(1 << update_start);
309 }
310
311 void oled_set_cursor(uint8_t col, uint8_t line) {
312   uint16_t index = line * oled_rotation_width + col * OLED_FONT_WIDTH;
313
314   // Out of bounds?
315   if (index >= OLED_MATRIX_SIZE) {
316     index = 0;
317   }
318
319   oled_cursor = &oled_buffer[index];
320 }
321
322 void oled_advance_page(bool clearPageRemainder) {
323   uint16_t index = oled_cursor - &oled_buffer[0];
324   uint8_t remaining = oled_rotation_width - (index % oled_rotation_width);
325
326   if (clearPageRemainder) {
327     // Remaining Char count
328     remaining = remaining / OLED_FONT_WIDTH;
329
330     // Write empty character until next line
331     while (remaining--)
332       oled_write_char(' ', false);
333   } else {
334     // Next page index out of bounds?
335     if (index + remaining >= OLED_MATRIX_SIZE) {
336       index = 0;
337       remaining = 0;
338     }
339
340     oled_cursor = &oled_buffer[index + remaining];
341   }
342 }
343
344 void oled_advance_char(void) {
345   uint16_t nextIndex = oled_cursor - &oled_buffer[0] + OLED_FONT_WIDTH;
346   uint8_t remainingSpace = oled_rotation_width - (nextIndex % oled_rotation_width);
347
348   // Do we have enough space on the current line for the next character
349   if (remainingSpace < OLED_FONT_WIDTH) {
350     nextIndex += remainingSpace;
351   }
352
353   // Did we go out of bounds
354   if (nextIndex >= OLED_MATRIX_SIZE) {
355     nextIndex = 0;
356   }
357
358   // Update cursor position
359   oled_cursor = &oled_buffer[nextIndex];
360 }
361
362 // Main handler that writes character data to the display buffer
363 void oled_write_char(const char data, bool invert) {
364   // Advance to the next line if newline
365   if (data == '\n') {
366     // Old source wrote ' ' until end of line...
367     oled_advance_page(true);
368     return;
369   }
370
371   // copy the current render buffer to check for dirty after
372   static uint8_t oled_temp_buffer[OLED_FONT_WIDTH];
373   memcpy(&oled_temp_buffer, oled_cursor, OLED_FONT_WIDTH);
374
375   // set the reder buffer data
376   uint8_t cast_data = (uint8_t)data; // font based on unsigned type for index
377   if (cast_data < OLED_FONT_START || cast_data > OLED_FONT_END) {
378     memset(oled_cursor, 0x00, OLED_FONT_WIDTH);
379   } else {
380     const uint8_t *glyph = &font[(cast_data - OLED_FONT_START) * OLED_FONT_WIDTH];
381     memcpy_P(oled_cursor, glyph, OLED_FONT_WIDTH);
382   }
383
384   // Invert if needed
385   if (invert) {
386     InvertCharacter(oled_cursor);
387   }
388
389   // Dirty check
390   if (memcmp(&oled_temp_buffer, oled_cursor, OLED_FONT_WIDTH)) {
391     uint16_t index = oled_cursor - &oled_buffer[0];
392     oled_dirty |= (1 << (index / OLED_BLOCK_SIZE));
393     // Edgecase check if the written data spans the 2 chunks
394     oled_dirty |= (1 << ((index + OLED_FONT_WIDTH) / OLED_BLOCK_SIZE));
395   }
396
397   // Finally move to the next char
398   oled_advance_char();
399 }
400
401 void oled_write(const char *data, bool invert) {
402   const char *end = data + strlen(data);
403   while (data < end) {
404     oled_write_char(*data, invert);
405     data++;
406   }
407 }
408
409 void oled_write_ln(const char *data, bool invert) {
410   oled_write(data, invert);
411   oled_advance_page(true);
412 }
413
414 #if defined(__AVR__)
415 void oled_write_P(const char *data, bool invert) {
416   uint8_t c = pgm_read_byte(data);
417   while (c != 0) {
418     oled_write_char(c, invert);
419     c = pgm_read_byte(++data);
420   }
421 }
422
423 void oled_write_ln_P(const char *data, bool invert) {
424   oled_write_P(data, invert);
425   oled_advance_page(true);
426 }
427 #endif // defined(__AVR__)
428
429 bool oled_on(void) {
430 #if !defined(OLED_DISABLE_TIMEOUT)
431   oled_last_activity = timer_read();
432 #endif
433
434   static const uint8_t PROGMEM display_on[] = { I2C_CMD, DISPLAY_ON };
435   if (!oled_active) {
436     if (I2C_TRANSMIT_P(display_on) != I2C_STATUS_SUCCESS) {
437       print("oled_on cmd failed\n");
438       return oled_active;
439     }
440     oled_active = true;
441   }
442   return oled_active;
443 }
444
445 bool oled_off(void) {
446   static const uint8_t PROGMEM display_off[] = { I2C_CMD, DISPLAY_OFF };
447   if (oled_active) {
448     if (I2C_TRANSMIT_P(display_off) != I2C_STATUS_SUCCESS) {
449       print("oled_off cmd failed\n");
450       return oled_active;
451     }
452     oled_active = false;
453   }
454   return !oled_active;
455 }
456
457 bool oled_scroll_right(void) {
458   // Dont enable scrolling if we need to update the display
459   // This prevents scrolling of bad data from starting the scroll too early after init
460   if (!oled_dirty && !oled_scrolling) {
461     static const uint8_t PROGMEM display_scroll_right[] = {
462       I2C_CMD, SCROLL_RIGHT, 0x00, 0x00, 0x00, 0x0F, 0x00, 0xFF, ACTIVATE_SCROLL };
463     if (I2C_TRANSMIT_P(display_scroll_right) != I2C_STATUS_SUCCESS) {
464       print("oled_scroll_right cmd failed\n");
465       return oled_scrolling;
466     }
467     oled_scrolling = true;
468   }
469   return oled_scrolling;
470 }
471
472 bool oled_scroll_left(void) {
473   // Dont enable scrolling if we need to update the display
474   // This prevents scrolling of bad data from starting the scroll too early after init
475   if (!oled_dirty && !oled_scrolling) {
476     static const uint8_t PROGMEM display_scroll_left[] = {
477       I2C_CMD, SCROLL_LEFT, 0x00, 0x00, 0x00, 0x0F, 0x00, 0xFF, ACTIVATE_SCROLL };
478     if (I2C_TRANSMIT_P(display_scroll_left) != I2C_STATUS_SUCCESS) {
479       print("oled_scroll_left cmd failed\n");
480       return oled_scrolling;
481     }
482     oled_scrolling = true;
483   }
484   return oled_scrolling;
485 }
486
487 bool oled_scroll_off(void) {
488   if (oled_scrolling) {
489     static const uint8_t PROGMEM display_scroll_off[] = { I2C_CMD, DEACTIVATE_SCROLL };
490     if (I2C_TRANSMIT_P(display_scroll_off) != I2C_STATUS_SUCCESS) {
491       print("oled_scroll_off cmd failed\n");
492       return oled_scrolling;
493     }
494     oled_scrolling = false;
495   }
496   return !oled_scrolling;
497 }
498
499 uint8_t oled_max_chars(void) {
500   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
501     return OLED_DISPLAY_WIDTH / OLED_FONT_WIDTH;
502   }
503   return OLED_DISPLAY_HEIGHT / OLED_FONT_WIDTH;
504 }
505
506 uint8_t oled_max_lines(void) {
507   if (!HAS_FLAGS(oled_rotation, OLED_ROTATION_90)) {
508     return OLED_DISPLAY_HEIGHT / OLED_FONT_HEIGHT;
509   }
510   return OLED_DISPLAY_WIDTH / OLED_FONT_HEIGHT;
511 }
512
513 void oled_task(void) {
514   if (!oled_initialized) {
515     return;
516   }
517
518   oled_set_cursor(0, 0);
519
520   oled_task_user();
521
522   // Smart render system, no need to check for dirty
523   oled_render();
524
525   // Display timeout check
526 #if !defined(OLED_DISABLE_TIMEOUT)
527   if (oled_active && timer_elapsed(oled_last_activity) > OLED_TIMEOUT) {
528     oled_off();
529   }
530 #endif
531 }
532
533 __attribute__((weak))
534 void oled_task_user(void) {
535 }