So I have this code I made, and basically what it does is when I press the button the motor rotates to the right for X amount of steps. after this is done Led 1 turns on and Led2 turns off and i can press the button again. When I press the button again, the motor rotates the other side and Led 2 turns on and led1 off... you get the idea.
But the weird thing is that at random moments the motor rotates glitchy or back and forth for a little... Most of the times it just works smooth, but for my particular project I cant have these bugs since im working with a precise amount of steps it has to complete.
Could anyone check my code and find out why it might bug sometimes? cuz I am at a loss
P.S. I did get some parts of the code from internet, so ignore the names like relaypin and some comments... these relaypins go toward the LEDs
int pbuttonPin = 7;// connect output to push button
int relayPin = 10;// Connected to relay (LED)
int relayPin2 = 11;// Connected to relay (LED)
int val = 0; // push value from pin 2
int lightON = 0;//light status
int pushed = 0;//push status
#define step_pin 3
#define dir_pin 2
#define MS1 5
#define MS2 4
int dir;
int steps = 3000;
void setup() {
Serial.begin(9600);
pinMode(pbuttonPin, INPUT_PULLUP);
pinMode(relayPin, OUTPUT);
pinMode(relayPin2, OUTPUT);
digitalWrite(relayPin, HIGH);// keep the load OFF at the begining. If you wanted to be ON, change the HIGH to LOW
pinMode(relayPin2, OUTPUT);
digitalWrite(relayPin2, HIGH);// keep the load OFF at the begining. If you wanted to be ON, change the HIGH to LOW
pinMode(MS1, OUTPUT);
pinMode(MS2, OUTPUT);
pinMode(dir_pin, OUTPUT);
pinMode(step_pin, OUTPUT);
digitalWrite(MS1, LOW);
digitalWrite(MS2, LOW);
digitalWrite(dir_pin, HIGH);
}
void loop() {
val = digitalRead(pbuttonPin);// read the push button value
if(val == HIGH && lightON == LOW){
pushed = 1-pushed;
}
lightON = val;
if(pushed == LOW){
Serial.println("Light ON");
digitalWrite(relayPin, HIGH);
digitalWrite(relayPin2, LOW);
digitalWrite(dir_pin, LOW);
}
else{
Serial.println("Light OFF");
digitalWrite(relayPin, LOW);
digitalWrite(relayPin2, HIGH);
digitalWrite(dir_pin, HIGH);
}
if (val == LOW){
Motor();
delay(100);
}
}
void Motor(){
steps = 3000;
while(steps > 0) {
digitalWrite(step_pin, HIGH);
delay(1);
digitalWrite(step_pin, LOW);
delay(1);
steps--;
}
return;
}