-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathlarson.js
More file actions
119 lines (93 loc) · 2.45 KB
/
larson.js
File metadata and controls
119 lines (93 loc) · 2.45 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
/**
* larson.js
*
* Larson scanner (AKA Cylon or Knight Rider)
*
* LEDstrip plugin
*
* Copyright (c) 2013 Dougal Campbell
*
* Distributed under the MIT License
*/
function Larson (ledstrip, opts) {
opts = opts || {};
this.ledstrip = ledstrip;
this.ledstrip.clear();
this.direction = 1;
this.color = opts.color || [255,0,0]; // default to red
this.speed = opts.speed || 3; // run every Nth tick? 1 == full speed
this.spread = opts.spread || 3; // spread N pixels on either side
// tick counter
this.t = 0;
this.position = 0;
return this;
}
Larson.prototype.init = function() {return this;}
Larson.prototype.setColor = function(color) {
this.color = color;
return this;
}
Larson.prototype.setSpeed = function(speed) {
this.speed = speed;
return this;
}
Larson.prototype.setSpread = function(spread) {
this.spread = spread;
return this;
}
Larson.prototype.setPosition = function(pos) {
this.position = pos;
return this;
}
Larson.prototype.setDirection = function(dir) {
if (dir >= 0) {
this.direction = 1;
} else {
this.direction = -1;
}
return this;
}
Larson.prototype.scan = function (tick) {
var fade, i, spos, scol;
if (!(tick % this.speed == 0)) return; // speed control
this.ledstrip.clear();
// Set the primary dot
this.ledstrip.buffer[this.position] = this.color;
// handle spread
if (this.spread > 0) {
fade = 1 / (this.spread + 1);
for (i = 1; i <= this.spread; i++) {
scol = [
Math.floor(this.color[0] * ((this.spread + 1 - i) / (this.spread + 1))),
Math.floor(this.color[1] * ((this.spread + 1 - i) / (this.spread + 1))),
Math.floor(this.color[2] * ((this.spread + 1 - i) / (this.spread + 1)))
];
if (this.position + i < this.ledstrip.buffer.length) {
this.ledstrip.buffer[this.position + i] = scol;
}
if (this.position - i >= 0) {
this.ledstrip.buffer[this.position - i] = scol;
}
}
}
/**
* Update position and direction for next pass
*/
this.position += this.direction;
// check for out-of-bounds:
if (this.position >= this.ledstrip.buffer.length) {
this.position -= 2;
this.direction = -1; // all skate, reverse direction!
}
if (this.position < 0) {
this.position += 2;
this.direction = 1;
}
this.ledstrip.send();
return this;
}
Larson.prototype.animate = function() {
animation = requestAnimationFrame(this.animate.bind(this)); // preserve our context
this.scan(this.t++); // calculate waves and increment tick
this.ledstrip.send(); // update strip
}