I am using a stepper motor for a project that I want it to stop. I tried for loops, while, and an if statement. All of these were placed inside the void loop, because it raised an error.
My code with the if loop:
//This program does about 1 rotation or 4100 steps. The program should be able to stop the stepper motor after it does one rotation.
int Pin1 = 8;
int Pin2 = 9;
int Pin3 = 10;
int Pin4 = 11;
int _step = 0;
int _on = 4100;
int _switches = 0;
boolean direct = false;
void setup() {
pinMode (Pin1, OUTPUT);
pinMode (Pin2, OUTPUT);
pinMode (Pin3, OUTPUT);
pinMode (Pin4, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (_on > 0) {
switch(_step)
{
case 0:
digitalWrite (Pin1, LOW);
digitalWrite (Pin2, LOW);
digitalWrite (Pin3, LOW);
digitalWrite (Pin4, HIGH);
break;
case 1:
digitalWrite (Pin1, LOW);
digitalWrite (Pin2, LOW);
digitalWrite (Pin3, HIGH);
digitalWrite (Pin4, HIGH);
break;
case 2:
digitalWrite (Pin1, LOW);
digitalWrite (Pin2, LOW);
digitalWrite (Pin3, HIGH);
digitalWrite (Pin4, LOW);
break;
case 3:
digitalWrite (Pin1, LOW);
digitalWrite (Pin2, HIGH);
digitalWrite (Pin3, HIGH);
digitalWrite (Pin4, LOW);
break;
case 4:
digitalWrite (Pin1, LOW);
digitalWrite (Pin2, HIGH);
digitalWrite (Pin3, LOW);
digitalWrite (Pin4, LOW);
break;
case 5:
digitalWrite (Pin1, HIGH);
digitalWrite (Pin2, HIGH);
digitalWrite (Pin3, LOW);
digitalWrite (Pin4, LOW);
break;
case 6:
digitalWrite (Pin1, HIGH);
digitalWrite (Pin2, LOW);
digitalWrite (Pin3, LOW);
digitalWrite (Pin4, LOW);
break;
case 7:
digitalWrite (Pin1, HIGH);
digitalWrite (Pin2, LOW);
digitalWrite (Pin3, LOW);
digitalWrite (Pin4, HIGH);
break;
case 8:
digitalWrite (Pin1, LOW);
digitalWrite (Pin2, LOW);
digitalWrite (Pin3, LOW);
digitalWrite (Pin4, LOW);
break;
}
if(direct == false) {
_step++;
_switches++;
direct = false;
}else{
_step--;
_switches--;
direct = true;
}
Serial.println(_switches);
if(_step>7) {
_step=0;
}
if(_step<0) {
_step=7;
}
_on--;
delay(1); // This solves it.
}
break; //This raises an error when used with for loop.
}
Can anyone help on why the delay makes it stop? And why the break command raises and error?
Arduino UNO. 5 wire stepper.