Repository navigation
Expand file tree
/
Copy pathunicornhat-hd.js
More file actions
102 lines (82 loc) · 2.17 KB
/
Copy pathunicornhat-hd.js
File metadata and controls
102 lines (82 loc) · 2.17 KB
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
var SPI = require('pi-spi');
function UnicornHatHD(device) {
this.matrix = [];
for (var y = 0; y < 16; y++) {
this.matrix.push([]);
for (var x = 0; x < 16; x++) {
this.matrix[y].push({
r: 0,
g: 0,
b: 0
})
}
}
this.brightness = 0.5;
this.spi = SPI.initialize(device);
}
UnicornHatHD.prototype.setBrightness = function(brightness) {
this.brightness = brightness;
};
UnicornHatHD.prototype.getBrightness = function() {
return this.brightness;
};
UnicornHatHD.prototype.setAll = function(r, g, b) {
if (r !== parseInt(r, 10)) {
throw 'r must be an integer';
}
if (g !== parseInt(g, 10)) {
throw 'r must be an integer';
}
if (b !== parseInt(b, 10)) {
throw 'b must be an integer';
}
for (var x = 0; x < 16; x++) {
for (var y = 0; y < 16; y++) {
this.matrix[x][y].r = r;
this.matrix[x][y].g = g;
this.matrix[x][y].b = b;
}
}
};
UnicornHatHD.prototype.setPixel = function(x, y, r, g, b) {
this.matrix[x][y].r = r;
this.matrix[x][y].g = g;
this.matrix[x][y].b = b;
};
UnicornHatHD.prototype.getPixel = function(x, y) {
return [
this.matrix[x][y].r,
this.matrix[x][y].g,
this.matrix[x][y].b
];
};
UnicornHatHD.prototype.rotate = function() {
this.matrix = this.matrix[0].map((_, colIndex) => this.matrix.map(row => row[colIndex]));
}
UnicornHatHD.prototype.clear = function() {
this.setAll(0, 0, 0);
};
UnicornHatHD.prototype.show = function(flip_horizontal, flip_vertical) {
if (flip_horizontal) {
for (var i = 0; i < this.matrix.length; i++) {
this.matrix[i].reverse();
}
}
if (flip_vertical) {
this.matrix.reverse();
}
var buffer = new Buffer(16 * 16 * 3);
for (var y = 0; y < 16; y++) {
for (var x = 0; x < 16; x++) {
buffer[y * 16 * 3 + x * 3 + 0] = this.matrix[x][y].r * this.brightness;
buffer[y * 16 * 3 + x * 3 + 1] = this.matrix[x][y].g * this.brightness;
buffer[y * 16 * 3 + x * 3 + 2] = this.matrix[x][y].b * this.brightness;
}
}
this.spi.write(Buffer.concat([new Buffer([0x72]), buffer]), function(err) {
if (err) {
throw 'Something went wrong!';
}
});
};
module.exports = UnicornHatHD;