Generating 40kHz square wave

You need a pwm mode that allows you to set the top.

Was the any more to your post, dhenry?