Hey. I want to use an encoder to increment a counter when i rotate the encoder handle. I have encoder module HW-040:
\
It already comes with pre-installed pull ups on A and B data lines.
I was trying to find as simple as possible code to do that and managed to find the code above. It seems to work alright except that sometimes it prints multiple lines at once when I make a single rotation on my encoder:
As you can see from my serial monitor above, I am getting multiple prints (I just barely touched the encoder and rotated it by only 1 position). I should be getting Position:1 and instead is bouncing back and forth for multiple times. Could someone suggest a simple solution to this problem?
\
It already comes with pre-installed pull ups on A and B data lines.
Code:
#define outputB 35 // DATA signal
#define outputA 34 // CLOCK signal
int counter = 0;
int aState;
int aLastState;
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (115200);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
}
void loop() {
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter ++;
} else {
counter --;
}
Serial.print("Position: ");
Serial.println(counter);
}
aLastState = aState; // Updates the previous state of the outputA with the current state
}
As you can see from my serial monitor above, I am getting multiple prints (I just barely touched the encoder and rotated it by only 1 position). I should be getting Position:1 and instead is bouncing back and forth for multiple times. Could someone suggest a simple solution to this problem?
Last edited: