Advertisement
skizziks_53

mega_stepper_button_02

Feb 15th, 2018
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.84 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 'fixed' software button debounce where the debounce time is not tracked
  7.    and the button is only re-enabled after a certain event completes
  8.    (in this case when the stepper motor completes one cycle of rotation).
  9.  
  10.    This is not the usual way to debounce,
  11.    but it can work okay if the button event is long enough-
  12.    (such as a stepper motor turning a bunch of times).
  13. */
  14.  
  15. #include <Stepper.h>
  16.  
  17. const int stepsPerRevolution = 128;
  18. const int inPin = 52;
  19. int val = 0;
  20. Stepper myStepper(stepsPerRevolution, 3, 5, 4, 6);
  21. int stepperDirection = 0; // This is used to hold a modified value of stepsPerRevolution (either positive or negative) without changing the original value.
  22.  
  23. // Below is variables for debouncing the button input.
  24. bool button_enabled = true;
  25. // There is no variables needed for debounce timing.
  26.  
  27. void setup() {
  28.   myStepper.setSpeed(120);
  29.   pinMode(inPin, INPUT);
  30.   pinMode(13, OUTPUT);
  31.   digitalWrite(13, HIGH);
  32. }
  33.  
  34. void loop() {
  35.  
  36.   if (button_enabled == true) {
  37.     val = digitalRead(inPin);
  38.     if (val == 1) {
  39.       button_enabled = false;
  40.       // If the button is enabled and it is pressed, then it is disabled here.
  41.       digitalWrite(13, LOW);
  42.     }
  43.   }
  44.  
  45.   if (val == HIGH) {
  46.     stepperDirection = stepsPerRevolution;
  47.   }
  48.   else {
  49.     stepperDirection = (stepsPerRevolution * -1);
  50.   }
  51.  
  52.   myStepper.step(stepperDirection);
  53.  
  54.   // After the motor has rotated through one cycle, the direction value is reset to zero and the button is re-enabled.
  55.   val = 0;
  56.   button_enabled = false;
  57.   digitalWrite(13, HIGH); // Turn pin 13 back on, since the button is now enabled.
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement