Stepper motor defining start position and limit switches

That's a fairly simple version of homing ( and it sets the reference point to the middle of your movement :wink: ). The limit switch must be positioned at the negative end.

// Bounce.ino
// -- mode: C++ --
//
// Make a single stepper bounce from one limit to another
//

#include <AccelStepper.h>

// Define a stepper and the pins it will use
// AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
AccelStepper stepper(1,7,6);

const byte limitPin = A2;   // input pin for limit switch, change to your needs
                            // Switch must connect to GND if stepper reaches the switch.
void setup()
{
// Change these to suit your stepper if you want
pinMode( limitPin, INPUT_PULLUP );
stepper.setMaxSpeed(100);       // slow speed for homing
stepper.setAcceleration(100);
// start homing procedure
stepper.moveTo( -2000 );                // should be max possible movement towards the limit switch
while( digitalRead( limitPin ) == HIGH ) stepper.run(); // move until limit switch is reached
stepper.setCurrentPosition( -1000 );    // set current position as negative limit
// start normal move
stepper.setMaxSpeed(1000);
stepper.setAcceleration(10);
stepper.moveTo(1000);
}

void loop()
{
// If at the end of travel go to the other end
if (stepper.distanceToGo() == 0)
stepper.moveTo(-stepper.currentPosition());

stepper.run();

}