#define dirPin 8
#define stepPin 9
#define enaPin 10
int microstepping = 16; //1, 2, 4, 8, 16
int steps = 200 * microstepping;
int x;
int count;
const int STEPS_PER_REV = 200 * 16; // Change this to match your stepper motor
const int DEFAULT_RPM = 30; // Change this to your desired default RPM value
unsigned int prevMillis;
unsigned int delayMillis = 2;
unsigned int currentmillis;
//int microstepping = 16;
float stepsperrev = 200 * microstepping;
float rpm = 60;
float stepspersecond = (rpm * stepsperrev) / 60;
float inputSteps = 400;
int incInSteps = 0;
boolean pulseStat = LOW;
void setup() {
Serial.begin(115200);
// put your setup code here, to run once:
pinMode(dirPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(enaPin, OUTPUT);
digitalWrite(enaPin, LOW);
}
void loop() {
//basic();
//generateStepPulses(9, 8, 10, DEFAULT_RPM);
stepmillis();
}
void basic() {
digitalWrite(enaPin, HIGH); //if toggled HIGH, it will release its hold
digitalWrite(dirPin, HIGH); //if toggled HIGH, it will go clockwise
//For Making a pulse using for Loop
for(x = 0; x != steps; x++) {
digitalWrite(stepPin, HIGH);
//delayMicroseconds(1000);
digitalWrite(stepPin, LOW);
//delayMicroseconds(1000);
Serial.println(x);
}
digitalWrite(enaPin, LOW); //if toggled HIGH, it will release its hold
steps = 0;
}
void generateStepPulses(int stepPin1, int dirPin1, int steps1, int rpm1) {
// Calculate the step pulse duration based on the RPM and steps per revolution
float steps_per_second = (rpm1 * STEPS_PER_REV) / 60.0;
float step_pulse_duration = 1.0 / steps_per_second * 1000;
// Set the direction pin based on the desired direction of rotation
if (steps > 0) {
digitalWrite(dirPin1, HIGH);
} else {
digitalWrite(dirPin1, LOW);
steps1 = -steps1;
}
// Generate the desired number of step pulses
unsigned long previous_time;
unsigned long current_time = millis();
for (int i = 0; i <= steps1; i++) {
previous_time = current_time;
if (current_time - previous_time >= step_pulse_duration) {
digitalWrite(stepPin1, HIGH);
digitalWrite(stepPin1, LOW);
}
}
}
void stepmillis() {
digitalWrite(enaPin, HIGH); //if toggled HIGH, it will release its hold
digitalWrite(dirPin, HIGH); //if toggled HIGH, it will go clockwise
float microseconds = round(stepspersecond/1000000);
if (incInSteps <= inputSteps) {
if (micros() - prevMillis >= microseconds && pulseStat == LOW) {
digitalWrite(stepPin, HIGH);
digitalWrite(stepPin, LOW);
pulseStat = HIGH;
prevMillis = micros();
}
else if (micros() - prevMillis >= microseconds/2 && pulseStat == HIGH) {
incInSteps++;
pulseStat = LOW;
prevMillis = micros();
Serial.print("incrementing: ");
Serial.println(incInSteps);
}
}
}