john2016:
hi,am testing the rotary encoder and determining its no of turns, am using this codeint pinA = 3; // Connected to CLK on KY-040
int pinB = 4; // Connected to DT on KY-040
int encoderPosCount = 0;
int pinALast;
int aVal;
boolean bCW;
void setup() {
pinMode (pinA,INPUT);
pinMode (pinB,INPUT);
/* Read Pin A
Whatever state it's in will reflect the last position
*/
pinALast = digitalRead(pinA);
Serial.begin (9600);
}
void loop() {
aVal = digitalRead(pinA);
if (aVal != pinALast){ // Means the knob is rotating
// if the knob is rotating, we need to determine direction
// We do that by reading pin B.
if (digitalRead(pinB) != aVal) { // Means pin A Changed first - We're Rotating Clockwise
encoderPosCount ++;
bCW = true;
} else {// Otherwise B changed first and we're moving CCW
bCW = false;
encoderPosCount--;
}
Serial.print ("Rotated: ");
if (bCW){
Serial.println ("clockwise");
}else{
Serial.println("counterclockwise");
}
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);
}
pinALast = aVal;
}
but the issue is for every slight turn, two increment adds up instead of one on both CW and CCW, is it because of debounce? ive also tested using a 100nf caps in parallel to digital input where clk & dt is inserted but still same issue, the push button works fine which is "NO" on pressing it closes circuit and resets the arduino, now am testing blink without delay on lcd...
Your test code just simply won't work. Yayaya, this is also saying that the demo code in your link doesn't work in the first place.
The bugs is here...
...
Serial.print ("Rotated: ");
if (bCW){
Serial.println ("clockwise");
}else{
Serial.println("counterclockwise");
}
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);
...
For the encoder to work, you need to test the pin state at a rate way faster than that of the encoder pins turning on/off. Serial communication is a very slow operation. Having it in sync with the test code, you are missing a whole lot of the encoder state change information while busy doing serial communication.
Use the code Code Archives - Arduino Learning that Raschemmel suggested. It should work like a charm. Be reminded that there are just a handful of hardware interrupt pins on an Arduino boards, please make sure you are using the interrupt pins for the job. For details, see https://www.arduino.cc/en/Reference/AttachInterrupt .