const int dirPin = 2;
const int stepPin = 3;
const int buttonPin = 4; // Pin untuk push button
bool motorRunning = false;
bool buttonStateLast = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Gunakan INPUT_PULLUP untuk mengaktifkan resistor pull-up internal
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState != buttonStateLast) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (buttonState != digitalRead(buttonPin)) {
if (buttonState == LOW) {
toggleMotor();
}
}
}
buttonStateLast = buttonState;
}
void toggleMotor() {
if (!motorRunning) {
startMotor();
} else {
stopMotor();
}
}
void startMotor() {
motorRunning = true;
// Set arah motor searah jarum jam
digitalWrite(dirPin, HIGH);
// Putar motor sampai tombol ditekan kembali
while (digitalRead(buttonPin) == HIGH) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(2500);
digitalWrite(stepPin, LOW);
delayMicroseconds(2500);
}
motorRunning = false;
// Tunda sebentar sebelum menghentikan
delay(100);
}
void stopMotor() {
motorRunning = false;
// Hentikan motor dengan mengatur dirPin dan stepPin menjadi LOW
digitalWrite(dirPin, LOW);
digitalWrite(stepPin, LOW);
// Tunda untuk memastikan motor berhenti
delay(100);
// Reset posisi motor berlawanan arah jarum jam
digitalWrite(dirPin, HIGH);
// Tunda sebentar sebelum menghentikan
delay(100);
}