Advertisement
skizziks_53

mega_stepper_button_01

Feb 15th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.32 KB | None | 0 0
  1. /*
  2.    15 February 2018
  3.    This is a test sketch to operate a reversible stepper motor on an Arduino Mega.
  4.    The stepper motor spins all the time, but pressing the button reverses the motor for 1 rotation cycle.
  5.  
  6.    This sketch uses a 'normal' software button debounce,
  7.    where the debounce time is tracked separately and resets itself no matter what else is happening.
  8. */
  9.  
  10. #include <Stepper.h>
  11.  
  12. const int stepsPerRevolution = 128;
  13. const int inPin = 52;
  14. int val = 0;
  15. Stepper myStepper(stepsPerRevolution, 3, 5, 4, 6);
  16. int stepperDirection = 0; // This is used to hold a modified value of stepsPerRevolution (either positive or negative) without changing the original value.
  17.  
  18. // Below is variables for debouncing the button input.
  19. bool button_enabled = true;
  20. int button_debounce_time = 500; // This is the time in milliseconds for the button to de-bounce (half a second).
  21. unsigned long buttonPress_beginTime = 0;
  22. unsigned long buttonPress_currentTime = 0;
  23.  
  24. void setup() {
  25.   myStepper.setSpeed(120);
  26.   pinMode(inPin, INPUT);
  27.   // This sketch uses pin 13 to indicate if the button input is enabled or not.
  28.   pinMode(13, OUTPUT);
  29.   digitalWrite(13, HIGH);
  30. }
  31.  
  32. void loop() {
  33.  
  34.   if (button_enabled == true) {
  35.     val = digitalRead(inPin);
  36.     if (val == 1) {
  37.       button_enabled = false;
  38.       digitalWrite(13, LOW);
  39.       buttonPress_beginTime = millis();
  40.     }
  41.   }
  42.   else {
  43.     // This part is what happens after a button has been pressed.
  44.     // This is how you would usually use a software button debounce,
  45.     // since most events will take less time to complete than the button debounce time.
  46.     buttonPress_currentTime = millis();
  47.     if (buttonPress_currentTime >= buttonPress_beginTime) {
  48.       if (buttonPress_currentTime >= (buttonPress_beginTime + button_debounce_time)) {
  49.         // If (button_debounce_time) has passed since (buttonPress_beginTime), then-
  50.         button_enabled = true; // re-enable the button
  51.         val = 0; // set the direction back to zero
  52.         digitalWrite(13, HIGH); // turn pin 13 back on
  53.       }
  54.     }
  55.     else {
  56.       buttonPress_beginTime = millis(); // millis() rollover condition.
  57.     }
  58.   }
  59.  
  60.   if (val == HIGH) {
  61.     stepperDirection = stepsPerRevolution;
  62.   }
  63.   else {
  64.     stepperDirection = (stepsPerRevolution * -1);
  65.   }
  66.   myStepper.step(stepperDirection);
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement