// accel without library
byte dirPin = 2;
byte stepPin = 3;
byte limitPin = 4;
byte startPin = 5;
bool stepState = LOW; // start pulse
bool currentButtonState; // current button state (pressed/not pressed)
bool lastButtonRead; // previous button reading
unsigned long previousMillis = 0; // store last step
unsigned long interval = 2; // (milliseconds) half-interval for stepping
unsigned long debounceTimeout = 50; // debounceTimeout
unsigned long timer = 0; // measures button press time
void setup() {
Serial.begin(9600);
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(limitPin, INPUT_PULLUP);
pinMode(startPin, INPUT_PULLUP);
digitalWrite(dirPin, HIGH); // HIGH = CW
Serial.print("Press START.");
while (digitalRead(startPin)); // wait for START button press
Serial.println(" Started. Press LIMIT.");
delay(200); // debounce
}
void loop() {
checkTime();
readButton();
}
void readButton() {
bool currentButtonRead = digitalRead(limitPin); // read button pin
if (currentButtonRead != lastButtonRead) { // if button pin reading changes...
timer = millis(); // ...start a timer
lastButtonRead = currentButtonRead; // ... and store current state
}
if ((millis() - timer) > debounceTimeout) { // if button read change was longer than debounceTimeout
if (currentButtonState == HIGH && lastButtonRead == LOW) { // ... and State NOT pressed while Button PRESSED
changeMotorDirection(dirPin); // call function after button is pressed and released
}
currentButtonState = currentButtonRead; // change the state
}
}
void changeMotorDirection(byte dirPin) {
digitalWrite(dirPin, !digitalRead(dirPin));
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
if (digitalRead(dirPin))
Serial.print("CW ");
else
Serial.print("CC ");
}
void checkTime() { // for the stepper motor
if (millis() - previousMillis >= interval) { // compare time to interval
previousMillis = millis(); // store last step time
// squarewave(); // HIGH for interval, LOW for interval
singlepulse(); // HIGH/LOW pulse then wait for next interval
}
}
void squarewave() { // toggle the state
stepState = !stepState;
delayMicroseconds(500); // let the motor arrive at the next step
digitalWrite(stepPin, stepState); // step the motor
}
void singlepulse() { // minimum requirement to step a stepper
digitalWrite(stepPin, HIGH);
delayMicroseconds(500); // let the motor arrive at the next step
digitalWrite(stepPin, LOW);
}
START
LIMIT