#include <AccelStepper.h>
#include <Button.h>
const byte motStep = PB3;
const byte motDir = PB4;
Button btnStart(PB1);
Button homeSensor(PB2);
const int delMS = 5000; // Sets how fast the stepper moves
void setup() {
// Set pinmode for buttons and homing switch
pinMode(motStep, OUTPUT);
pinMode(motDir, OUTPUT);
// Startbutton object (for debounce)
btnStart.begin();
homeSensor.begin();
// Run the motor until the homing signal trips = Zeroed
while (homeSensor.pressed() == false) {
motMove(0, 1);
}
}
// Single function to move the motor, dir = 1 or 0 (left/right), number of steps
void motMove(byte dir, byte steps) {
dir = (dir == 1) ? HIGH : LOW;
for (int i = 0; i < steps; i++) {
digitalWrite(motDir, dir);
digitalWrite(motStep, HIGH);
delayMicroseconds(delMS);
digitalWrite(motStep, LOW);
delayMicroseconds(delMS);
}
}
// Collection of sequences to run based of the number sent to the function
void runSequence(int x) {
switch (x) {
case 1:
motMove(1, 100);
delay(500);
motMove(1, 100);
break;
case 2:
motMove(0, 100);
delay(500);
motMove(0, 100);
break;
case 3:
motMove(0, 100);
delay(500);
motMove(1, 100);
break;
case 4:
motMove(1, 100);
delay(500);
motMove(0, 100);
break;
case 5:
motMove(1, 200);
delay(500);
motMove(0, 200);
break;
}
}
void loop() {
// Wait for a button signal, generate a random number 1 to 4, call the sequence function
if (btnStart.pressed()) {
int x = random(1,5);
runSequence(x);
}
if(homeSensor.pressed()){
while (!homeSensor.pressed()) {
motMove(0, 1);
}
}
}