Rotary Encoder Problem.

Hello Everyone.
I am trying to use a Rotary Encoder but is i add a delay to the code the rotary encoder will always read in the same direction.
Can anyone help??

Thanks.

 #define outputA 6
 #define outputB 5
 int angle = 0; 
 int aState;
 int aLastState;  

void setup(void)
{
  Serial.begin(9600);
  /**/
  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);
  /**/
}

void loop(void)
{ 
  aState = digitalRead(outputA);
  if (aState != aLastState){     
     if (digitalRead(outputB) != aState) { 
       angle ++;
     }
     else {
       angle --;
     }
  
     Serial.print("Position: ");
     Serial.println(angle);
  }
  aLastState = aState;
  delay (100);  //with this delay it doesnt work //
}

Hi,
You answered your own question, delay.
It is a blocking bit of code.

When you delay(100);
You STOP your program for 100mS, so if any input state changes, such as your encode input states, then they will be missed.

In the Examples part of the IDE, look for the "Blink without Delay" example.
This will give you an example of how to time a portion of your code, but still keep the program running.

Tom.. :slight_smile:

Change the baud rate to max, 115200.
Lose the delay() call.

Shorten the serial print string, ie lose this line:

     Serial.print("Position: ");

Then your code has a hope of keeping up.

Most importantly change:

  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);

to

  pinMode (outputA,INPUT_PULLUP);
  pinMode (outputB,INPUT_PULLUP);