|
| 1 | +load("api_bitbang.js"); |
| 2 | +load("api_gpio.js"); |
| 3 | +load("api_sys.js"); |
| 4 | + |
| 5 | +let NeoPixel = { |
| 6 | + RGB: 0, |
| 7 | + GRB: 1, |
| 8 | + BGR: 2, |
| 9 | + |
| 10 | + // ## **`NeoPixel.create(pin, numPixels, order)`** |
| 11 | + // Create and return a NeoPixel strip object. Example: |
| 12 | + // ```javascript |
| 13 | + // let pin = 5, numPixels = 16, colorOrder = NeoPixel.GRB; |
| 14 | + // let strip = NeoPixel.create(pin, numPixels, colorOrder); |
| 15 | + // strip.setPixel(0 /* pixel */, 12, 34, 56); |
| 16 | + // strip.show(); |
| 17 | + // |
| 18 | + // strip.clear(); |
| 19 | + // strip.setPixel(1 /* pixel */, 12, 34, 56); |
| 20 | + // strip.show(); |
| 21 | + // ``` |
| 22 | + create: function(pin, numPixels, order) { |
| 23 | + GPIO.set_mode(pin, GPIO.MODE_OUTPUT); |
| 24 | + GPIO.write(pin, 0); // Keep in reset. |
| 25 | + let s = Object.create({ |
| 26 | + pin: pin, |
| 27 | + len: numPixels * 3, |
| 28 | + // Note: memory allocated here is currently not released. |
| 29 | + // This should be ok for now, we don't expect strips to be re-created. |
| 30 | + data: Sys.malloc(numPixels * 3), |
| 31 | + order: order, |
| 32 | + setPixel: NeoPixel.set, |
| 33 | + clear: NeoPixel.clear, |
| 34 | + show: NeoPixel.show, |
| 35 | + }); |
| 36 | + s.clear(); |
| 37 | + return s; |
| 38 | + }, |
| 39 | + |
| 40 | + // ## **`strip.setPixel(i, r, g, b)`** |
| 41 | + // Set i-th's pixel's RGB value. |
| 42 | + // Note that this only affects in-memory value of the pixel. |
| 43 | + set: function(i, r, g, b) { |
| 44 | + let v0, v1, v2; |
| 45 | + if (this.order === NeoPixel.RGB) { |
| 46 | + v0 = r; v1 = g; v2 = b; |
| 47 | + } else if (this.order === NeoPixel.GRB) { |
| 48 | + v0 = g; v1 = r; v2 = b; |
| 49 | + } else if (this.order === NeoPixel.BGR) { |
| 50 | + v0 = b; v1 = g; v2 = r; |
| 51 | + } else { |
| 52 | + return; |
| 53 | + } |
| 54 | + this.data[i * 3] = v0; |
| 55 | + this.data[i * 3 + 1] = v1; |
| 56 | + this.data[i * 3 + 2] = v2; |
| 57 | + }, |
| 58 | + |
| 59 | + // ## **`strip.clear()`** |
| 60 | + // Clear in-memory values of the pixels. |
| 61 | + clear: function() { |
| 62 | + for (let i = 0; i < this.len; i++) { |
| 63 | + this.data[i] = 0; |
| 64 | + } |
| 65 | + }, |
| 66 | + |
| 67 | + // ## **`strip.show()`** |
| 68 | + // Output values of the pixels. |
| 69 | + show: function() { |
| 70 | + GPIO.write(this.pin, 0); |
| 71 | + Sys.usleep(60); |
| 72 | + BitBang.write(this.pin, BitBang.DELAY_100NSEC, 3, 8, 8, 6, this.data, this.len); |
| 73 | + GPIO.write(this.pin, 0); |
| 74 | + Sys.usleep(60); |
| 75 | + GPIO.write(this.pin, 1); |
| 76 | + }, |
| 77 | +}; |
0 commit comments