31khz PWM on TIMER2 atmega8

I have been trying to generate a 31khz variable duty cycle pwm on atmega8. So far I have been able to generate 7 different frequency pwm with Fast pwm and 16mhz external crystal.

But I cant seem to generate 31khz variable duty cycle one.

I can use ctc mode but its toogle only.

Any help will be appreciated :slight_smile:

Post the code, using code tags, and explain the problem with it.

void setup() {
  pinMode(11, OUTPUT);
  TCCR2=0x6A; //01101010 in hex
  OCR2=0x80; //128 in hex


void loop() {


This gives me a 7.8khz 50% pwm on pin 11. What I am trying to achieve a 31khz pwm with variable duty cycle.

I am using minicore at here for compilation for atmega8

The clock select bits you have chosen for TCCR2 divide the system clock by 8. Choose TCCR2= 0x68 to divide by 1, for 62.5 kHz PWM.

For intermediate values you need to use a different TOP than 256, with a decrease in PWM resolution.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.