Please help. Below is code to oscillate stepper around centre position. Entire code is working fine except one condition. Given below
void Arm() {
Data_recieve(a, n);
unsigned long now = millis();
if (now - lastRecvTime > TIMEOUT_DURATION) {
Serial.println("Signal lost");
resetData(); // Signal lost, Reset
}
AC = A[5];
ang = A[2];
arm_sp = A[4];
stepper.setCurrentPosition(0);
int originalPosition;
ang = map(ang, 0, 1023, Min_Angle, Max_Angle);
arm_sp = map(arm_sp, 0, 1023, Min_Arm_Sp, Max_Arm_Sp);
stepper.setMaxSpeed(arm_sp);
stepper.setSpeed(arm_sp);
stepper.setAcceleration(20000);
ang = ang * 30;
switch (state) {
case IDLE:
if (AC == 1) {
stepper.stop();
state = IDLE;
}
if (AC == 0) {
digitalWrite(Relay_Blast, HIGH);
stepper.setCurrentPosition(0);
state = Step1;
}
break;
case Step1:
{
originalPosition = stepper.currentPosition(); // Store original position when entering Step1
// Serial.println("Original Position: " + String(originalPosition));
state = Step3;
}
break;
case Step3:
{
int targetPosition1 = originalPosition + ang;
int targetPosition2 = originalPosition - ang;
while (AC == 0) {
Serial.println("Moving to Target Position1 in Step3: " + String(targetPosition1));
stepper.moveTo(originalPosition + ang);
stepper.runToPosition();
delay(100);
Data_recieve(a, n);
AC = A[5];
ang = A[2];
arm_sp = A[4];
ang = map(ang, 0, 1023, Min_Angle, Max_Angle);
arm_sp = map(arm_sp, 0, 1023, Min_Arm_Sp, Max_Arm_Sp);
stepper.setMaxSpeed(arm_sp);
stepper.setSpeed(arm_sp);
stepper.setAcceleration(20000);
ang = ang * 30;
Serial.println("Moving to Target Position 0 in Step3: " + String(originalPosition));
stepper.moveTo(0);
stepper.runToPosition();
// delay(100);
Data_recieve(a, n);
AC = A[5];
ang = A[2];
arm_sp = A[4];
ang = map(ang, 0, 1023, Min_Angle, Max_Angle);
arm_sp = map(arm_sp, 0, 1023, Min_Arm_Sp, Max_Arm_Sp);
stepper.setSpeed(arm_sp);
ang = ang * 30;
// Check if we need to move to Step4
if (AC == 1) {
state = IDLE;
Serial.println("Skipping Step4 - Going IDLE");
break;
}
Serial.println("Moving to Target Position2 in Step3: " + String(targetPosition2));
stepper.moveTo(originalPosition - ang);
stepper.runToPosition();
Data_recieve(a, n);
delay(100);
AC = A[5];
Serial.println(AC);
// Check if we need to move to Step4
if (AC == 1) {
Serial.println("Moving To Step4 --- 2");
state = Step4;
break;
}
}
state = Step1; // Move back to Step1 after the loop
}
break;
case Step4:
{
// Move to center (zero) position
Serial.println("Moving to Center Position in Step4: 0");
stepper.moveTo(0);
stepper.runToPosition();
// while (stepper.distanceToGo() != 0) {
// stepper.run();
// delay(10); // Add a small delay to avoid high CPU usage
// }
// // Stop the stepper
// stepper.stop();
// Set state back to IDLE
state = IDLE;
Serial.println("Step 4 - Going to IDLE");
}
break;
}
}