Using limit switches on a ball screw system

Hello,

I am wondering how the logic works for a screw system with two limit switches, one on either end.
One is the home switch and one is the end switch. I have the homing logic in setup to ensure the bearing is always at the home position at the startup.

I want the motor to drive the bearing forward until the end is reached, delay 5 seconds in that position, and then drive back until the home switch is activated. repeat.

The limit switches are operating as N.O. contacts and my drive forward/drive backward functions do operate correctly.

My current code can be seen below:

void loop() {

 while (digitalRead(EndSwitch))   //Do this until end switch is activated 
  {
    DriveForward();
  }

 delay(5000);                     //Deleay 5 seconds after end limit is reached 

 while (digitalRead(HomeSwitch))  //Do this until the home switch is activated 
 {
   DriveBackward();
 }
 
 
}

Am I correct in how this is to operate? or should I be using a different loop function than while loops?

I will be more than happy to answer any other questions about the program or hardware.

Thanks in advance.

At this time, the code is of no use. You need to show schematic of how the switches are actually wired. Then the code might be correct or in error.

Paul

Confused, what is your while statement checking?

Usually I would expect something more like..
while ( digitalRead(EndSwitch) == 0 )

Slumpert:
Usually I would expect something more like..
while ( digitalRead(EndSwitch) == 0 )

while (digitalRead(EndSwitch)) // is shorthand for
while (digitalRead(EndSwitch == HIGH))

Switches eventually fail, not making proper contact. So it's usually safer to use endswitches normally closed.
Connect the switch between pin and ground, and use internal pull up on the pin with pinMode.
pinMode(EndSwitch, INPUT_PULLUP);
then you can use
while (!digitalRead(EndSwitch)) DriveForward(); // while switch is closed
Leo..

Smagby:
Am I correct in how this is to operate? or should I be using a different loop function than while loops?

I prefer to use IF rather than WHILE and allow loop() to do the iteration.

A WHILE loop() blocks until it completes which prevents the Arduino from doing other things that might be useful - like checking if the operator wants to stop the process part way through.

...R

Slumpert:
Confused, what is your while statement checking?

Usually I would expect something more like..
while ( digitalRead(EndSwitch) == 0 )

Disagree, while (digitalRead(pin)) makes sense to me, digitalRead returns a
boolean, while needs a boolean.

It is often, however, clearer to write digitalRead (pin) == state to document exactly
what voltage state is expected (particularly if active-low logic is being used.

The best way to be clear is to use a macro or function to name the signal state directly:

 while (! limit_switch_active())

http://www.thebox.myzen.co.uk/Tutorial/State_Machine.html