Skip to content

Instantly share code, notes, and snippets.

@kachurovskiy
Last active November 16, 2021 17:05
Show Gist options
  • Save kachurovskiy/c819c01b8b8bfd15e7e5b4e77eea91d0 to your computer and use it in GitHub Desktop.
Save kachurovskiy/c819c01b8b8bfd15e7e5b4e77eea91d0 to your computer and use it in GitHub Desktop.
Pi4j rotary encoder reading
// Pin pinA - CLK pin,
// Pin pinB - DT pin
// rotate(int i) - callback receiving -1 or 1
inputA = gpio.provisionDigitalInputPin(pinA, "PinA", PinPullResistance.PULL_UP);
inputB = gpio.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) {
rotate(b == a ? -1 : 1);
lastA = a;
}
}
});
@zipCoder933
Copy link

How do I read the encoder value?

@kachurovskiy
Copy link
Author

Encoder is a relative device, it doesn't store an absolute value. In your callback code, you can yourself store an int that starts at 0 and increment/decrement it each time it triggers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment