Hello,
I am currently using two limit switches (https://www.amazon.com/Lysee-Printer-Parts-Accessories-Mechanical/dp/B092TLSZC1/ref=sr_1_5?dchild=1&qid=1626198847&refinements=p_n_feature_two_browse-bin%3A9648512011&s=industrial&sr=1-5) to limit the motion of a stepper motor along a linear driver. I am using a cnc and arduino uno with the limit switches connect to x+ and x- of the end stop pins
#include <AccelStepper.h>
//Pins
const byte limitSwitch1 = 9;
const byte analogX_pin = A1;
AccelStepper stepperX(1,2,5);
//variables
int analogX = 0; //x-axis valueint
int analogX_AVG = 0; //x-axis average value (middle)
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(analogX_pin,INPUT);
pinMode(limitSwitch1,INPUT);
InitialValues(); //calculating the middle/average value for three analog pins
//stepper parameters
stepperX.setMaxSpeed(5000);
stepperX.setAcceleration(1000);
stepperX.setSpeed(500);
delay(500);
}
void loop() {
readAnalog();
stepperX.runSpeed();
}
void readAnalog() {
//reading from joystick position
analogX = analogRead(analogX_pin);
//if value is at least 25 away from the average value with allow the update of speed and moving to pointed direction
if(abs(analogX - analogX_AVG)>25) {
//if limit switch is clicked, do not run the motor
if (digitalRead(limitSwitch1) == LOW) {
stepperX.setSpeed(0);
Serial.println("switch is clicked");
} else {
stepperX.setSpeed(5*(analogX - analogX_AVG));
Serial.println("switch is not clicked");
}
}
else { //the analog value is less than 25 so do not run the motor yet
stepperX.setSpeed(0);
}
}
void InitialValues() {
float tempX = 0; //set temporary x value to 0
//read the analog value initial 50 times and get the average to have accurate middle value
for (int i=0;i<50;i++) {
tempX += analogRead(analogX_pin);
}
analogX_AVG = tempX/50;
}
Everything seems wired correctly and by printing simple messages (switch is clicked/switch is not clicked), it seems that the code is working. When I am using the joystick and clicking the switch the correct message is printed. Nevertheless, the motor actually doesn't rotate and move. It makes a weird sounds but holds still. Would you know possible reasons for this?
I have tried controlling the motor just with joystick and no limit switch and works perfectly so the issue arises when I add the limit switches!
Thanks!