1 Principles

The software example presented here demonstrates the generation of ten PWM channels on an Atmel ATmega238PB Microcontroller, but is equally applicable to any other AVR with an 8-bit timer capable of generating an overflow interrupt. Low jitter is achieved by having the timer overflow as the only enabled interrupt, and by having the output signals updated during the first instructions in the Interrupt Service Routine (ISR). This makes the execution tempo very predictable, the only jitter being variations in interrupt response time which depends on the instruction being executed at the exact moment the interrupt occurs, giving a typical jitter of ±1 clock cycle. With the full PWM cycle time being 65536 clock cycles, jitter is therefore ±0.0015% of the PWM base frequency and is non-cumulative over time.

The general principle of the software PWM is to mimic the operation of the hardware timers in PWM mode. An array of ‘compare’ values is established with elements set to the required PWM pulse widths, and a complementary ‘compbuff’ array is used to double-buffer any compare array update, ensuring consistent PWM operation. An 8-bit timer is initialized to count the main clock and generate an interrupt on overflow, so an interrupt occurs once every 256-clock cycles. This means the ISR must complete in less than 256 cycles to maintain the low jitter specification. An 8-bit soft counter is incremented during each ISR to act as a position indicator within the PWM cycle, giving a PWM resolution of 1/256 or ~0.4%, and an overall PWM base frequency of main clock/(256 * 256).