Im pretty new to arduino, and i wanted to write a code where i control a stepper to do a certain movement (different angles the stepper should drive to) depending on the position of my rotary encoder. Sadly i've runned into some problems pretty early. Getting a value on my serial monitor by turning the rotary encoder is no problem but as soon as i put (Motor.step(2048)) or something else related to the stepper into the loop i can't get a value from my rotary encoder anymore to let the stepper drive somewhere depending of that value the encoder gives me. I hope anyone can help.
#include <Stepper.h>
int Steps = 2048;
Stepper Motor(Steps, 10, 11, 12, 13);
#define outputA 2
#define outputB 3
int counter = 0;
int aState;
int aLastState;
void setup() {
// put your setup code here, to run once:
Motor.setSpeed(5);
pinMode(outputA, INPUT_PULLUP);
pinMode(outputB, INPUT_PULLUP);
Serial.begin(9600);
aLastState = digitalRead(outputA);
for (int i = 2; i <10; i++) {
pinMode(i, OUTPUT);
}
}
void loop() {
// put your main code here, to run repeatedly:
aState = digitalRead(outputA);
if(aState != aLastState) {
if(digitalRead(outputB) != aState) {
counter ++;
} else {
counter --;
}
Serial.print("Position: ");
Serial.println(counter);
}
aLastState = aState;
Motor.step(2048);
}
No matter how i put this code for the stepper into the loop, the encoder doesnt work anymore.
Keep in mind that the step() method in the Stepper library is blocking. In other words it does not return until it completes the number of steps specified.
You have a couple of choices to minimize blocking:
Only call the step() method with 1 step and control the speed yourself
Use the AccelStepper library which is non-blocking.
You may still want to use an encoder library as @Grumpy_Mike suggested. In any case, the more you can avoid blocking the more responsive your sketch will be.
Are you using an UNO? If so I would not use pin 13 since the on-board LED is attached to that. Also I am assuming you are not using a driver stepper. If you are not and since you instantiated the stepper object with no parameters then your motor needs to be connected to pins 2, 3, 4, and 5.
For the encoder you need to make sure the pins you are using are usable for interrupts. For example, on an UNO only pins 2 and 3 are capable of interrupting.