// ================= PIN DEFINITIONS =================
#define STEP_PIN 25
#define DIR_PIN 26
#define EN_PIN 27
#define TOP_LIMIT 32
#define BOTTOM_LIMIT 33
// ================= BIN SETTINGS =================
const int stepsPerBin = 800; // Adjust based on belt & pulley
int currentBin = 0;
int targetBin = 0;
// ================= SETUP =================
void setup() {
Serial.begin(115200);
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
pinMode(EN_PIN, OUTPUT);
pinMode(TOP_LIMIT, INPUT_PULLUP);
pinMode(BOTTOM_LIMIT, INPUT_PULLUP);
digitalWrite(EN_PIN, LOW); // Enable A4988 (LOW = enabled)
homing();
}
// ================= LOOP =================
void loop() {
if (Serial.available()) {
targetBin = Serial.parseInt();
moveToBin(targetBin);
}
}
// ================= FUNCTIONS =================
void stepMotor(int steps, bool direction) {
digitalWrite(DIR_PIN, direction);
for (int i = 0; i < steps; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(800);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(800);
}
}
void homing() {
Serial.println("Homing started...");
digitalWrite(DIR_PIN, LOW); // Move down
while (digitalRead(BOTTOM_LIMIT) == HIGH) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(900);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(900);
}
currentBin = 0;
Serial.println("Homing complete");
}
void moveToBin(int bin) {
if (bin < 0 || bin > 10) {
Serial.println("Invalid bin number");
return;
}
int diff = bin - currentBin;
int steps = abs(diff) * stepsPerBin;
if (diff > 0) {
stepMotor(steps, HIGH); // Up
} else if (diff < 0) {
stepMotor(steps, LOW); // Down
}
currentBin = bin;
Serial.print("Reached Bin: ");
Serial.println(currentBin);
}