I bought a rotary encoder from sparkfun (Rotary Encoder - COM-09117 - SparkFun Electronics). I have never worked with rotary, first I thought that it was like a potentiometer, but it doesn't. So my question is: Is it possible to know the direction of the encoder?
I want to built a weather vane using this encoder as a way to know the direction of the wind. (N,S,E,W).
Yes, in fact the code is working good, the encoder is counting from 0 to 255, if I turn the knob clockwise and it reverses if I go counterclockwise. First problem is that "almost" ,and I say almost 'cause is not always, every time it counts +4 steps or -4 depending the direction. Using this code I could know if the weather vane is turning clockwise or counter clockwise, but I can't get the actually position of the knob to determinate north, south, east, west.
but I can't get the actually position of the knob to determinate north, south, east, west.
Why not? Put a knob with a pointer on it on the encoder. Rotate the encoder one complete turn. You should see the counter count up to some value for one complete turn. If the counter goes back to 0 before one complete rotation, change the type from int8_t to int16_t. You'll need to disable interrupts before updating counter, and enable them again afterwards, to that you don't get an interrupt in the middle of updating counter.
The encoder you describe is not really suitable as it's a 2 bit encoder (no pun intended) you can only count pulses when the shaft is turned and depending on A/B high/low sequence what direction it was turned. What you need is at least a 4 bit encoder, this would give you 16 distinct values so a certain shaft position would always return the same value.
This is more along the lines of what you looking for (see truth table in datasheet) but not really sturdy enough for a weather vane. Try looking for a metal equivilent
You would probably be better off with something along the lines of a magnet mounted on the shaft and a ring of hall-effect sensors around it. As the shaft rotates it triggers a different hall effect sensor. The smaller and more numerous the sensors the more accurate the direction can be determined.