forked from noopkat/oled-js
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy patholed.js
543 lines (464 loc) · 14.9 KB
/
oled.js
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
var i2c = require('i2c');
var Oled = function(opts) {
this.HEIGHT = opts.height || 32;
this.WIDTH = opts.width || 128;
this.ADDRESS = opts.address || 0x3C;
this.PROTOCOL = 'I2C';
// create command buffers
this.DISPLAY_OFF = 0xAE;
this.DISPLAY_ON = 0xAF;
this.SET_DISPLAY_CLOCK_DIV = 0xD5;
this.SET_MULTIPLEX = 0xA8;
this.SET_DISPLAY_OFFSET = 0xD3;
this.SET_START_LINE = 0x00;
this.CHARGE_PUMP = 0x8D;
this.EXTERNAL_VCC = false;
this.MEMORY_MODE = 0x20;
this.SEG_REMAP = 0xA1; // using 0xA0 will flip screen
this.COM_SCAN_DEC = 0xC8;
this.COM_SCAN_INC = 0xC0;
this.SET_COM_PINS = 0xDA;
this.SET_CONTRAST = 0x81;
this.SET_PRECHARGE = 0xd9;
this.SET_VCOM_DETECT = 0xDB;
this.DISPLAY_ALL_ON_RESUME = 0xA4;
this.NORMAL_DISPLAY = 0xA6;
this.COLUMN_ADDR = 0x21;
this.PAGE_ADDR = 0x22;
this.INVERT_DISPLAY = 0xA7;
this.ACTIVATE_SCROLL = 0x2F;
this.DEACTIVATE_SCROLL = 0x2E;
this.SET_VERTICAL_SCROLL_AREA = 0xA3;
this.RIGHT_HORIZONTAL_SCROLL = 0x26;
this.LEFT_HORIZONTAL_SCROLL = 0x27;
this.VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29;
this.VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A;
this.cursor_x = 0;
this.cursor_y = 0;
// new blank buffer
this.buffer = new Buffer((this.WIDTH * this.HEIGHT) / 8);
this.buffer.fill(0x00);
this.dirtyBytes = [];
var config = {
'128x32': {
'multiplex': 0x1F,
'compins': 0x02,
'coloffset': 0
},
'128x64': {
'multiplex': 0x3F,
'compins': 0x12,
'coloffset': 0
},
'96x16': {
'multiplex': 0x0F,
'compins': 0x2,
'coloffset': 0,
}
};
// Setup i2c
console.log('this.ADDRESS: ' + this.ADDRESS);
this.wire = new i2c(this.ADDRESS, {device: '/dev/i2c-0'}); // point to your i2c address, debug provides REPL interface
var screenSize = this.WIDTH + 'x' + this.HEIGHT;
this.screenConfig = config[screenSize];
this._initialise();
}
Oled.prototype._initialise = function() {
// sequence of bytes to initialise with
var initSeq = [
this.DISPLAY_OFF,
this.SET_DISPLAY_CLOCK_DIV, 0x80,
this.SET_MULTIPLEX, this.screenConfig.multiplex, // set the last value dynamically based on screen size requirement
this.SET_DISPLAY_OFFSET, 0x00, // sets offset pro to 0
this.SET_START_LINE,
this.CHARGE_PUMP, 0x14, // charge pump val
this.MEMORY_MODE, 0x00, // 0x0 act like ks0108
this.SEG_REMAP, // screen orientation
this.COM_SCAN_DEC, // screen orientation change to INC to flip
this.SET_COM_PINS, this.screenConfig.compins, // com pins val sets dynamically to match each screen size requirement
this.SET_CONTRAST, 0x8F, // contrast val
this.SET_PRECHARGE, 0xF1, // precharge val
this.SET_VCOM_DETECT, 0x40, // vcom detect
this.DISPLAY_ALL_ON_RESUME,
this.NORMAL_DISPLAY,
this.DISPLAY_ON
];
var i, initSeqLen = initSeq.length;
// write init seq commands
for (i = 0; i < initSeqLen; i ++) {
this._transfer('cmd', initSeq[i]);
}
}
// writes both commands and data buffers to this device
Oled.prototype._transfer = function(type, val, fn) {
var control;
if (type === 'data') {
control = 0x40;
} else if (type === 'cmd') {
control = 0x00;
} else {
return;
}
// send control and actual val
// this.board.io.i2cWrite(this.ADDRESS, [control, val]);
this.wire.writeByte(control, function(err) {
this.wire.writeByte(val, function(err) {
fn();
});
});
}
// read a byte from the oled
Oled.prototype._readI2C = function(fn) {
this.wire.readByte(function(err, data) {
// result is single byte
fn(data);
});
}
// sometimes the oled gets a bit busy with lots of bytes.
// Read the response byte to see if this is the case
Oled.prototype._waitUntilReady = function(callback) {
var done,
oled = this;
function tick(callback) {
oled._readI2C(function(byte) {
// read the busy byte in the response
busy = byte >> 7 & 1;
if (!busy) {
// if not busy, it's ready for callback
callback();
} else {
console.log('I\'m busy!');
setTimeout(tick, 0);
}
});
};
setTimeout(tick(callback), 0);
}
// set starting position of a text string on the oled
Oled.prototype.setCursor = function(x, y) {
this.cursor_x = x;
this.cursor_y = y;
}
// write text to the oled
Oled.prototype.writeString = function(font, size, string, color, wrap, sync) {
var immed = (typeof sync === 'undefined') ? true : sync;
var wordArr = string.split(' '),
len = wordArr.length,
// start x offset at cursor pos
offset = this.cursor_x,
padding = 0, letspace = 1, leading = 2;
// loop through words
for (var w = 0; w < len; w += 1) {
// put the word space back in
wordArr[w] += ' ';
var stringArr = wordArr[w].split(''),
slen = stringArr.length,
compare = (font.width * size * slen) + (size * (len -1));
// wrap words if necessary
if (wrap && len > 1 && (offset >= (this.WIDTH - compare)) ) {
offset = 1;
this.cursor_y += (font.height * size) + size + leading;
this.setCursor(offset, this.cursor_y);
}
// loop through the array of each char to draw
for (var i = 0; i < slen; i += 1) {
// look up the position of the char, pull out the buffer slice
var charBuf = this._findCharBuf(font, stringArr[i]);
// read the bits in the bytes that make up the char
var charBytes = this._readCharBytes(charBuf);
// draw the entire character
this._drawChar(charBytes, size, false);
// calc new x position for the next char, add a touch of padding too if it's a non space char
padding = (stringArr[i] === ' ') ? 0 : size + letspace;
offset += (font.width * size) + padding;
// wrap letters if necessary
if (wrap && (offset >= (this.WIDTH - font.width - letspace))) {
offset = 1;
this.cursor_y += (font.height * size) + size + leading;
}
// set the 'cursor' for the next char to be drawn, then loop again for next char
this.setCursor(offset, this.cursor_y);
}
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes);
}
}
// draw an individual character to the screen
Oled.prototype._drawChar = function(byteArray, size, sync) {
// take your positions...
var x = this.cursor_x,
y = this.cursor_y;
// loop through the byte array containing the hexes for the char
for (var i = 0; i < byteArray.length; i += 1) {
for (var j = 0; j < 8; j += 1) {
// pull color out
var color = byteArray[i][j],
xpos, ypos;
// standard font size
if (size === 1) {
xpos = x + i;
ypos = y + j;
this.drawPixel([xpos, ypos, color], false);
} else {
// MATH! Calculating pixel size multiplier to primitively scale the font
xpos = x + (i * size);
ypos = y + (j * size);
this.fillRect(xpos, ypos, size, size, color, false);
}
}
}
}
// get character bytes from the supplied font object in order to send to framebuffer
Oled.prototype._readCharBytes = function(byteArray) {
var bitArr = [],
bitCharArr = [];
// loop through each byte supplied for a char
for (var i = 0; i < byteArray.length; i += 1) {
// set current byte
var byte = byteArray[i];
// read each byte
for (var j = 0; j < 8; j += 1) {
// shift bits right until all are read
var bit = byte >> j & 1;
bitArr.push(bit);
}
// push to array containing flattened bit sequence
bitCharArr.push(bitArr);
// clear bits for next byte
bitArr = [];
}
return bitCharArr;
}
// find where the character exists within the font object
Oled.prototype._findCharBuf = function(font, c) {
// use the lookup array as a ref to find where the current char bytes start
var cBufPos = font.lookup.indexOf(c) * font.width;
// slice just the current char's bytes out of the fontData array and return
var cBuf = font.fontData.slice(cBufPos, cBufPos + font.width);
return cBuf;
}
// send the entire framebuffer to the oled
Oled.prototype.update = function() {
// wait for oled to be ready
this._waitUntilReady(function() {
// set the start and endbyte locations for oled display update
var displaySeq = [
this.COLUMN_ADDR,
this.screenConfig.coloffset,
this.screenConfig.coloffset + this.WIDTH - 1, // column start and end address
this.PAGE_ADDR, 0, (this.HEIGHT / 8) - 1 // page start and end address
];
var displaySeqLen = displaySeq.length,
bufferLen = this.buffer.length,
i, v;
// send intro seq
for (i = 0; i < displaySeqLen; i += 1) {
this._transfer('cmd', displaySeq[i]);
}
// write buffer data
for (v = 0; v < bufferLen; v += 1) {
this._transfer('data', this.buffer[v]);
}
}.bind(this));
}
// send dim display command to oled
Oled.prototype.dimDisplay = function(bool) {
var contrast;
if (bool) {
contrast = 0; // Dimmed display
} else {
contrast = 0xCF; // Bright display
}
this._transfer('cmd', this.SET_CONTRAST);
this._transfer('cmd', contrast);
}
// turn oled off
Oled.prototype.turnOffDisplay = function() {
this._transfer('cmd', this.DISPLAY_OFF);
}
// turn oled on
Oled.prototype.turnOnDisplay = function() {
this._transfer('cmd', this.DISPLAY_ON);
}
// clear all pixels currently on the display
Oled.prototype.clearDisplay = function(sync) {
var immed = (typeof sync === 'undefined') ? true : sync;
// write off pixels
//this.buffer.fill(0x00);
for (var i = 0; i < this.buffer.length; i += 1) {
if (this.buffer[i] !== 0x00) {
this.buffer[i] = 0x00;
if (this.dirtyBytes.indexOf(i) === -1) {
this.dirtyBytes.push(i);
}
}
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes);
}
}
// invert pixels on oled
Oled.prototype.invertDisplay = function(bool) {
if (bool) {
this._transfer('cmd', this.INVERT_DISPLAY); // inverted
} else {
this._transfer('cmd', this.NORMAL_DISPLAY); // non inverted
}
}
// draw an image pixel array on the screen
Oled.prototype.drawBitmap = function(pixels, sync) {
var immed = (typeof sync === 'undefined') ? true : sync;
var x, y,
pixelArray = [];
for (var i = 0; i < pixels.length; i++) {
x = Math.floor(i % this.WIDTH);
y = Math.floor(i / this.WIDTH);
this.drawPixel([x, y, pixels[i]], false);
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes);
}
}
// draw one or many pixels on oled
Oled.prototype.drawPixel = function(pixels, sync) {
var immed = (typeof sync === 'undefined') ? true : sync;
// handle lazy single pixel case
if (typeof pixels[0] !== 'object') pixels = [pixels];
pixels.forEach(function(el) {
// return if the pixel is out of range
var x = el[0], y = el[1], color = el[2];
if (x > this.WIDTH || y > this.HEIGHT) return;
// thanks, Martin Richards.
// I wanna can this, this tool is for devs who get 0 indexes
//x -= 1; y -=1;
var byte = 0,
page = Math.floor(y / 8),
pageShift = 0x01 << (y - 8 * page);
// is the pixel on the first row of the page?
(page == 0) ? byte = x : byte = x + (this.WIDTH * page);
// colors! Well, monochrome.
if (color === 'BLACK' || color === 0) {
this.buffer[byte] &= ~pageShift;
}
if (color === 'WHITE' || color > 0) {
this.buffer[byte] |= pageShift;
}
// push byte to dirty if not already there
if (this.dirtyBytes.indexOf(byte) === -1) {
this.dirtyBytes.push(byte);
}
}, this);
if (immed) {
this._updateDirtyBytes(this.dirtyBytes);
}
}
// looks at dirty bytes, and sends the updated bytes to the display
Oled.prototype._updateDirtyBytes = function(byteArray) {
var blen = byteArray.length, i,
displaySeq = [];
// check to see if this will even save time
if (blen > (this.buffer.length / 7)) {
// just call regular update at this stage, saves on bytes sent
this.update();
// now that all bytes are synced, reset dirty state
this.dirtyBytes = [];
} else {
this._waitUntilReady(function() {
// iterate through dirty bytes
for (var i = 0; i < blen; i += 1) {
var byte = byteArray[i];
var page = Math.floor(byte / this.WIDTH);
var col = Math.floor(byte % this.WIDTH);
var displaySeq = [
this.COLUMN_ADDR, col, col, // column start and end address
this.PAGE_ADDR, page, page // page start and end address
];
var displaySeqLen = displaySeq.length, v;
// send intro seq
for (v = 0; v < displaySeqLen; v += 1) {
this._transfer('cmd', displaySeq[v]);
}
// send byte, then move on to next byte
this._transfer('data', this.buffer[byte]);
this.buffer[byte];
}
}.bind(this));
}
// now that all bytes are synced, reset dirty state
this.dirtyBytes = [];
}
// using Bresenham's line algorithm
Oled.prototype.drawLine = function(x0, y0, x1, y1, color, sync) {
var immed = (typeof sync === 'undefined') ? true : sync;
var dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1,
dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1,
err = (dx > dy ? dx : -dy) / 2;
while (true) {
this.drawPixel([x0, y0, color], false);
if (x0 === x1 && y0 === y1) break;
var e2 = err;
if (e2 > -dx) {err -= dy; x0 += sx;}
if (e2 < dy) {err += dx; y0 += sy;}
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes);
}
}
// draw a filled rectangle on the oled
Oled.prototype.fillRect = function(x, y, w, h, color, sync) {
var immed = (typeof sync === 'undefined') ? true : sync;
// one iteration for each column of the rectangle
for (var i = x; i < x + w; i += 1) {
// draws a vert line
this.drawLine(i, y, i, y+h-1, color, false);
}
if (immed) {
this._updateDirtyBytes(this.dirtyBytes);
}
}
// activate scrolling for rows start through stop
Oled.prototype.startScroll = function(dir, start, stop) {
var scrollHeader,
cmdSeq = [];
switch (dir) {
case 'right':
cmdSeq.push(this.RIGHT_HORIZONTAL_SCROLL); break;
case 'left':
cmdSeq.push(this.LEFT_HORIZONTAL_SCROLL); break;
// TODO: left diag and right diag not working yet
case 'left diagonal':
cmdSeq.push(
this.SET_VERTICAL_SCROLL_AREA, 0x00,
this.VERTICAL_AND_LEFT_HORIZONTAL_SCROLL,
this.HEIGHT
);
break;
// TODO: left diag and right diag not working yet
case 'right diagonal':
cmdSeq.push(
this.SET_VERTICAL_SCROLL_AREA, 0x00,
this.VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL,
this.HEIGHT
);
break;
}
this._waitUntilReady(function() {
cmdSeq.push(
0x00, start,
0x00, stop,
// TODO: these need to change when diagonal
0x00, 0xFF,
this.ACTIVATE_SCROLL
);
var i, cmdSeqLen = cmdSeq.length;
for (i = 0; i < cmdSeqLen; i += 1) {
this._transfer('cmd', cmdSeq[i]);
}
}.bind(this));
}
// stop scrolling display contents
Oled.prototype.stopScroll = function() {
this._transfer('cmd', this.DEACTIVATE_SCROLL); // stahp
}
module.exports = Oled;