sine wave generator

then what could be the best way to do?

Get hold of an oscilloscope or a frequency counter, and tweak your loop times until you get closest to 40kHz.

and amplifier for the square wave?

MAX232 or similar.