Used two buttons to control the stepper motor forward and backward by the sketch attached, it was OK. I tried to stop the motor by changed the myStepper.setSpeed(motorSpeed); into myStepper.setSpeed(0); and used BTStop button, the motor can't restart again even pressed the Forward button after BTStop pressed. why? how to use button control the running stepper motor?
Thanks
//20200528 test GOOD!
const int BTSMForward = A2;
const int BTSMBackward = A3;
int BTSMForwardState = 0;
int BTSMBackwardState = 0;
const int BTStop = A4;
int BTStopState = 0;
#include <Stepper.h>
const int stepsPerRevolution = 200; /
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
void setup() {
Serial.begin(9600);
pinMode(BTSMForward, INPUT_PULLUP);
pinMode(BTStop, INPUT_PULLUP);
} // close setup
void loop() {
button();
}
void button() {
BTStopState = digitalRead(BTStop);
if (!BTStopState) {
Stop();
}
BTSMForwardState = digitalRead(BTSMForward);
if (BTSMForwardState) {
ForwardSM();
}
BTSMBackwardState = digitalRead(BTSMBackward);
if (BTSMBackwardState) {
BackwardSM();
}
}
// close void loop
void ForwardSM() {
// read the sensor value:
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(stepsPerRevolution / 100);
}
}
void BackwardSM() {
// read the sensor value:
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
/// myStepper.setSpeed(motorSpeed);
myStepper.setSpeed(0);
myStepper.setSpeed(motorSpeed);
// step 1/100 of a revolution:
myStepper.step(-stepsPerRevolution / 100);
}
}
void Stop() {
// read the sensor value:
int sensorReading = analogRead(A0);
// map it to a range from 0 to 100:
int motorSpeed = map(sensorReading, 0, 1023, 0, 100);
// set the motor speed:
if (motorSpeed > 0) {
myStepper.setSpeed(0);
// step 1/100 of a revolution:
myStepper.step(-stepsPerRevolution / 100);
}
Serial.print("stop");
// Serial.print();
}