Hi I have a project in which I have a toggle button that reverses the stepper motor direction but it only changes the direction when released! I would like the opposite to change direction on the press of the button not the release!
here is my code:_
const int stepPin = 3;
int dirPin = 4;
int dirButton = 2;
int state = HIGH;
int reading;
int previous = LOW;
int stepDelay=500;
#define bt_S A2 // Stop Button
#define enPin 10 //10Pin of Arduino--Enabled of stepper motor driver
#define bt_Sp A1 // ms1
#define ms1Pin 11 //10Pin of Arduino—ms1 high or low select
int Mode=1, flag=0;
long time = 0;
long debounce = 500;
int customDelay,customDelayMapped; // Defines variables
void setup() {
// Sets the two pins as Outputs
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(dirButton, INPUT_PULLUP);
pinMode(bt_S, INPUT_PULLUP); // declare bt_S as input
pinMode(enPin, OUTPUT); // declare as output for Enabled of stepper motor driver
pinMode(bt_Sp, INPUT_PULLUP); // declare bt_S as input
pinMode(ms1Pin, OUTPUT); // declare as output for Enabled of stepper motor driver
digitalWrite(dirPin,HIGH); //change the rotation direction HIGH for clockwise and LOW for anticlockwise
}
void loop() {
if(digitalRead (bt_Sp) == 0){ //For ms1
if(flag==0){flag=1;
if(Mode>1)Mode=1;
else{Mode=!Mode;
if(Mode==0)digitalWrite(ms1Pin, HIGH);
else digitalWrite(ms1Pin, LOW);
}
delay(200);
}
}else{flag=0;}
reading = digitalRead(dirButton);
if(digitalRead (bt_S) == 0){ //For Stop
if(flag==0){flag=1;
if(Mode>1)Mode=1;
else{Mode=!Mode;
if(Mode==0)digitalWrite(enPin, HIGH);
else digitalWrite(enPin, LOW);
}
delay(200);
}
}else{flag=0;}
// if the input just went from LOW and HIGH and we've waited long enough
// to ignore any noise on the circuit, toggle the output pin and remember
// the time
if (reading == HIGH && previous == LOW && millis() - time > debounce) {
if (state == HIGH)
state = LOW;
else
state = HIGH;
time = millis();
}
digitalWrite(dirPin, state);
previous = reading;
digitalWrite(stepPin, HIGH);
delayMicroseconds(stepDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay);
customDelayMapped = speedUp(); // Gets custom delay values from the custom speedUp function
// Makes pules with custom delay, depending on the Potentiometer, from which the speed of the motor depends
digitalWrite(stepPin, HIGH);
delayMicroseconds(customDelayMapped);
digitalWrite(stepPin, LOW);
delayMicroseconds(customDelayMapped);
}
// Function for reading the Potentiometer
int speedUp() {
int customDelay = analogRead(A0); // Reads the potentiometer
int newCustom = map(customDelay, 0, 1023, 100,15000); // Convrests the read values of the potentiometer from 0 to 1023 into desireded delay values (300 to 4000)
return newCustom;
}
Thanks