You are reading a single comment by @Kim and its replies. Click here to read the full conversation.
  • Here is an extended version of your last code to glow an LED. There has been a bit of a comment explosion, it allows you to specify the duration and the Hz, and it has an improved glow by taking the power of the sine function, so that only the peak is very bright. I would like to go to pow( .. , 3) but ... floating point error ;).

    // add a new function to all pins to glow
    Pin.prototype.glow = function(milliseconds, Hz) {
      // see if the user specified a Hz
      // if she/he did not, we default to 60Hz
      Hz = ((typeof Hz) === "undefined") ? 60 : Hz;
      // save the pin: this is important, as in an internal function
      // 'this' would refer to the function, and no longer the pin.
      var pin = this;
      // remember that to achieve a certain Hz, we need to 
      // have cycles every 1000/Hz milliseconds
      var cycle = 1000/Hz;
      // we need to cheat a bit and take pos > 0 since
      // sin(0) = 0 and digitalPulse does not accept 0
      var pos = 0.001;
      // next, we create the function that will call our digital pulse
      var interval = setInterval(function() {
        // we send our pulse, and we use the sine function to determine the length
        // the use of Math.pow( .. ) will epsecially lower the lowest values, while
        // keeping 1 almost 1. This will help to ensure that only the brightest
        // part of the glow is truly bright.
        digitalPulse(pin, 1, Math.pow(Math.sin(pos*Math.PI), 2)*cycle);
        // we advance to the next position, determined by 
        // how long we want one glow to take
        pos += 1/(milliseconds/cycle);
        // if we are done, we clear this interval
        if (pos>=1) clearInterval(interval);
        // finally, we launch this every cycle, where the dimmer cycles
        // will have a shorter pulse and the brighter cycles a longer pulse
      }, cycle);
    };
    
About

Avatar for Kim @Kim started