Encoder Direction trigger

I have a project on the go that has a shaft driven by a stepper motor with a linear encoder attached. The encoder provides feedback as to the shafts actual position compensating for any missed steps or slippage of the shaft.

I am trying to implement a program and repeat function where when the stepper is off you can move the shaft manually then repeat and loop the moves. This requires sensing the min and max input from the encoder.

I tried using something like this

if(cmd == 4){
int encmove = stepper1.readEnc();
int lastmove;
int encdir;
if(lastmove < stepper1.readEnc()){
    encdir = 1;
    lastmove = stepper1.readEnc();
}

if(lastmove > stepper1.readEnc()){
    encdir = 0;
    lastmove = stepper1.readEnc();

}

However the encoder has a slight jitter that seems to trigger the direction to read the opposite direction even when it’s moving forward. My thoughts were to compare the last 4 read values and if the majority are in the + direction then use the highest/lowest number.

Unless anyone has any other ideas or suggestions that could help with this.

Ideally when the shaft is at its max/min travel the value will be stored to memory then another piece of code will be executed to play and repeat the values stored there.

int lastmove;
int encdir;

What values do you think these local variables have? If you said "some random garbage", you'd be right. But, you'd also be wrong, because you assume that they contain useful values. They do NOT.

would lastmove not be set by the first calling of lastmove = stepper1.readEnc(); ?
that would make it whatever position the encoder is at ?
then int encdir would be whatever direction is either 1 or 0.

Ahh, however i think i see what you are getting at, they should be created before the loop and if statement and set to 0.

You make one comparison before you set those values, so you will have one reading that isn't necessarily related to the real movement and position of your encoder.

Thanks to you both for picking that up, seems to work a perfectly now. :slight_smile:

Thanks to you both for picking that up, seems to work a perfectly now.

I got into the habit years and years ago of following certain practices. When typing an if statement, I always put the open and close curly braces before typing any code for the body. When typing a variable declaration statement, I type the type, the name, a space, an equal sign, a space, and then the initial value for the variable. If I can't figure out what the initial value should be, I know I have some logic flaw that is going to bite me, so I deal with that before moving on.