Frankly, I've not looked through your code, but asking questions to see if you've eliminated those cases.

1. Disconnect the motor for tests. Use a LED instead
2. Check on the power supply decoupling. Not enough??
3. Back EMF protection. Since you seem to be using this, is the value within the supply rails?? Usually, a freewheeling diode is used to suppress back emf.