/*
This sketch drives a stepper motor without using a driver or external
libraries.
It is designed so that no current flows through the coils when the
motor is stopped.
- The red LEDs turn on when current flows through a coil.
- The green LEDs turn on when the line is set HIGH.
The constant VLWS (Voltage Level When Stopped) defines whether all four
lines are held HIGH or LOW when the motor is not moving. In both cases,
no current flows through the coils.
Wiring reference for cable colors:
https://i.imgur.com/eZdhbHZ.png
Written in 2024 by raphik
*/
#define AN 11
#define AP 10
#define BP 9
#define BN 8
#define VLWS LOW // set to LOW or HIGH, as preferred
// https://blog.ars-electronica.com.ar/2015/04/tutorial-stepper-motor-paso-a-paso.html
//uint8_t sequence[4] = { B1000, B0010, B0100, B0001 }; // weaker torque
uint8_t sequence[4] = { B1010, B0110, B0101, B1001 }; // stronger torque
int8_t index = 0;
void setup() {
Serial.begin(9600);
pinMode(AN,OUTPUT); pinMode(AP,OUTPUT); // coil A
pinMode(BP,OUTPUT); pinMode(BN,OUTPUT); // coil B
}
void loop() {
int thinkanumber = random(100, 500 );
Serial.println(thinkanumber);
// sequence of movements that always ends in zero steps
step(thinkanumber/5); delay(500);
step(-thinkanumber/3); delay(500);
step(thinkanumber/5); delay(500);
step(thinkanumber%5); delay(500);
step(thinkanumber/5); delay(500);
step(-thinkanumber/3); delay(500);
step(-thinkanumber%3); delay(500);
step(thinkanumber/5); delay(500);
step(-thinkanumber/3); delay(500);
step(thinkanumber/5); delay(500);
Serial.println(F("The stepper must've gotten back to zero."));
delay(2000);
}
void step(int16_t steps) {
int8_t direction = 0;
if (steps > 0 ) direction = 1;
if (steps < 0 ) direction = -1;
for ( int16_t i = abs(steps); i > 0; i-- ) {
index += direction;
if (index == 4) index = 0;
if (index == -1) index = 3;
digitalWrite(AN, bitRead(sequence[index], 0));
digitalWrite(AP, bitRead(sequence[index], 1));
digitalWrite(BP, bitRead(sequence[index], 2));
digitalWrite(BN, bitRead(sequence[index], 3));
delay(20);
}
digitalWrite(AN, VLWS); digitalWrite(AP, VLWS);
digitalWrite(BP, VLWS); digitalWrite(BN, VLWS);
}