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 ;).

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

Avatar for Kim @Kim started