Encoder library help

Status
Not open for further replies.

ilium007

Well-known member
I am trying to get a rotary encoder working on a Teensy 3.2 and 3.6 - I have tried my code on both but the same happens.

I am getting a count of 4 for each detent on a Bournes 24 position rotary encoder.

My code:

Code:
#define ENCODER_OPTIMIZE_INTERRUPTS

#include <Encoder.h>
Encoder encoder0(2, 3);

long encoderPos = -999;

void setup() {
  Serial.begin(9600);
  Serial.println("Encoder Test:");
}

void loop() {
  long newEncoderPos;
  newEncoderPos = encoder0.read();
  if (newEncoderPos != encoderPos) {
    Serial.print("Position = ");
    Serial.print(newEncoderPos);
    Serial.println();
    encoderPos = newEncoderPos;
  }
}

The output I see on the serial monitor - 2 clicks right and two clicks left:

Code:
Encoder Test:
Position = 0
Position = 1
Position = 2
Position = 3
Position = 4
Position = 5
Position = 6
Position = 7
Position = 8
Position = 7
Position = 6
Position = 5
Position = 4
Position = 3
Position = 2
Position = 1
Position = 0

Each click results in 4 lines being printed to the serial monitor.

Circuit is below - only difference is that I am using a HC7414N Schmitt trigger (yes its decoupled !):

Screen Shot 2019-02-28 at 9.05.48 pm.png

If I turn the rotary encoder EXTREMELY slowly between detents I can get it to count up / down in 1 increment.

Any help would be appreciated ! Is it the type of encoder I have that is doing this ? 4 counts per detent ?
 
Is your Bournes encoder an optical quadrature encoder? In which case you might be getting the 4 phases giving one count each. The mechanical detents are also not really perfectly aligned to the optical discs inside an optical encoder which is why I find detent optical encoders difficult to use.
 
Where is the problem? There are different encoders, some with 1, others with 2, and still others with 4 counts per detent. It will be sufficient to adapt your loop() as follows :
Code:
void loop() {
  long newEncoderPos;
  newEncoderPos = (encoder0.read() >> 2); //same effect like divide by 4 but using much less CPU than a division
  if (newEncoderPos != encoderPos) {
    Serial.print("Position = ");
    Serial.print(newEncoderPos);
    Serial.println();
    encoderPos = newEncoderPos;
  }
}
 
Status
Not open for further replies.
Back
Top