Someone has posted something very similar before with the same proximity limit switch but i am still confused in regards to it in my context.
I am using a 10-30V, PNP, NC proximity switch /limit switch a with linear actuator and Arduino Nano. The objective is that the motor first moves backwards util the extreme limit is reached, afterwards it goes through the main void loop to move three more times twice in forwards and once backwards.
The sensors' works fine, so when the object is in its proximity the LED on it turns off and turns on when it is away. However, the output (in form of 0 and 1) I am getting is quite random and not according to the sensors' LED.
The value I am expecting is Low/High when LED is on and opposite is when it is off. However, I am not getting this. I am about 6 months into Arduino and very stuck.
Any help would be amazing because im out of options atm ![]()
Below is my code and my current wiring:
Schematic:
Code:
const int stepPin = 31;
const int dirPin = 33;
const int enPin = 35;
const int limitSwitchPin = 25; // Pin connected to the limit switch
bool homingCompleted = false; // Flag to indicate whether homing is completed
void setup() {
// Motor setup
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
digitalWrite(enPin, LOW);
// Limit switch setup
pinMode(limitSwitchPin, INPUT); // Set limit switch pin as input withOUT pull-up resistor
// Move the actuator to origin during setup
moveStepperToOrigin(LOW, limitSwitchPin);
}
void moveStepper(int direction, int steps, int delayMicros) {
digitalWrite(dirPin, direction);
for (int x = 0; x < steps; x++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(delayMicros);
digitalWrite(stepPin, LOW);
delayMicroseconds(delayMicros);
}
}
void moveStepperToOrigin(int direction, int limitSwitchPin) {
digitalWrite(dirPin, direction); // Move in reverse direction
while (digitalRead(limitSwitchPin) == LOW) { // Keep moving until limit switch is pressed (set to LOW as nature of NC switch)
digitalWrite(stepPin, HIGH);
delayMicroseconds(15); // Adjust this delay as needed
digitalWrite(stepPin, LOW);
delayMicroseconds(15); // Adjust this delay as needed
}
homingCompleted = true; // Set the homing completed flag
}
void loop() {
if (homingCompleted) {
// Movement stages
// Movement 1
moveStepper(HIGH, 15000, 15);
delay(1000); // Pause between movements
// Movement 2
moveStepper(HIGH, 5000, 50);
delay(1000); // Pause between movements
// Movement 3
moveStepper(LOW, 20000, 15);
delay(2000); // Pause between movements (adjust as needed)
homingCompleted = false; // Reset the homing completed flag to stop loop execution
}
}


