/*Example sketch to control a stepper motor with A4988 stepper motor driver,
AccelStepper library and Arduino: continuous rotation.
More info: https://www.makerguides.com */
// Include the AccelStepper library:
#include <AccelStepper.h>
#define dirPin 8
#define stepPin 9
#define motorInterfaceType 1
#define btn 4
AccelStepper stepper = AccelStepper(motorInterfaceType, stepPin, dirPin);
void setup() {
Serial.begin(9600);
stepper.setMaxSpeed(1000);
pinMode(btn, INPUT_PULLUP);
}
int btn_current = 0;
int btn_previous = 0;
bool stepper_state = true;
String input_val;
int val = 0;
void loop()
{
long distance = stepper.distanceToGo();
long position = stepper.currentPosition();
if (Serial.available())
input_val = Serial.readString();
if (val > 0)
val = input_val.toInt();
if (stepper.distanceToGo() == 0)
{
// Random change to speed, position and acceleration
// Make sure we dont get 0 speed or accelerations
stepper.moveTo(rand() % 200);
stepper.setMaxSpeed(1000);
stepper.setAcceleration((rand() % 200) + 1);
}
btn_current = digitalRead(btn);
if (btn_current == 0 && btn_previous == 1) {
stepper_state = !stepper_state;
}
btn_previous = btn_current;
if (stepper_state) {
stepper.run();
} else {
stepper.stop();
}
Serial.print("distance: " + String(distance));
Serial.println(" position: " + String(position));
}