quadrature encoder not counting anti clock wise

guys,
i have been working on the following encoder from element 14

1.http://sg.element14.com/bourns/pec11r-4225f-s0024/encoder-incremental-2ch-60rpm/dp/2381866?ost=2381866&selectedCategoryId=&categoryNameResp=All&searchView=table&iscrfnonsku=false

i am sing basic counting code ,the encoder doesnt count anti clockwise,
i have pasted the code below kindly help me

/* Read Quadrature Encoder

  • Connect Encoder to Pins encoder0PinA, encoder0PinB, and +5V.
  • Sketch by max wolf / www.meso.net
  • v. 0.1 - very basic functions - mw 20061220

*/

int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() {
pinMode (encoder0PinA,INPUT);
pinMode (encoder0PinB,INPUT);
Serial.begin (9600);
}

void loop()
{
n = digitalRead(encoder0PinA);
//Serial.println
if ((encoder0PinALast == LOW) && (n == HIGH))
{

if (digitalRead(encoder0PinB) == HIGH )
{
// Serial.println("entered");
encoder0Pos--;
}
else
{
encoder0Pos++;
}
Serial.println (encoder0Pos);
// Serial.println ("/");
}
encoder0PinALast = n;
}

Can you confirm with a very simple digitalRead() sketch that you can see HIGH and LOW transitions on encoder0PinB which is digital pin 4.

no, the encoder0pinb gives a constant high output,

pinMode (encoder0PinA,INPUT);

Do you have pulldown resistors on the encoder pins?

Hi,

http://www.farnell.com/datasheets/1785154.pdf

You need pull up resistors.
The encoder is in the broken line box below.
Encoder1.jpg

Tom… :slight_smile:

All you need is to change:

 void setup() {
   pinMode (encoder0PinA,INPUT);
   pinMode (encoder0PinB,INPUT);
   Serial.begin (9600);
 }

to

 void setup() {
   pinMode (encoder0PinA,INPUT_PULLUP);
   pinMode (encoder0PinB,INPUT_PULLUP);
   Serial.begin (9600);
 }

Read both pins unconditionally at the top of the loop.

byte pinAState;
byte pinBState;

void loop() {
  byte pinAPrevState = pinAState; 
  byte pinBPrevState = pinBState; 
  pinAState = digitalRead(pinA);
  pinBState = digitalRead(pinB);
}

Quadrature logic is:

If A has gone high, then forward if B is high, else backward.
If A has gone low, then backward if B is high, else forward.

If B has gone high, then backward if B is high, else forward.
If B has gone low, then forward if B is high, else backward.

more compactly:

if(pinAPrevState != pinAState) if(pinA == pinB) count++; else count--;
if(pinBPrevState != pinBState) if(pinA == pinB) count--; else count++;

Couple this with what Paul said: