// Definisikan pin untuk motor 1 dan motor 2
const int stepPin1 = 23; // STEP motor 1
const int dirPin1 = 22; // DIR motor 1
const int stepPin2 = 21; // STEP motor 2
const int dirPin2 = 19; // DIR motor 2
// Tombol
const int buttonPin1 = 16; // Tombol 1
const int buttonPin2 = 17; // Tombol 2
// Status tombol
bool motor1Direction = true; // true = ke kanan, false = ke kiri
bool motor2Direction = true; // true = ke kanan, false = ke kiri
unsigned long lastDebounceTime1 = 0; // Waktu debounce tombol 1
unsigned long lastDebounceTime2 = 0; // Waktu debounce tombol 2
const unsigned long debounceDelay = 50; // Delay debounce (ms)
int lastButtonState1 = LOW;
int lastButtonState2 = LOW;
void setup() {
// Setel pin untuk motor 1 dan 2
pinMode(stepPin1, OUTPUT);
pinMode(dirPin1, OUTPUT);
pinMode(stepPin2, OUTPUT);
pinMode(dirPin2, OUTPUT);
// Setel pin tombol sebagai input pull-up
pinMode(buttonPin1, INPUT_PULLUP);
pinMode(buttonPin2, INPUT_PULLUP);
// Setel arah motor awal
digitalWrite(dirPin1, motor1Direction);
digitalWrite(dirPin2, motor2Direction);
}
void loop() {
// Cek tombol 1
checkButton(buttonPin1, stepPin1, dirPin1, motor1Direction, lastButtonState1, lastDebounceTime1);
// Cek tombol 2
checkButton(buttonPin2, stepPin2, dirPin2, motor2Direction, lastButtonState2, lastDebounceTime2);
}
// Fungsi untuk memeriksa tombol dan menggerakkan motor
void checkButton(int buttonPin, int stepPin, int dirPin, bool &direction, int &lastButtonState, unsigned long &lastDebounceTime) {
int reading = digitalRead(buttonPin);
// Jika status tombol berubah
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
// Jika debounce selesai
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading == LOW) { // LOW karena tombol menggunakan INPUT_PULLUP
digitalWrite(dirPin, direction); // Atur arah motor
for (int i = 0; i < 20; i++) { // Putar motor sebanyak 20 langkah
digitalWrite(stepPin, HIGH);
delayMicroseconds(1000); // Atur kecepatan
digitalWrite(stepPin, LOW);
delayMicroseconds(1000);
}
direction = !direction; // Balik arah motor untuk langkah berikutnya
}
}
// Simpan status tombol terakhir
lastButtonState = reading;
}