Hi, I'm a relatively novice coder (I teach kids so I can do lots of block programming, and I've dabbled a bit in arduino before for other various projects), but I am stumped by this problem. I'm trying to build an earthquake table that is run by a stepper motor. I've got all the hardware set up and have made the motor move, change speeds, bounce, and other simple things. However, what I actually want it to do is a bit more complicated than that. I have 3 arcade buttons, which correspond to the three speeds we want the motor to run. When button one is pushed, I want the motor to turn on at a slow speed for ten seconds, ignore all other input, and then turn off. With button two, do the same at a medium speed, and button three, do it at a fast speed.
The issues I am running into are:
-
delay does a great job blocking code, but the stepper needs to update every step so that doesn't work
-
If I use millis(), like in multiple things at once or Blink Without Delay, then the new input overrides the old input and it switches speeds if another button is pressed.
How do I insert blocking code for inputs while still allowing the motor to update, and the timer to count down?
I've included my code in case there is anything suggestions anyone has. Thanks in advance!
-Evan
#include <MultiStepper.h>
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper(1,7,6); //stepper in mode 1, PUL- on pin 7, DIR- on pin 6
const int button1 = 2; //slow button
const int button2 = 3; //medium button
const int led1 = 13; //indicator for slow
const int led2 = 12; //indicator for medium
int button1State = 0;
int button2State = 0;
unsigned long previousButton1Millis = 0;
unsigned long previousButton2Millis = 0;
const long interval = 10000;
void setup() {
// put your setup code here, to run once:
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
stepper.setMaxSpeed(1000);
stepper.setAcceleration(500);
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long currentMillis = millis(); //
button1State = digitalRead(button1);
button2State = digitalRead(button2);
if ((button1State == LOW) && (button2State == HIGH)) {
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
stepper.setSpeed(200);
} stepper.run();
if (currentMillis - previousButton1Millis >= interval){
previousButton1Millis = currentMillis;
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
stepper.stop();
}
if ((button1State == HIGH) && (button2State == LOW)) {
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
stepper.setSpeed(400);
stepper.run();
}
if (currentMillis - previousButton2Millis >= interval){
previousButton2Millis = currentMillis;
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
stepper.stop();
}
}