We don't know yet and possibly won't ever know for sure. One theory that I find plausible:  

* Parts of the military where unhappy with Erdogan, for various reasons: the political splist between the (tradionally Kemalist) military and the (sorta-islamist) AKP. The most current reason would be the war against the Kurds Turkey is waging right now, where the military suffers some losses. 
* Because of this tension, Erdogan wanted to purge the military of disloyal higher officers.

* Some of these officers wanted to preempt this purge by staging a coup

* the Government learned of the planned coup, so the generals started it premature and ill planned. 

This would explain why, not 24h after the coup has started, the government has lists of thousands of soldiers, judges and others to remove from office or detain.

Official turkish propaganda glossed over or played down the losses suffered by the army in the civil war against the Kurds. According to Germany-based journalist (and expert on Turkey) [Ismail Küpeli][1] (can't find the relevant tweets now), the government was criticised for not honouring the "sacrifices" they bring on (inofficial) social media accounts associated with army units. So some tension between army and AKP government was there, though tradionatlly the Kemalist army had a strong anti-kurdish stance.


This theory is found [more or less in the Süddeutsche Zeitung][2].


  [1]: https://twitter.com/ismail_kupeli
  [2]: http://www.sueddeutsche.de/politik/akn-oeztuerk-der-kopf-der-verschwoerer-1.3082069