Here's my code for starting a Stepper motor and trying to stop the motor:
#include <BasicStepperDriver.h>
#define DIR 34
#define STEP 36
#define ENBL 30
BasicStepperDriver stepper1(10000, DIR, STEP, ENBL);
BasicStepperDriver stepper2(10000, DIR, STEP, ENBL);
bool enableMotor1 = false;
bool enableMotor2 = false;
void rotate1() {
Serial.println("Rotate start 1");
stepper1.rotate(360);
Serial.println("Rotate end 1");
}
void rotate2() {
Serial.println("Rotate start 2");
stepper2.rotate(360);
Serial.println("Rotate end 2");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
stepper1.enable();
stepper1.setMicrostep(1);
stepper1.setRPM(50);
stepper2.enable();
stepper2.setMicrostep(1);
stepper2.setRPM(50);
}
void loop() {
if(enableMotor1 == true) {
rotate1();
} else if(enableMotor2 == true) {
rotate2();
}
if (Serial.available ()) {
String first = Serial.readStringUntil(',');
Serial.read();
String second = Serial.readStringUntil(',');
if(first == "start"){
if(second == "1") {
Serial.println("Starting motor 1");
enableMotor1 = true;
}
if(second == "2") {
Serial.println("Starting motor 2");
enableMotor2 = true;
}
} else if(first == "stop") {
if(second == "1") {
Serial.println("Stopping motor 1");
enableMotor1 = false;
stepper1.disable();
}
if(second == "2") {
enableMotor2 = false;
Serial.println("Stopping motor 1");
stepper2.disable();
}
}
}
}
The problem with this code is that it is not possible to stop the motor through Serial interface. The goal is to have the Stepper motor running until the stop
command is entered in the serial monitor. What could be wrong in my code?
This image shows that we can start the motor but can't be stopped:
start,1
instead ofstart,1,
, so the second call toreadStringUntil(',')
should incur in a timeout of1 s.
because no comma appears after1
. Note that this delay could potentially disrupt your stepper by preventing it from rotating at a constant rate. Removing the delay isn't an option either, because with the current parsing functionality that you implement you increase the chance of parsing fragments of commands rather than the whole thing. Note that you would need an extraSerial.read()
to account for the extra,
too.first
andsecond
to serial after parsing, what's inside? 2. repeat the commandstart, 1
and see if it is taken again? 3. send the commandstop, 1
for first and see whether it is taken?stop, 1
andstop, 1,
works?