我正在为覆盆子pi创建一个基本的java程序,当按下按钮时,按钮编号和按下它。我的2个代码类在下面,但正如您从输出中看到的那样,有时它会显示按钮被按下两次一次。
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
public class Button {
private GpioPinDigitalInput buttonPin;
boolean pressed = false;
public Button(GpioController gpio, Pin pin) {
// Provision the pin
buttonPin = gpio.provisionDigitalInputPin(pin, PinPullResistance.PULL_UP);
// Add a listener to the button
buttonPin.addListener(new GpioPinListenerDigital() {
@Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
if(event.getState().isLow()) {
pressed = true;
// When Button is not pressed
GPIOTest.print(event.getPin() + ", pressed");
}
}
});
}
}
第2课
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.util.Console;
public class GPIOTest {
private final static Console console = new Console();
private final static GpioController gpio = GpioFactory.getInstance();
private static Pin[] pinList = { RaspiPin.GPIO_00,
RaspiPin.GPIO_01,
RaspiPin.GPIO_02,
RaspiPin.GPIO_03,
RaspiPin.GPIO_04};
public static void main(String args[]) throws InterruptedException {
console.title("Test GPIO");
console.promptForExit();
for (Pin pin : pinList) {
new Button(gpio, pin);
}
console.waitForExit();
}
public static void print(String message) {
console.println(message);
}
}
答案 0 :(得分:0)
可能是一个去抖动的问题。在按下按钮之前按下按钮可能会接地,拉高并重新接地几次,然后开关进入接地状态。
有几种常见的去抖算法。您可以在第一次更改后多次阅读状态,并且仅报告"按下"当几个" 0"在很短的延迟后报告连续。如果你是谷歌的话,还有更复杂的算法。
祝你好运。