Stepper motor problem with external interrupt

Hi everyone.

I am new to Arduino and this is my first post. I hope I am at the right place.

I am trying to use Arduino Mega 2560, RAMPS 1.4 and A4988 to control 3 bipolar stepper motors (NEMA 17). Like feeding g-code to a 3D printer, I can send G1 command (G1 F1000 X20.0 Y20.00 Z10.00) to the arduino through the serial monitor to make the motor running. TIMER 1, TIMER 3 and TIMER 4 are used to send pulses to motor x ,y and z respectively.

But here I have encountered a problem when I played with a limit switch. I wished to do the Homing(as a 3D printer does) which commands the motor to spin clockwise until a limit switch is pressed, the motor will then run in anti-clockwise direction for a short amount of distance and then again spin clockwise until the limit switch is pressed again. But the motor would stop abruptly once the limit switch was pressed for the first time.

After some trial and error, I found that the Homing process somehow went smoothly if the line in motor_control_xy.cpp

(Czo > 0)? TIMSK4 |= (1 << OCIE4A) : TIMSK4 = 0;    //turn on CTC interrupt if Czo > 0

is replaced with

TIMSK4 |= (1 << OCIE4A);

I cannot understand this and I would like to ask if there are any differences between TIMER 1 and TIMER 4.
Any suggestions and comments will be very much appreciated. Thank you in advance.

main_1.zip (7.74 KB)