Code not work until Opening Serial Monitor

Hi everyone,

I try to control stepper motor with distance sensor HC SR04. I have uploaded my code.

The sensor will record the initial position of an object, then if the position is less than the target position, motor will turn clockwise, if the position is more than the target position, motor will turn counterclockwise until the object reaches its target.

My motor stalls right at the beginning, yet works perfectly well as soon as I open the serial monitor, regardless if I have the line serial.print or not.

I heard of something like the arduino auto-reset with serial monitor on. So how do I fix this problem?

Thanks for any insightful input.

sketch_feb21b.ino (1.55 KB)

Please learn how to post your sketch with your post as code and not as an attachment.