/*
This sketch handle stepper motors without driver nor librairies.
It was designed so that current does not flow through the coils
when the motor is stopped.
A Red LED lit reveals the current flow through a coil.
A Green LED lit indicates the state of a line.
The VLWS (Voltage Level When Stopped) is to keep the lines HIGH
or LOW when stopped. In no case current flows through the coils.
Cable colors as seen at: 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 // or HIGH if you find it more interesting
// 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);
}