The problem is that the turning on and off it occurs erratically such that it works fine for a while and then some errors and then works fine.
What do you mean by "turning on and off"? What is turned off?
Give examples of the errors, and describe the erratic behavior.
Please also post a complete wiring diagram and a photo of your setup. Motor electrical noise is a common cause of program malfunction.