Flashing lights example try 4 not working

Posted on
  • Hello,

    I just received my espruinos and started typing a few examples.
    I have upgraded the firmware as explained in the quick start guide and I am following this tutorial: http://www.espruino.com/Flashing+Lights
    The code under "try 4" is not working as expected:

    Pin.prototype.startFlashing = function(period) { 
      var on = false;
      setInterval(function() {
        on = !on;
        digitalWrite(this, on);
      }, period);
    }
    LED1.startFlashing(100);
    

    On the console I can read "ERROR: Invalid pin!". There seems to be a problem handling "this", in fact the issue seems to be the same as in this other forum post: http://forum.espruino.com/conversations/­389/

    The code works fine with the following modification:

    Pin.prototype.startFlashing = function(period) {
      var me = this;
      var on = false;
      setInterval(function() {
        on = !on;
        digitalWrite(me, on);
      }, period);
    }
    
    LED1.startFlashing(100);
    

    Just letting you know, I don't know this should be considered a bug in the code or in the documentation.

    Thanks a lot!

  • Great, thanks for letting me know! I've just updated the code/documentation.

    It's because Espruino used to remember the value of 'this' when setInterval was called (which I believe was wrong). I fixed that and forgot to change the docs :)

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Flashing lights example try 4 not working

Posted by Avatar for nglod @nglod

Actions