Adafruit provide the following code to produce a 38kHz IR carrier.... you can adjust the numbers to try to get 40. It doesn't use analogWrite, but just does digtalWrites. 40kHz needs a total of 25uS.
// 38 kHz is about 13 microseconds high and 13 microseconds low
 digitalWrite(IRledPin, HIGH); // this takes about 3 microseconds to happen
 delayMicroseconds(10);    // hang out for 10 microseconds, you can also change this to 9 if its not working
 digitalWrite(IRledPin, LOW); // this also takes about 3 microseconds
 delayMicroseconds(10);    // hang out for 10 microseconds, you can also change this to 9 if its not working
I found that gave 36kHz with delays of 10; 9 gave closer to 38.
This code gives me a slightly asymmetric wave close to 40kHz
// to get a square wave
byte wavePin = 2;
void setup()
{
 pinMode(wavePin, OUTPUT);
}
void loop()
{
// 40kHz is 25us
 digitalWrite(wavePin, HIGH); // seems about 4
 delayMicroseconds(8);    Â
 digitalWrite(wavePin, LOW); Â
 delayMicroseconds(9);  Â
}
the function call of - loop() - overhead can be removed to make it more symmetrical (see below)
using direct port manipulation instead of digitalWrite is faster so better timing possible
using a HW timer i.s.o delayMicroseconds will also improve timing
// to get a square wave
byte wavePin = 2;
void setup()
{
 pinMode(wavePin, OUTPUT);
}
void loop()
{
 while(1)
 {
 digitalWrite(wavePin, HIGH); // seems about 4
 delayMicroseconds(9);   Â
 digitalWrite(wavePin, LOW);Â
 delayMicroseconds(9);
 }
}
This is the code I have for making the PWM go at the sorts of frequencies you want.
Just do an analogWrite to pin 3 with a value of 128.
/* Code to pulse pin 3 with a modulated signal
* By Mike Cook Nov 2011 - Released under the Open Source license
*/
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();
}
void loop(){
// do something here
}
OCR2A controls the PWM frequency, it looks like something in the order of a value of 49 should give you what you want.