-
• #2
Thanks for this. It might tidy modules up quite a bit.
-
• #3
Here is one more I named LED. It is a very simple class the can handle three led states:
on / off / blink( duration in ms for off and on)
Some led are switched on with Pin.write(1) and some with Pin.write(0) thats why the constructor needs two parameter, one for the pin and one for the value used to switch the led on.
class LED { constructor(led, on) { this.led = led; this.ON = on; this.id = 0; } on() { this.off(); this.led.write(this.ON); } off(){ if ( this.id ) { clearInterval(this.id); this.id = 0; } this.led.write(!this.ON); } blink(t){ this.off(); this.id = setInterval(function(led){led.toggle();},t, this.led); } }
Code to test class LED on a Pico
/* Pico LED1 red LED2 green */ led1 = new LED(LED1, true); led1.blink(500); led2 = new LED(LED2, true); led2.blink(250); // stop after 10 sec setTimeout(function(){led1.off();led2.off();},1E4);
Hope it is useful ;-)
-
• #4
Just to add to this, there's another 'hack' for things like this - since you can add to the built-in classes in Espruino, it is possible to just extend
Pin
:Pin.prototype.blink = function(t) { ... } LED1.blink();
The gotcha here is that there's no storage for fields (like the interval's ID) in the Pin itself, so you'd have to store them elsewhere, like maybe in a closure:
(function() { var ids = []; Pin.prototype.on = function() { this.blink(0); this.set(); }; Pin.prototype.off = function() { this.blink(0); this.reset(); }; Pin.prototype.blink = function(t) { this.write(0); if (ids[this]) clearInterval(ids[this]); if (t) ids[this] = setInterval(_=>this.toggle(), t); else delete ids[this]; }; })(); LED1.blink(100); ... LED1.off();
In reality it's maybe not as clean as @MaBe's suggestion, but it's an interesting thing to be aware of :)
Like to share how to write a module containing a class
and use it.