Generating 40kHz square wave

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