Arduino motor control with proximity sensor need help

Debouncing is always possible. But I think his code is fundamentally lacking something: state-memory based on the object itself.

He is actuating his motor directly based on sensor state. Once the proximity detector triggers the motor stops. Then wait, and turn the motor on again for the object to get out of view. Since detection happens in a split second, and mechanical acceleration of the motor takes time this is a blocking condition.As soon as the waiting period is over it energizes the motor pin, but in the next loop it thinks it detects an object again so stops it before it turned even one bit. And the sensor never changed it’s output level during that.

If you implement a state-memory based on the process through which the object is handled then you can differentiate between the arriving state( motor is on, once proximity sensor fires transition to waiting-state), the waiting-state (motor is stopped, do nothing until time is passed then transition to leaving-state) and the leaving-state(motor is engaged, once proximity sensor is cleared transition to arriving-state). The leaving state transitions to arriving state as soon as the proximity sensor is cleared by the object, but never stops the motor during both states. The transitions are based on external (proximity sensor) or internal (clock-time) influences. But until those change in a particular order, there is no transition to the next state. So the motor get’s the time to move the object out of the proximity location, and bring the next one in place.

The waiting-state could be implemented with a simple delay() function to make it simple to begin with. Later you can improve it with millis() to make it non-blocking during those seconds.