Without analyzing the complete code, the steps to go are:
- Remove the
delayfunction calls. These mostly delay the program in such a way that other parts are not executed in time or 'at the same time'. - Instead use the
millicommandmilliscommand and check again time stamps (ofunsigned long inttype) to reach the delays you need. - Create a state machine. This means in simple form that you use an enumeration (
enumtype) which can have one out of a set of values (like Stopped, Accelerating, Decelerating), for each 'states' you can define in your sketch. - Use these state machines and times to move from one state to another, and while changing state (or during a state) you can perform the actions you need.