40khz output using fast-pwm

Good morning,
i wrote a code to drive a dc motor(right and left) with potensiometer.
Now i have to modify this code and set the frequency 40khz and then modify the duration of pwm with the potensiometer. Could you please give me a help with that?

int potPin = 0;        
int speedPin = 3;      
int motor1Pin = 6;     
int motor2Pin = 7;     
int ledPin = 13;       
int val = 0;         
int x = 0;
void setup() {
// set digital i/o pins as outputs:
pinMode(speedPin, OUTPUT);
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}
void loop() {
digitalWrite(ledPin, HIGH);  
val = analogRead(potPin);
if (val <= 511) {
x=255-(val/2);
digitalWrite(motor1Pin, LOW);
digitalWrite(motor2Pin, HIGH); 
analogWrite(speedPin, x); 
}
else {
  x=(val/2)-256;
digitalWrite(motor1Pin, HIGH);  // set leg 1 of the H-bridge high
digitalWrite(motor2Pin, LOW);   // set leg 2 of the H-bridge low
analogWrite(speedPin, x);  // output speed as PWM value


}
Serial.print("X: ");
                Serial.println(x, DEC);
}
void startTransducer()
{
  TCCR2A = _BV(COM2A0) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS20);
  OCR2A = B11000111; // 199, so timer2 counts from 0 to 199 (200 cycles at 16 MHz)
}

void setup()
{
pinMode(11, OUTPUT);
startTransducer();
}

void loop()
{
}

This code will set the PWM to another frequency around what you want, see comments in the code.

/* Code to pulse pin 3 with a modulated signal
* Can be used to drive an IR LED to keep a TSOP IR reciever happy
* This allows you to use a modulated reciever and a continious beam detector
* By Mike Cook Nov 2011 - Released under the Open Source licence
*/
 volatile byte pulse = 0;

ISR(TIMER2_COMPB_vect){  // Interrupt service routine to pulse the modulated pin 3
    pulse++;
  if(pulse >= 8) { // change number for number of modulation cycles in a pulse
    pulse =0;
    TCCR2A ^= _BV(COM2B1); // toggle pin 3 enable, turning the pin on and off
  }
}

void setIrModOutput(){  // sets pin 3 going at the IR modulation rate
  pinMode(3, OUTPUT);
  TCCR2A = _BV(COM2B1) | _BV(WGM21) | _BV(WGM20); // Just enable output on Pin 3 and disable it on Pin 11
  TCCR2B = _BV(WGM22) | _BV(CS22);
  OCR2A = 51; // defines the frequency 51 = 38.4 KHz, 54 = 36.2 KHz, 58 = 34 KHz, 62 = 32 KHz
  OCR2B = 26;  // deines the duty cycle - Half the OCR2A value for 50%
  TCCR2B = TCCR2B & 0b00111000 | 0x2; // select a prescale value of 8:1 of the system clock
}

void setup(){
  setIrModOutput();
  TIMSK2 = _BV(OCIE2B); // Output Compare Match B Interrupt Enable
}

void loop(){
// do something here
}

To change the duty cycle then change the value in OCR2B, note that this can not be greater than the value in OCR2A so the total resolution of the control is smaller that 8 bits. This is inevitable.