I thought I had found what I was looking for with a rotary encoder, but it is giving me a lot of headache =
.
I spend a few nights already reading many posts about how they work, debouncing them, etc. I have tried out many configurations, with internal pull ups, with different capacitors, with different encoders I have and with the many sketches I have come across. Unfortunately I have not been able to solve my problem. That is, that the encoders works well in one direction (counting up), but not the other direction, when it counts up and down and up and down, etc. Somehow I have a feeling it is not a problem of bouncing, because one direction works very well.
I connected the encoder to pin2 and 3 of the arduino and to ground (middle pin). When I run the sketch (below), I get the following reading:
start
A:0 B:0 pos:102 Here I turn it in the working direction
A:1 B:1 pos:103
A:0 B:0 pos:104
A:1 B:1 pos:105
A:0 B:0 pos:106
A:1 B:1 pos:107
A:0 B:0 pos:108
A:1 B:1 pos:109
A:0 B:0 pos:110
A:1 B:1 pos:111
A:0 B:0 pos:112
A:1 B:1 pos:113
A:0 B:0 pos:114
A:1 B:1 pos:115
A:0 B:0 pos:116
A:1 B:1 pos:117
A:0 B:0 pos:118
A:1 B:1 pos:119
A:0 B:0 pos:120
A:1 B:1 pos:121
A:0 B:0 pos:122 Untill here it works perfect, but now I turn it the other direction
A:1 B:0 pos:121
A:0 B:0 pos:122
A:1 B:0 pos:121
A:0 B:0 pos:122
A:1 B:0 pos:121
A:0 B:0 pos:122
A:1 B:0 pos:121
A:0 B:0 pos:122
A:0 B:0 pos:123
A:1 B:1 pos:124
A:0 B:0 pos:125
A:1 B:0 pos:124
A:0 B:0 pos:125
A:1 B:0 pos:124
A:0 B:0 pos:125
A:1 B:0 pos:124
A:0 B:0 pos:125
A:1 B:0 pos:124
A:0 B:0 pos:125
A:1 B:0 pos:124
A:0 B:0 pos:125
A:1 B:0 pos:124
A:0 B:0 pos:125
A:0 B:0 pos:126
A:1 B:1 pos:127
A:0 B:0 pos:128
A:1 B:0 pos:127
A:0 B:0 pos:128
A:1 B:0 pos:127
A:0 B:0 pos:128
A:1 B:0 pos:127
A:0 B:0 pos:128
A:1 B:0 pos:127
A:0 B:0 pos:128
A:1 B:1 pos:129
When I turned it in the other direction, pin B kept on being read as 0 (with the odd 1). Does anyone has any idea what causes this and how to solve it? Interestingly, when I switch the connection to pin 2 and 3, I get constant 1's for pin B in stead of 0's in the non-accumulation direction.
Thanks, Rutger
p.s. I had a look at optical encoders, but they are a bit too expensive for me, so I hope I can solve it with the ones I have.
#define encoder0PinA 2
#define encoder0PinB 3
volatile unsigned int encoder0Pos = 100;
void setup() {
pinMode(encoder0PinA, INPUT);
digitalWrite(encoder0PinA, HIGH);
pinMode(encoder0PinB, INPUT);
digitalWrite(encoder0PinB, HIGH);
attachInterrupt(0, doEncoder, CHANGE);
Serial.begin (9600);
Serial.println("start"); }
void loop(){delay (100);}
void doEncoder() {
int A = digitalRead(encoder0PinA);
int B = digitalRead(encoder0PinB);
if (A == B) {encoder0Pos++; }
else {encoder0Pos--;}
Serial.print ("A:");
Serial.print (A);
Serial.print (" B:");
Serial.print (B);
Serial.print (" pos:");
Serial.println (encoder0Pos);}