Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 15 February 2018
- This is a test sketch to operate a reversible stepper motor on an Arduino Mega.
- The stepper motor spins all the time, but pressing the button reverses the motor for 1 rotation cycle.
- This sketch uses a 'normal' software button debounce,
- where the debounce time is tracked separately and resets itself no matter what else is happening.
- */
- #include <Stepper.h>
- const int stepsPerRevolution = 128;
- const int inPin = 52;
- int val = 0;
- Stepper myStepper(stepsPerRevolution, 3, 5, 4, 6);
- int stepperDirection = 0; // This is used to hold a modified value of stepsPerRevolution (either positive or negative) without changing the original value.
- // Below is variables for debouncing the button input.
- bool button_enabled = true;
- int button_debounce_time = 500; // This is the time in milliseconds for the button to de-bounce (half a second).
- unsigned long buttonPress_beginTime = 0;
- unsigned long buttonPress_currentTime = 0;
- void setup() {
- myStepper.setSpeed(120);
- pinMode(inPin, INPUT);
- // This sketch uses pin 13 to indicate if the button input is enabled or not.
- pinMode(13, OUTPUT);
- digitalWrite(13, HIGH);
- }
- void loop() {
- if (button_enabled == true) {
- val = digitalRead(inPin);
- if (val == 1) {
- button_enabled = false;
- digitalWrite(13, LOW);
- buttonPress_beginTime = millis();
- }
- }
- else {
- // This part is what happens after a button has been pressed.
- // This is how you would usually use a software button debounce,
- // since most events will take less time to complete than the button debounce time.
- buttonPress_currentTime = millis();
- if (buttonPress_currentTime >= buttonPress_beginTime) {
- if (buttonPress_currentTime >= (buttonPress_beginTime + button_debounce_time)) {
- // If (button_debounce_time) has passed since (buttonPress_beginTime), then-
- button_enabled = true; // re-enable the button
- val = 0; // set the direction back to zero
- digitalWrite(13, HIGH); // turn pin 13 back on
- }
- }
- else {
- buttonPress_beginTime = millis(); // millis() rollover condition.
- }
- }
- if (val == HIGH) {
- stepperDirection = stepsPerRevolution;
- }
- else {
- stepperDirection = (stepsPerRevolution * -1);
- }
- myStepper.step(stepperDirection);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement