Forked from kachurovskiy/PI4JRotaryEncoderReading.java
Last active
November 16, 2021 17:08
-
-
Save zipCoder933/0ec496d7eb6f14883f33e7639f3f2dab to your computer and use it in GitHub Desktop.
Pi4j rotary encoder reading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @author zipCoder933 | |
*/ | |
public class RotaryEncoder { | |
/** | |
* @return the encoder value | |
*/ | |
public final int getValue() { | |
return value; | |
} | |
private int value; | |
/** | |
* callback receiving -1 or 1 | |
* | |
* @param i | |
*/ | |
public void onRotate(int i) { | |
} | |
public RotaryEncoder(Pin pinA, Pin pinB) { | |
init(pinA, pinB, 0); | |
} | |
public RotaryEncoder(Pin pinA, Pin pinB, int initialValue) { | |
init(pinA, pinB, initialValue); | |
} | |
private void init(Pin pinA, Pin pinB, int initialValue) { | |
value = initialValue; | |
GpioPinDigitalInput inputA = GpioFactory.getInstance().provisionDigitalInputPin(pinA, "PinA", PinPullResistance.PULL_UP); | |
GpioPinDigitalInput inputB = GpioFactory.getInstance().provisionDigitalInputPin(pinB, "PinB", PinPullResistance.PULL_UP); | |
inputA.addListener(new GpioPinListenerDigital() { | |
int lastA; | |
@Override | |
public synchronized void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent arg0) { | |
int a = inputA.getState().getValue(); | |
int b = inputB.getState().getValue(); | |
if (lastA != a) { | |
value += (b == a ? -1 : 1); | |
onRotate(b == a ? -1 : 1); | |
lastA = a; | |
} | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I put kachurovskiy's code into a class. The class can be instantiated.