06/09/2023
Writing about Stepper Motor With Arduino for educational and informational purposes only. however, do not hesitate to use this information on your own risk as we make no warranty of any kind.
void setup() {
// put your setup code here, to run once:
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
delay(10);
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
delay(10);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
delay(10);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
delay(10);
}
const int trigPin = 7; // Trigger Pin
const int echoPin = 6; // Echo Pin
const long dist = 5; // This is the distance to turn on the LED
int timer = 0;
void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//stepper pins
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
}
void loop() {
long duration, distinches;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distinches = duration / 74 / 2;
if (distinches < dist) {
digitalWrite(13, HIGH); //Turn On Blue
digitalWrite(12, LOW); //Turn Off Green
if (timer > 5 && timer < 10) {
digitalWrite(11, HIGH); //Turn On Yellow
}
if (timer > 9) {
digitalWrite(10, HIGH); //Turn On Red
//Spin the motor
for(int counter = 1;counter <= 160;counter++) {
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
delay(10);
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
digitalWrite(5, LOW);
delay(10);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, HIGH);
digitalWrite(5, LOW);
delay(10);
digitalWrite(2, LOW);
digitalWrite(3, LOW);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
delay(10);
}
}
} else {
digitalWrite(13, LOW); //Turn Off Blue
digitalWrite(12, HIGH); //Turn On Green
digitalWrite(11, LOW); //Turn Off Yellow
digitalWrite(10, LOW); //Turn Off Red
timer = 0; // Timer Reset
}
delay(1000);
timer = timer + 1; //Timer +1
}