We don't know yet and possibly won't ever know for sure. One theory that I find plausible:
- Parts of the military were unhappy with Erdogan, for various reasons: the political splits 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 (can't find the relevant tweets now), the government was criticised for not honouring the "sacrifices" they bring on (unofficial) social media accounts associated with army units. So some tension between army and AKP government was there, though traditionally the Kemalist army had a strong anti-kurdish stance.
This theory is found more or less in the Süddeutsche Zeitung.
This excellent article in Jacobinmag also supports the theory, apparently Erdogan planned to purge the army of anti-AKP elements this July and the coup was a last ditch attempt to prevent this.