Never mind folks, I took a different approach and it works fine.
One PIR sensor, one Hall effect sensor and 1 magnet.
At power up, I home steppers using the Hall effect sensor. Then, since I have fixed stop points, I put them in an array. Then generate a random number, which points to the position in the array, and move there every time PIR sensor is triggered.
Thanks all for your help.
I'm posting my code, it might help someone.
const int stepX = 2; // X.STEP
const int dirX = 5;
const int stepZ = 4; // Z.STEP
const int dirZ = 7 ;
const int MoveSens = 9; // HC-SR 501 Movement Sensor (Pin X+)
const int STopSens = 11; // Hall sensore stop (Pin Z+)
int CurrPos;
int NewPos;
void setup() {
Serial.begin(115200);
pinMode(MoveSens, INPUT);
pinMode(STopSens, INPUT);
pinMode(stepX, OUTPUT);
pinMode(dirX, OUTPUT);
pinMode(stepZ, OUTPUT);
pinMode(dirZ, OUTPUT);
Home(); // Home Stepper X and Y
delay(5000);
}
void loop() {
int MoveSensVal = digitalRead(9); // value for HC-SR 501 Movement Sensor
if (MoveSensVal == HIGH) {
NewPos = Generate_Random_Position();
if (NewPos != CurrPos) {
Serial.println("New Position = " + String(NewPos));
GoToTarget(NewPos);
}
}
}
void Home() {
digitalWrite (dirX, LOW); // Turn CW
digitalWrite (dirZ, LOW);
for (int n = 1; n < 2000; n++) {
int StopSensVal = digitalRead(11); // Value for Hall Effect sensor STOP
if (StopSensVal == HIGH) {
for (int x = 0; x < 1; x++) {
digitalWrite(stepX, HIGH);
digitalWrite(stepZ, HIGH);
delay(10);
digitalWrite(stepX, LOW);
digitalWrite(stepZ, LOW);
}
}
}
CurrPos = 0;
Serial.println("Home Position = " + String(CurrPos));
}
int Generate_Random_Position() {
int RandNum;
int TargetPos;
int Positions[] = {0, 150, 230, 350, 400, 800, 900, 950};
randomSeed(analogRead(0)); // generate a random number
RandNum = random(0, 8);
delay(50);
TargetPos = (Positions[RandNum]);
Serial.println("Random Number = " + String(RandNum));
return TargetPos;
}
void GoToTarget(int T) {
Serial.println("Moving to Position .... " );
if (CurrPos > T) {
digitalWrite (dirX, HIGH); // Turn CCW
digitalWrite (dirZ, HIGH);
}
else {
digitalWrite (dirX, LOW); // Turn CW
digitalWrite (dirZ, LOW);
}
for (int x = 0; x < T + 1; x++) {
digitalWrite(stepX, HIGH);
digitalWrite(stepZ, HIGH);
delay(10);
digitalWrite(stepX, LOW);
digitalWrite(stepZ, LOW);
}
CurrPos = T;
Serial.println("Moved to Position = " + String(CurrPos));
delay(10000);
}