Software PWM

Posted on
  • It turns out software PWM is much easier than I thought it would be, so I've been experimenting with adding it to Espruino - it's especially useful for the LEDs on the Pico.

    But... how should it be exposed? In my prototype, if you do:

    analogWrite(pin, 0.5);
    

    It'll use a DAC if it's available, followed by hardware PWM, followed by software PWM. But you have no way to tell which one it's using, which could be dangerous - especially if using really high frequencies.

    I guess an option would be to use the optional 3rd argument, like so:

    >analogWrite(LED1, 0.5);
    Pin B2 is not capable of PWM, available pins are:
    ...
    Or use software pwm with analogWrite(pin, val, {soft:true});
    >analogWrite(LED1, 0.5, {soft:true});
    ... now works
    

    But then that's not very beginner friendly. Perhaps it could default to using 50Hz PWM, and if you specified a frequency but not soft:true it'd complain?

    >analogWrite(LED1, 0.5);
    ... works
    >analogWrite(LED1, 0.5, {freq:1000});
    Pin B2 is not capable of Hardware PWM, available pins are:
    ...
    Or use software pwm with analogWrite(pin, val, {soft:true});
    >analogWrite(LED1, 0.5, {freq:1000, soft:true});
    ... now works
    

    Thoughts?

  • I would do it on a pin per pin basis. If it supports hardware then use it to its limits. If the pin can only do software pwm then allow only a specific freq range. If parameters are outside the limits then throw an error.

    IMO

  • Ok... and just do it automatically, without mentioning anything?

  • I prefer this:

    >analogWrite(LED1, 0.5);
    Pin B2 is not capable of PWM, available pins are:
    ...
    Or use software pwm with analogWrite(pin, val, {soft:true});
    >analogWrite(LED1, 0.5, {soft:true});
    ... now works
    
    

    This would gently discourage people from using software PWM (with it's potential impact on performance and constant interrupts happening in the background), while still making the route to use software PWM clear. I don't think we should be letting people use an inferior PWM mode without them knowing that they are.

    Is anyone having a problem with there not being enough PWM pins on the Espruino?! How do you use that many PWM pins?!

  • Are you saying that software PWM should not be possible?

  • I'm saying it should be possible, but since hardware pwm is more desirable, we should encourage use of that, rather than software pwm.it would be bad, imo, if someone who could pick whatever pins they wanted, wound up using software pwm because they chose a pin without hardware pwm.

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

Software PWM

Posted by Avatar for Gordon @Gordon

Actions