// Using NO library but blocking loop
#define dirPin 2
#define stepPin 3
#define stepsPerRevolution 200
#define buttonPin 4
#define rgbLED 8
bool buttonState = 0;
void setup() {
randomSeed(analogRead(A0));
Serial.begin(115200);
pinMode(rgbLED, OUTPUT);
pinMode(rgbLED + 1, OUTPUT);
pinMode(rgbLED, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH)
setStep();
}
void setStep()
{
int speed = random(250, 1750); // motor speed (minimum, maximum)
int rotations = random(3) + 1; // number of rotations +1 for non-zero
int direction = random(2); // direction 0 = CW or 1 = CCW
Serial.print("DIRECTION: ");
Serial.print((direction == 0) ? " CW" : "CCW");
Serial.print(" ROTATIONS: ");
Serial.print(rotations);
Serial.print(" SPEED: ");
Serial.println(2000 - speed);
digitalWrite(rgbLED + direction, HIGH);
rotate (speed, rotations, direction);
digitalWrite(rgbLED + direction, LOW);
delay(250);
digitalWrite(rgbLED + !direction, HIGH);
rotate (speed, rotations, !direction);
digitalWrite(rgbLED + !direction, LOW);
}
void rotate(int speed, int rotations, bool direction) {
digitalWrite(dirPin, direction);
for (int i = 0; i < rotations * stepsPerRevolution; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(speed);
digitalWrite(stepPin, LOW);
delayMicroseconds(speed);
}
}
/*
+-------------------------+
LOW=DSBL | ENABLE A4988 VMOT | 8-35vdc ---+ 100uf electro cap
microstep | MS1 GND | gnd -------+ pwr spike protect
microstep | MS2 2B | stepper 2B
microstep | MS3 2A | stepper 2A
RST | RESET 1A | stepper 1A
SLP | SLEEP 1B | stepper 1B
Pin 3 | STEP VDD | 5vdc
Pin 2 | DIR GND | gnd
+-------------------------+
MS1 MS2 MS3 Step resolution
Low Low Low Full step
High Low Low 1/2 step
Low High Low 1/4 step
High High Low 1/8 step
High High High 1/16 step
SET DRIVER CURRENT LIMIT
1. Power A4988 driver (Vdd, GND)
2. Connect RST to SLP
3. Disconnect motor
4. Apply USB power
5. Calculate current limit: Current Limit = Vref ÷ (8 × Rcs)
6. A current limit of 1A (standard) needs Vref of 540mV
7. Adjust POT while measuring Vref at GND to POT (metal screw)
8. If the motor is making a lot of noise, lower the current limit
*/