encoder and LCD problem

Hey
i try wrote a code that count encoder turns and display the turns counter to an LCD 1602 display.
at first i wrote the part that read the encoder and checked it with serial port to verify the counter code and it work fine (count up and down)
then i add the LCD display part and since then something happens to the encoder readings, when i counting up everything is ok
but when i try to count down (rotate ccw) the counter continue to count up no matters if i rotate fast or slow, sometimes it does count down for some steps and then again going up .
if i comment the LCD part and check with serial monitor everything is ok , but when i do use the LCD part the encoder count almost only up again.
does anyone have an idea why ?

my code is:

#include <LiquidCrystal.h>

int PIN_A = 7;
int PIN_B = 6;
int counter = 0;
int LAST_POS = 0;
int CORRENT_POS = 0;
int turns =0;
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);


void setup()
{
 Serial.begin(9600);
  pinMode (PIN_A, INPUT);
  pinMode (PIN_B, INPUT);
  lcd.begin(16, 2);
 
      
       lcd.setCursor(0, 0);      
       lcd.print(" ENCODER" );
       lcd.setCursor(0, 1);
       lcd.print("COUNTER" );
       delay(3000);
       lcd.clear();
  
  
}

void loop()
{
       CORRENT_POS = digitalRead(PIN_A);
  if ((LAST_POS == LOW) && (CORRENT_POS == HIGH))
  {
      if (digitalRead(PIN_B) == LOW) 
        {
           if (counter>0)
              {
                counter--;
                turns = counter*20;
              }
         } else 
              {
                 if (counter<49)
                    {
                      counter++;
                      turns = counter*20;
                    }
              }

          lcd.clear();
  }
  LAST_POS = CORRENT_POS;
  
            lcd.setCursor(0, 0);
            lcd.print("  ");
            lcd.print(turns );
            lcd.print(" of" );
            lcd.setCursor(0, 1);
            lcd.print("encode" );

            
      }

sketch_apr14a.ino (1.25 KB)

Well, you are only looking at one pin of the encoder - it just goes HIGH and LOW, but gives you no indication of which direction it is turning. How could it?

Need to search on "quadrature encoder".

Paul__B:
you are only looking at one pin of the encoder

It looks valid to me:
When PIN_A goes from LOW to HIGH, it checks he state of PIN_B to determine the direction.

If this worked before you added the LCD, and now it still knows when to count, but not the direction, then double check the wiring to PIN_B.

Also, you are now updating the LCD on every loop(). Maybe this takes enough time that you don't sample your encoder fast enough and start missing state changes. See if it helps if you only update the LCD when the counter has changed.

I have a funny feeling the code changed before my eyes. :astonished:

Oh well.