Thank you very much guys! I learnt alot from your examples, i specially liked cattledog's version by using bitread, it was fast enough for my aplication, which was reading the position of the steering wheel on my full scale 3.3l V6 1,8 ton RC car
The optical encoder is HN3806.
cattledog:
Good job with the code tags on your first post.
You can read the encoder to count 1,2, or 4 of the available quadrature transitions. The resolution is a design choice for you to make. Robin2 suggests a routine to read 1 of the 4 transitions. Your original code was to count all 4 transitions so I have kept with that approach although the resolution sounds high(but achievable) for 330rpm. What is your application, and what are you going to do with the count?There are many things wrong with your code. The switching of interrupt modes(RISING/FALLING) is wrong and can lead to problems. Use CHANGE and read the pin.
if (B = 1) {You have several statements like this, which are wrong for two reasons. You must use == for the comparison, and you need to read the value of the B pin with digitalRead(B); There are faster routines than digitalRead() and I have used one of them in the code below.
if (count != count)To control you output, you need to use count and previous count, and assign the value of count to previousCount after the comparison. You also need to briefly stop the interrupts to grab a value of count which will not change as it is being read.
Here's a modified version of your code which addresses these issues.
const byte encoderPinA = 2;//outputA digital pin2
const byte encoderPinB = 3;//outoutB digital pin3
volatile int count = 0;
int protectedCount = 0;
int previousCount = 0;
#define readA bitRead(PIND,2)//faster than digitalRead()
#define readB bitRead(PIND,3)//faster than digitalRead()
void setup() {
Serial.begin (115200);
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(encoderPinA), isrA, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), isrB, CHANGE);
}
void loop() {
noInterrupts();
protectedCount = count;
interrupts();
if(protectedCount != previousCount) {
Serial.println(protectedCount);
}
previousCount = protectedCount;
}
void isrA() {
if(readB != readA) {
count ++;
} else {
count --;
}
}
void isrB() {
if (readA == readB) {
count ++;
} else {
count --;
}
}