I have changed the code and the code doesn't stall anymore.
I also receive different numbers now instead of only zero's.
#define encoder0PinA 2
volatile int val = 0;
volatile int PinB = 3;
volatile int valA;
volatile int valB;
int valold;
void setup()
{
pinMode(encoder0PinA, INPUT);
pinMode(PinB, INPUT);
digitalWrite(encoder0PinA, HIGH);
digitalWrite(PinB, HIGH);
attachInterrupt(0, doEncoderA, CHANGE); // encoder pin on interrupt 0 (pin 2)
Serial.begin (9600);
Serial.print("Encoderpositie = ");
Serial.println(val);
valold = val;
}
void loop()
{
if (valold != val)
{
Serial.print("Encoderpositie = ");
Serial.println(val);
valold = val;
}
}
void doEncoderA()
{
valA = digitalRead(encoder0PinA);
valB = digitalRead(PinB);
if ((valA == HIGH) && (valB == LOW))
{
val = val + 1;
}
else
{
if ((valA == HIGH) && (valB == HIGH))
{
val = val - 1;
}
else
{
if ((valA == LOW) && (valB == HIGH))
{
val = val + 1;
}
else
{
if ((valA == LOW) && (valB == LOW))
{
val = val -1;
}
}}}
}
But the numbers are erratic. The trends seem to be ok (overall rising or falling numbers) but not every step gives the same difference. The differences can be really high (higher then some missed values by the serial monitor). Sometimes the trend can even shortly reverse while rotating in one direction???
Why is it so hard to read an encoder?
EDIT:
I have added two 0,1 uF capacitors between the A and B and ground and it seems to be a bit better now. (maybe it's only better in my mind but I have a feeling it really is a bit better now) Maybe the erratic behaviour is caused by bouncing?