[...] pwm in software [...]
PWM using timer works in the following way (simplified explanation):
- Set top value to say 100.
- Set compare value to 50
- Start timer (timer starts with current value equal to 0
- With every clock cycle current value gets incremented by 1
- When current value is equal to compare value, designated PWM pin is set to HIGH
- When current value is equal to top value, designated PWM pin is set to LOW
- Timer resets to 0, everything start all over
By changing compare value
You set duty cycle (how long PWM pin stays HIGH).
By changing top value
You set frequency (how many times per minute PWM cycle repeats).
All what's above can be done in software, only instead of timer counting from 0 to top value
, You simply count that in Your main loop, use if()
statements to check if current value
is equal to compare value
or top value
and flick any IO pin if before mentioned conditions are met.
Problem with software PWM is that the more You have in Your main loop, the bigger error You get in Your PWM signal. This can be avoided if You're willing to program in ASM, take into consideration how many commands Your main loop has, how long they take to execute and manually compensate for cycles lost executing them. Also, there are interrupts that interrupt main loop, hence they also interrupt Your software PWM causing error in timing.
Hope that helps