• If you only want slow-ish PWM, you can do something like this:

    Pin.prototype.pwm = function(dutyCycle, speed) {
      var pin = this;
      if (Pin.intervals===undefined)
        Pin.intervals = {};
      if (Pin.intervals[pin]!==undefined)
        clearInterval(Pin.intervals[pin]);
      var pulseLen = dutyCycle*1000/speed;
      Pin.intervals[pin] = setInterval(function() {
        digitalPulse(pin, 1, pulseLen);
      }, 1000/speed);
    };
    
    LED1.pwm(0.1, 100); // 100Hz
    

    Note that because digitalPulse uses a timer, you're only having to run JavaScript once per pulse, and not once.

    If you want to do that glowing effect then you could do something like this:

    Pin.prototype.glow = function() {
      var pin = this;
      var pos = 0.001;
      var interval = setInterval(function() {
        digitalPulse(pin, 1, Math.sin(pos*Math.PI)*20); // up to 20ms
        pos += 0.01;
        if (pos>=1) clearInterval(interval);
      }, 20); // 50Hz
    };
    
    LED1.glow();
    

    Which shouldn't halt Espruino while it's working.

About

Avatar for Gordon @Gordon started