200khz PWM 50% duty cycle

I have the arduino Mega 2560 and I'm trying to get it to put out a PWM signal of 200khz @ 50% duty cycle.
Unfortunately my coding skills are rusty and it seems to be more complicated than I thought.
Can anyone recommend me a script that will get this going?
Thanks.

Edited to correct output pin:
You could do this, adapted from: How to create a 38 Khz pulse with arduino using timer or PWM? - Programming Questions - Arduino Forum Post #12
Output on pin 10 for ATMEGA 2560.

const byte LED = 10;  // Timer 2 "A" output: OC2A

void setup() {
 pinMode (LED, OUTPUT);
 
 // set up Timer 2
 TCCR2A = _BV (COM2A0) | _BV(WGM21);  // CTC, toggle OC2A on Compare Match
 TCCR2B = _BV (CS20);   // No prescaler
 OCR2A =  40;           // http://eleccelerator.com/avr-timer-calculator/  200kHz
                           
} 

void loop() { }

I'm not getting anything on the output with that :frowning:

Oops. I'm just looking at a diagram which says OC2A is on pin D10 ( not D11 as previously posted).

Okay cool now it works. It's about 20khz off from 200khz though.

It's about 20khz off from 200khz though.

10% is a bit high for internal clock error. How calibrated is your measurement device?

You can adjust the OCR2A compare match value to get whatever frequency you want. 40*.0625 = 2.5 us so its nominally set for 200KHz. Try changing the value of 40 up or down to get want.

 OCR2A =  40;//change this value

The timer is in CTC mode so the formula for determining the value of the match value (OCR2A in this case) is:

OCR2A = 39; // CTC Mode: ( clock_frequency / ( prescaler * 2 * output_frequency)  )  - 1

which gives a value of 39, not 40 as in the original post.

for determining the original value, I used an online timer calculator which, although claiming to be an AVR calculator, did not point out that subtlety.

For a frequency of 200kHz, fast PWM mode may also be a useful option