Generating 40kHz square wave

You need to carefully read Nick Gammon's web site, I'd suggest starting here:

Nick Gammon's description of Timers and Counters