Want to get 20 KHz frequency but I am getting 31 KHz frequency on arduino

int led = 9;
    int button = 8;
    int buttonState =0;
    int brightness = 0;
    int brightup = 2;
    



int duty = 50;
int nduty = map(duty, 0, 100, 0, 255);

void setup ()
  {
  TCCR2B &= ~ _BV (CS22); // cancel pre-scaler of 64
  TCCR2B |= _BV (CS20);// no pre-scaler
  analogWrite (9, nduty);   
  //analogWrite (10, 200);  // 78.4 % duty cycle
  }  // end of setup

void loop () {  analogWrite(led, brightness);
    buttonState = digitalRead(button);
    if ( buttonState == HIGH ) {
    brightness = brightness + brightup;
    }
    if ( brightness == 128 ) {
    brightness = 0;
    }
    delay(30);
  
}

Please also tell me how to use code tags

Code is just not right to be honest.

 TCCR2B &= ~ _BV (CS22); // cancel pre-scaler of 64
  TCCR2B |= _BV (CS20);// no pre-scaler

You have not even set a Wave Generation Mode.
There are further issues...but maybe have a look at an example of using Timer 2 for PWM before attempting your own. Read the datasheet on "Fast" and "Phase Correct" PWM.

In the datasheet you will find the formula for PWM frequency. You can get really course control by setting the prescale but to get fine control you will need to set TOP as well.

PrashantAkhade,
STOP CROSS-POSTING. LAST WARNING.