Hi,
Having some good success with the pi4j library and have created a couple of working examples using temperature and motion sensors, thanks for all the work done on it to date.
My latest bit of code is around using a rotary encoder. Based on some C code found in
http://bildr.org/2012/08/rotary-encoder-arduino/ I have been able to get some reasonably reliable readings and have been impressed with the very low overhead the whole thing requires when running a couple of listeners to track changes in the state of the two encoder inputs (much better than a python library I used to prove things were working).
Was wondering if anyone else has attempted to code something similar using the pi4j library as I would like to compare notes, mostly because whilst the results are reliable, the value tends to increase by 2 on ever turn which I could live with if every now and again it didn't increase by just 1 which is the expected increment. This might just been a factor of how the two inputs are being triggered or the low-level native access being used to monitor the GPIO.
The crux of the code is the following method which is called by a single listener added to both inputA and inputB. The encoderValue provides the current reading of the encoder at any point in time:
/**
*/
private void updateEncoder() {
int MSB = inputA.getState().getValue(); //MSB = most significant bit
int LSB = inputB.getState().getValue(); //LSB = least significant bit
int encoded = (MSB << 1) | LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value
switch (sum) {
case 2:
case 4:
case 11:
case 13:
encoderValue++;
break;
case 1:
case 7:
case 8:
case 14:
encoderValue--;
}
lastEncoded = encoded; //store this value for next time
}
Thanks
Mark