Change stepper motor direction at end limit

Hi,

I have a stepper motor that moves a trolley on rails over a distance of 300 mm. The steps from the start position is fixed, but if the motor is knocked or slips, then it won’t know its position. Therefore, is there a way I include stopper sensors (such as an IR beam break) that once the sensor value changes, the motor direction will change? Any help with the code on this? Any other ideas?

Thanks in advance

burt46:
is there a way I include stopper sensors (such as an IR beam break) that once the sensor value changes, the motor direction will change?

Reasonable.

burt46:
Any help with the code on this? Any other ideas?

What's the hold-up?
If not for "sensors", could you manage to rig up a pair of switches (pushbuttons) for equivalent function?

I'm doing something similar, and I will likely just use two microswitches, one at each end.

dir = !dir is enough to turn it around.