Hi everyone, I am building a prototype for an invention and I am very new to Arduino but it is what I needed to make my project work. I have had a little help to get this far so thank you all. However, I am not sure how to execute the last step in my sketch to make my motor turn off after 40 counterclockwise revs? When the motor switches from CW to CCW, does it keep counting revs up or does it then countdown? This is my issue, I am not sure what I need to write to get it to stop after 40 CCW revs. Can someone give me some guidance please? Thanks again.
const int stepPin = 5;
const int dirPin = 3;
const long stepsPerRevolution = 1375;
const int buttonPin = 4;
int buttonState = 0;
long Distance = 0;
void setup()
{
// Declare pins as Outputs
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop()
{
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
// Set motor direction clockwise
digitalWrite(dirPin, LOW);
// Spin motor slowly
for (int x = 0; x < stepsPerRevolution; x++)
{
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
Distance = Distance + 1;
}
} else {
// turn motor off:
digitalWrite(stepPin, LOW);
if (Distance == 55000L) {
// Set motor direction counterclockwise
digitalWrite(dirPin, HIGH);
// Spin motor slowly
for (int x = 0; x < stepsPerRevolution; x++)
{
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
}
} else {
// turn motor off:
digitalWrite(stepPin, LOW);
}
}
}
if (Distance == 55000L)
{
// Set motor direction counterclockwise
digitalWrite(dirPin, HIGH);
// Spin motor slowly
for (int i = 0; i < 40; i++)
{
for (int x = 0; x < stepsPerRevolution; x++)
{
digitalWrite(stepPin, HIGH);
delayMicroseconds(500);
digitalWrite(stepPin, LOW);
delayMicroseconds(500);
}
}
Distance=0;
}```
Not tested, not even compiled
You are counting steps here: Distance = Distance + 1;
When going in the other direction it is entirely up to you if you count up or count down. It's all just counting.
The AccelStepper library will keep track of your position by doing the counting for you. It will count up in one direction and down in the other. It also takes care of ramping the speed up and down to keep the stepper from missing steps by trying to change speed too quickly.