In this post I will be referring to Pulse Width Modulation as PWM, which you can read about more here.
Since before I started working on this project I did not know anything about PWM, I did a bit of reading on-line and without getting into too much technical detail I started coding it as it first came to mind. The graph below is what I came up with.
PWM in Software
The diagram abobe shows five parallel processes:
- ticker controls the rate at which sine, and saw and control operate. It also dictates the rate at which control operates, although not necessary;
- saw and sine are just two oscillating functions, the difference being that sine has a constant increment, while saw has its increment dependent on the level you want to do PWM; since they have different increment / decrement rates, they intersect at rates dependent on the level you pass to saw;
- control reads the values from saw and sine and if they crossed sends a signal to switch;
- switch upon receiving a signal flips the power on or off.
This implementation, even though very ugly, does what it is supposed to do, almost. By almost I mean it modulates the pulse, but the modulation is not fast enough to give an impression of dimming an LED. That is, the LED appears to just blink at a fast rate, but to actually achieve PWM as it is supposed to be, we would need a much faster virtual machine.