Unlike in most countries, the Turkish military operates independently of its president. The ongoing coup has likely been triggered by Erdogan’s increasing push towards an Islamic state. The modern Turkish military was set up in part to prevent this- to keep Turkish as a secular state.
Erdogan knew this, so he replaced as much of the military leadership with allies as he could, though obviously not enough. However, it is still too early to tell whether or not this coup will succeed. Regardless, this is a very interesting modern day lesson on armed resistance against tyranny and how it can be difficult to know who the good guys are once guns are substituted for ballots.
Read more interesting details about the coup and its role in Turkey’s form of democracy at reddit.