const int stepPin = 11;
const int dirPin = 10;
const int enPin = 12;
const int forwardBtnPin = 3; // Forward button pin
const int stepsSegment = 100; // Segment size (100 steps per segment)
const int totalStepsLimit = 500; // Total steps before returning to step 0
int stepCounter = 0; // Counter for total steps
int counter = 0; // Conveyor Move counter
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(enPin, OUTPUT);
pinMode(forwardBtnPin, INPUT_PULLUP); // Button with pull-up resistor
digitalWrite(enPin, LOW); // Enable the driver (assuming active low)
Serial.begin(9600); // Initialize serial communication
}
void loop() {
bool forwardBtnState = digitalRead(forwardBtnPin) == LOW; // Button pressed (LOW)
if (forwardBtnState) {
// Move motor forward
digitalWrite(dirPin, HIGH); // Set direction to forward
moveMotor(stepsSegment); // Move motor in segments of 100 steps
stepCounter += stepsSegment; // Update step counter
counter++;
Serial.print("TotalSteps:");
Serial.print(stepCounter);
Serial.print(" MoveCounter:");
Serial.println(counter);
// Check if total steps have reached the limit
if (stepCounter >= totalStepsLimit) {
// Move motor backward to reset position
Serial.println("Total steps limit reached. Returning to step 0.");
digitalWrite(dirPin, LOW); // Set direction to reverse
moveMotor(totalStepsLimit); // Move back the total steps
stepCounter = 0; // Reset the step counter to 0
Serial.println("Returned to step 0.");
}
// Wait until the button is released to avoid multiple triggers
while (digitalRead(forwardBtnPin) == LOW) {
delay(10); // Small delay to avoid busy-waiting
}
delay(1000); // One second delay to separate button presses
}
}
// Function to move motor in specified segment size
void moveMotor(int steps) {
for (int x = 0; x < steps; x++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
}
}