Electronic – Arduino PWM pin vs digital pin PWM simulation

arduinodigital-logicpinspwm

Do I understand it correctly from this thread, Why do some pins have `~` signs next to their numbers?, that the PWM pins generate a square wave signal independently from what the code uploaded to the chip does after starting the PWM output? In other words, if my code contains all sorts of delay() functions that pause longer than the period of the PWM signal, the PWM signal will still be generated properly, correct?

On the other hand, if I decided to implement my own PWM on a digital pin instead by flipping the state between HIGH and LOW in my code at regular intervals, the presence of other delay() calls in other parts of the code would directly impact my ability to generate the desired consistent PWM signal. Is this correct? I hope this question makes sense (a bit hard to ask the question).

Best Answer

You understood right. The pins with the tilde (~) symbol are pins which are linked to an hardware PWM module (i.e. timer). Since it is a hardware module, it is independent of whatever your CPU does. As such, if you are stuck in a delay, your hardware PWM will still continue to generate the proper output signal. On the other hand, a software PWM (one that you would generate with a manual pin toggling) would be interrupted by your delay.

Most of the time, you should prefer hardware PWM over software PWM for many reason:

  1. It's more reliable;
  2. It consumes less power (you could sleep your MCU while still generating PWMs);
  3. It allows you to do something else instead of servicing the switching;
  4. It allows for larger frequencies, because you can typically get frequencies up to your MCU's operating frequency, while a software emulation involves a few operations, so you are not able to keep up;
  5. It's more accurate: the hardware PWM is simply a divider on your MCU's operating frequency, while software PWM uses CPU instructions, which require branching. Since it is compiled code, it is more or less deterministic, so your duty cycle would not be exactly the one you expect (near, but not perfect nor stable if doing something else at the same time).
Related Topic