Go Down

Topic: Rotary Encoder Problem. (Read 533 times) previous topic - next topic


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??


Code: [Select]

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

void setup(void)
  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: ");
  aLastState = aState;
  delay (100);  //with this delay it doesnt work //


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.. :)
Everything runs on smoke, let the smoke out, it stops running....


Oct 25, 2017, 11:48 pm Last Edit: Oct 25, 2017, 11:50 pm by MarkT
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:
Code: [Select]

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

Code: [Select]

  pinMode (outputA,INPUT_PULLUP);
  pinMode (outputB,INPUT_PULLUP);
[ I will NOT respond to personal messages, I WILL delete them, use the forum please ]

Go Up