Hello all, I am struggling with this script using TB6600, Arduino UNO R3 and a Sanyo Stepper Motor.
I need the script to do the following:
Click of a button move motor clockwise, delay a few seconds then move motor counterclockwise. And finally have an emergency stop button just in case.
The script is working but some times the start button doesnt work and the emergency stop doesnt do its thing.
Hope somebody can help here. Thanks
#include <AccelStepper.h>
const byte stepPin = 8;
const byte dirPin = 9;
const byte enablePin = 10;
int EMERGENCY_STOP_PIN = 3;
const byte buttonPin = 4;
long moveSteps = 5000;
bool trigger_forward = false ;
bool trigger_backward = false;
unsigned long time = 0 ;
AccelStepper stepper(AccelStepper::DRIVER, stepPin, dirPin);
bool lastButtonState = LOW;
bool isPressed = false;
void setup()
{
Serial.begin(9600);
pinMode(enablePin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
digitalWrite(enablePin, LOW);
stepper.setMaxSpeed(1000);
stepper.setAcceleration(1000);
pinMode (EMERGENCY_STOP_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(EMERGENCY_STOP_PIN), emergencyStop, CHANGE);
trigger_forward = true ;
}
void emergencyStop() {
stepper.stop();
Serial.println(F("The stepper motor is STOPPED"));
}
void loop()
{
static unsigned long timer = 0;
unsigned long interval = 50; // check switch 20 times per second
if (millis() - timer >= interval){
timer = millis();
//Serial.println("Timer:");
//Serial.println(timer);
bool buttonState = digitalRead(buttonPin);
Serial.println("buttonState:");
Serial.println(buttonState);
Serial.println(lastButtonState);
if (buttonState != lastButtonState)
{
if (buttonState == HIGH){
isPressed = true;
Serial.println(F("Button Start Pressed"));
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;
}
if(isPressed == true){
if ( millis () - time >= 1000 && trigger_forward) // if triggered set the forward motion going
{
trigger_forward = false ;
trigger_backward = true ;
isPressed = false;
time = millis() ;
Serial.println("Time1:");
Serial.println(time);
stepper.moveTo(1000);
Serial.println("The stepper moving FORWARD....");
}
}
if(isPressed == false){
//Serial.println 2(millis ());
if (millis ()- time >= 10000 && trigger_backward) // if return is due, do it
{
trigger_backward = false ;
trigger_forward = true;
time = millis();
Serial.println("Time2:");
Serial.println(time);
stepper.moveTo(-1000) ;
Serial.println("The stepper moving BACKWARDS....");
}
}
stepper.run(); // must be called very often
// ideally once every loop iteration
}
Check up this function! It's likely a blocking function, running until the job is done. Therefore the stop command is not accepted until the previous command is finished.
I only use a little Accelstepper but not like You do. There are helpers knowing more and other libraries to use. Mobatool?