I would like to generate a 10-30khz PWM signal with a span between 22% and 64% but still get full 8bit resolution.
I could maybe do this by using two timers one for PWM and another for adding low and high dead zones of the right length.
But before i spend all night coding this i thought i would ask if anyone knows of any better tricks to achieve this.
MCU is ATMega328p at 8Mhz
The way i currently plan to do it is this
-Setup TIM2 timer to fire an interrupt on COMP1 and COMP2 compare interrupts
-Setup TIM0 timer for PWM in one shot mode (using the trick of setting TOP below MATCH so it never fires unless forced to
see https://hackaday.com/2015/03/24/avr-hardware-timer-tricked-into-one-shot
-Use the interrupts to create a fixed amount of high/low dead time.
When COMP1 fires the PWM timer one shot is started and one cycle of pwm is produced at whatever pwm value i needed.
When COMP2 fires the PWM will be over and the output forced low.
TIM2 will overflow and start the cycle again.
There are some issues with this.
- At 31khz i am generating lots of interrupts. The handlers will only set maybe 2 registers, so not too bad but still a lot of cpu overhead.
- I'm not sure how i will get the two timers running at the right speed to make it work.
I may have to do the high and low dead time separately instead of within a single TIM2 cycle. (using one COMP). Then both timers can run at the same speed.Any thoughts on a better way to do this on AVR?