Wait for signal after homing

I have a stepper sequence that starts with homing and then, after a defined time-delay, begins running between two positions. If any limit switch is triggered, it will re-run the homing sequence. Instead of the defined time-delay after homing, I want it to wait for an input signal/trigger to start the sequence.
This is the homing part.

//if the system has not been homed, home system and save the home position
        if(homeStatus == notHomed  || homeStatus == pressedDuringHome){
                if(homeStatus == notHomed){
                        debugln("Homing system, stay clear of machine");
                        digitalWrite(stepperEnablePin, LOW);//Enable the motor
                        
                        //run the stepper reverse until the rear limit switch is reached
                        stepper.moveTo(homeTravelDistance);
                        stepper.setMaxSpeed(stepperHomeSpeed);
                        while(homeStatus == notHomed){
                                stepper.run();
                        }
                        //set position as 0
                        stepper.setCurrentPosition(0);
                }
                if(homeStatus == pressedDuringHome){  
                        debugln("Rear limit hit during homing, backing off switch");
                        digitalWrite(stepperEnablePin, LOW);//Enable the motor
                        
                        //run the stepper reverse until the rear limit switch is reached
                        stepper.moveTo(-stepsToGetOffLimitSwitchDuringHoming);
                        debugln("susped");
                        stepper.runToPosition();
                        debugln("@");
                        debugln("done backing off limit, ready to enter run");
                        //set position as 0
                        stepper.setCurrentPosition(0);
                        homeStatus = homed;       
                }

        }

I found the sample code below for a photo-interrupter component. Would that work (where to add in current code?) or does anyone have better suggestions?

int Led = 13; // define LED pin
int buttonpin = 3; // define photo interrupter signal pin
int val; //define a numeric variable
void setup()
{
pinMode(Led, OUTPUT); // LED pin as output
pinMode(buttonpin, INPUT); //photo interrupter pin as input
}
void loop()
{
val=digitalRead(buttonpin); //read the value of the sensor
if(val == HIGH) // turn on LED when sensor is blocked
{
digitalWrite(Led,HIGH);
}
else
{
digitalWrite(Led,LOW);
}
}

Welcome to the forum

As your topic does not relate directly to the installation or operation of the IDE it has been moved to the Programming category of the forum

Please post your full sketch

Full sketch.

#include "Setup.h"

void setup() {
        customSetup(); //See the Setup.h tabe for this function
}


//--------------------(Main Code)---------------------------//
void loop() {

        //if the system has not been homed, home system and save the home position
        if(homeStatus == notHomed  || homeStatus == pressedDuringHome){
                if(homeStatus == notHomed){
                        debugln("Homing system, stay clear of machine");
                        digitalWrite(stepperEnablePin, LOW);//Enable the motor
                        
                        //run the stepper reverse until the rear limit switch is reached
                        stepper.moveTo(homeTravelDistance);
                        stepper.setMaxSpeed(stepperHomeSpeed);
                        while(homeStatus == notHomed){
                                stepper.run();
                        }
                        //set position as 0
                        stepper.setCurrentPosition(0);
                }
                if(homeStatus == pressedDuringHome){  
                        debugln("Rear limit hit during homing, backing off switch");
                        digitalWrite(stepperEnablePin, LOW);//Enable the motor
                        
                        //run the stepper reverse until the rear limit switch is reached
                        stepper.moveTo(-stepsToGetOffLimitSwitchDuringHoming);
                        debugln("susped");
                        stepper.runToPosition();
                        debugln("@");
                        debugln("done backing off limit, ready to enter run");
                        //set position as 0
                        stepper.setCurrentPosition(0);
                        homeStatus = homed;       
                }

        }

        //while homingStatus == homed, continiously run back-n-forth between the limits
        while(homeStatus == homed){
              
                //On the first run, write to the serial monitor so we know
                if(debugStatus != runSequence){
                       debugln("Entered run sequence for the first time");   
                       debugStatus = runSequence;
                }

                
                //set the stepper speed and acceleration to the forward settings
                stepper.moveTo(-runDistance);
                stepper.setMaxSpeed(stepperForwardRunSpeed);
                stepper.setAcceleration(stepperForwardRunAcceleration);
                  
                //run stepper until the runDistance has been traveled (UNLESS either limit is hit)
                delay(10000);
                while (stepper.distanceToGo() != 0 & homeStatus == homed){
                        stepper.run();
                }

                //this stops the motor as quickly as possible while using accel+decell (May take trial and error during setup to find a setting that doesnt hit the limit switch)
                stepper.stop(); // Stop as fast as possible: sets new target
                stepper.runToPosition(); 
               
                //Write to the serial monitor (see DEBUG.h tab)
                debugln("Forward movement complete, reversing");

                // Now, tell the stepper to reverse back to the home position
                delay(10000); //ADDED TO SOURCE CODE to hold at end position
                stepper.moveTo(0);
                stepper.setMaxSpeed(stepperRearRunSpeed);
                stepper.setAcceleration(stepperRearRunAcceleration);

                // Full speed basck to 0 (UNLESS either limit switch is hit)
                while (stepper.distanceToGo() != 0 & homeStatus == homed){ 
                        stepper.run();
                }
                               
                //this stops the motor as quickly as possible while using accel+decell
                stepper.stop(); // Stop as fast as possible: sets new target
                stepper.runToPosition();               

                //write to the serial monitor 
                debugln("Reverse movement complete, pausing for a second, then sending forward");

        }

        //if an error occurs, disable the motor and wait for operator to check/reset
        while(homeStatus == error){
              debugln("An error has occured, check machine and reset when ready");
              digitalWrite(12, HIGH);//disable the motor
              delay(10000);
        }
       
}

We can't do what the comment suggests

//These are the libraries used
#include "UserSettings.h"
#include <AccelStepper.h> //version 1.61

//This is the debugger setup. Notes on this are on the UserSettings.h tab
#if DEBUG == 1
        #define debug(x) Serial.print(x);
        #define debug_delay(x) delay(x);
        #define debugln(x) Serial.println(x)
#else
        #define debug(x)
        #define debug_delay(x)
        #define debugln(x)
#endif

//this assigns the pins to the accelStepper library
AccelStepper stepper(1, stepperPulsePin, stepperDIRPin); // Driver; PUL pin 6; DIR pin 9

//define the homing states and set to notHomed initially. Use the "error" as a kill status
const int notHomed = 0;
const int homed = 1;
const int error = 3;
const int pressedDuringHome = 4;
int homeStatus = notHomed;

//this is used so some of the debug readings dont run continiously
const int runSequence = 4;
int debugStatus = notHomed;

//--------------(Interrupt Functions)-----------------------//

//Interrupt function for the forward limit switch
void rearLimitHit (){

        //If 
        if(homeStatus != pressedDuringHome){    
                
                delay(20);//delay used as a debouce. To help reduce the chance of false readings 
                
                //Check again after the slight delay to see if the limit switch is still pressed
                if(digitalRead(rearLimitSwitchPin) == LOW){
                        //if it is homing and trigger the rear limit, set to homed
                        if(homeStatus == notHomed){
                                homeStatus = pressedDuringHome;
                                debugln("rear limit hit #2");
                        }
                        //if its already homed and triggers the rear limit, something is wrong, stop and require a reset.
                        if(homeStatus == homed){
                             digitalWrite(stepperEnablePin, HIGH);   
                             homeStatus = error;
                             debugln("rear limit hit #3");
                        }
                }
        }
  
}
//Interrupt function for the forward limit switch
void forwardLimitHit (){

        delay(20);//delay used as a debouce. To help reduce the chance of false readings 
        
        //Check again after the slight delay to see if the limit switch is still pressed
        if(digitalRead(forwardLimitSwitchPin) == LOW){
                    //this is set to "error" since this limit should never be hit. If it is, it will stop and require a reset of the Arduino. 
                    digitalWrite(stepperEnablePin, HIGH);
                    homeStatus = error;
                    debugln("forward limit hit");
        }
}
//------------------------(Setup )-----------------------------//
void customSetup() {
  
        //These turn on the serial monitor, prints to let the user know the device is running and that they need to turn on the debug feature to use it.
        Serial.begin(9600);
        Serial.println("");
        Serial.println("System ON, ensure you set DEBUG = 0 in the UserSettings.h tab to use the serail debug readouts");
        Serial.println("");
        
        delay(500);
        
        // Setup the limit switches as Input Pullups. 
        pinMode(forwardLimitSwitchPin, INPUT_PULLUP);
        pinMode(rearLimitSwitchPin, INPUT_PULLUP);
        
        // Attach interrupt pins to handlers (functions can be found on this page above)
        attachInterrupt(digitalPinToInterrupt(forwardLimitSwitchPin), forwardLimitHit, FALLING);
        attachInterrupt(digitalPinToInterrupt(rearLimitSwitchPin), rearLimitHit, FALLING);

        //AccelStepper setup stuff
        stepper.setEnablePin(stepperEnablePin); // assign which pin was used for the the Enable motor pin
        stepper.setPinsInverted(stepperDirectionSetting, false, driverEnableSignalRequirement); //Here I am telling the Accel Stepper Library that my motor's driver uses for it enable signal (high/low) and setting the direction
        //Set the max speed/acceleration
        stepper.setMaxSpeed(stepperMaxSpeed); // 60RPM = 1 rev/sec = microsteps setting/maxspeed
        stepper.setAcceleration(stepperHomeAcceleration); // (was 6400)1 rev to maxspeed = microsteps setting/2 = acceleration; 1 rev =microsteps setting/2 = moveto
        stepper.setSpeed(stepperHomeSpeed);
}



shouldn't homing just move one step at a time until the limit switch becoms active

void home ()
{
    while (HIGH == digitalRead (PinCcwLmtSw))  {
        stepper.move (1);
        stepper.run ();
    }
}

wouldn't it be at the home position in one case?

one approach is to have a master enable flag that is set when a button is pressed. That master enable can be reset, stopping operation if either limit switch becomes active

bool enable;

void loop ()
{
    if (LOW == digitalRead (PinStart))
        enable = true;

    if (enable)
        run ();
}

i don't see values for runDistance or homeTravelDistance. I would expect the home position to be zero, so i don't understand how stepper.moveTo(-runDistance); works.

why not simply check for either of 2 end points?

const unsigned long EndPtA = 10;
const unsigned long EndPtB = 220;

void run ()
{
    if (EndPtA >= stepper.currentPostion ())
        stepper.moveTo (EndPtB)
    else if (EndPtB <= stepper.currentPostion ())
        stepper.moveTo (EndPtA)

    stepper.run ();
}

Hi, @fugander
Welcome to the forum.

Can you tell us what your project is for?
What is its scope?
What does the stepper move?

Thanks.. Tom.... :smiley: :+1: :coffee: :australia:

Thanks all for the response. I'm really a newbee on this, but the sketch works fine as is (found a sample code on Youtube...). It is used for a camera rig to move the camera in an arch over an object for product photography. The current sketch starts by reversing the rig until the rear limit switch is triggered. It moves avay from the limit switch to set the zero position. After a time-delay i starts moving a defined number of steps, stops, and moves back to the zero position. It continues util I hit either of the limit switches (rear/front), then re-runs the homing, and so on. Now I want to make it hold at the zero position, first time after homing, until a start switch is triggered (no time-delay used in this case). The purpose of the switch is to be able to synchronize the start of the sequence with other actions.
Here is the User settings that are used by the sketch.

/* Notes: 
 *  1. To turn on the serial monitor readouts/debugger, set the "DEBUG" value to 1.
 *  2. It is best to turn off the debugger when not using it. Since the motor will run smoother without it on. 
 *  3. Make sure test the code without the linear rail coupling attached to ensure your directions, speeds, and switches all work prior to running with the lead screw attached. 
 *  
 *  This code is not intended for industrial or commercial use and purely for personal use. 
 *  User accepts all liability.
 *  
 *  Parts used for origional setkup: 
 *  1. Linear rail: https://www.amazon.com/gp/product/B0784G53D4/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
 *  2. Stepper driver: https://www.amazon.com/gp/product/B06Y5VPSFN/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
 *  3. Limit switches: https://www.amazon.com/gp/product/B073SP7SXS/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
 *  4. Arduino UNO: https://www.amazon.com/gp/product/B016D5KOOC/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
 *  5. 24V Power Supply: https://www.amazon.com/gp/product/B0196PXMTU/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
 *  
 */

//Serial Debugger:
        #define DEBUG 0 // This turns the serial debug feature ON/OFF. 0 = OFF, 1 = ON. Essentially makes it easier to debug issues. Turning off can sometimes speed up processing, but should have much effect on yours, so Id leave on. 

//Driver Settings and Limit Switch Pins
        
        // Define which pins you use for the limit switches
        // Inportant: The code only works if the limit switches are connected to Interrupt pins. On the Uno/Nano, pins 2 & 3 are the pins to use.
        #define forwardLimitSwitchPin 2
        #define rearLimitSwitchPin    3
        
        //Define which pins you used to wire your stepper motor driver to the Arduino.
        #define stepperDIRPin    7
        #define stepperPulsePin  8
        #define stepperEnablePin 9
        
        bool driverEnableSignalRequirement = true;  //If your stepper motor is enabled pin requires a HIGH signal, change this to false. 
        bool stepperDirectionSetting       = false; //If your stepper heads in opposite direction than expected, you can change this value to reverse its directions without editing the main code. 
                                                    //The two options are "true" and "false" try each and see which works best for you. 

//MAIN DISTANCE SETTINGS

        float stepsToGetOffLimitSwitchDuringHoming = 1000;    //This is used to back off of the rear limit during homing. Test real world and adjust to the offset that you want. CHANGED FROM 600
        float homeTravelDistance = 30000;                    //This sets a high number for homing the device. If the homing sequence doesnt reach the rear limit switch, increase this number.
        float runDistance = 34500;                          //This set the length of the run so we dont have to use the limit switches (and they can be used as stops). Test this and adjust until the desired travel distance is reached.
        
//MAIN SPEED SETTINGS
        
        float stepperHomeSpeed = 300;                       //Homing speed. Higher # = faster homing CHANGED FROM 2000
        float stepperHomeAcceleration = 50;                //Home Acceleration CHANGED FROM 1000
        
        float stepperForwardRunSpeed = 800;                 //This sets the speed at which the stepper will push the weight at. larger# = faster CHANGED FROM 1000
        float stepperForwardRunAcceleration = 50;          //Sets the acceleration for the forward movement (pushing the weights) larger = faster CHANGED FROM 2000
        
        float stepperRearRunSpeed = 800;                    //This sets the speed at which the stepper will return the sled to the home position at. CHANGED FROM 8000
        float stepperRearRunAcceleration = 50;             //Sets the acceleration for the rear movement back to home position. larger = faster CHANGED FROM 5000

//SECONDARY SETTINGS (NOT LIKELY TO BE CHANGE)
        
        float stepperMaxSpeed = 10000;                       //This is for future use. Not super useful now. But if you ever set your speed higher than this, adjust this to match.