Class Button

  • All Implemented Interfaces:
    DeviceInterface, DigitalInputDeviceInterface, DeviceEventConsumer<DigitalInputEvent>, Closeable, AutoCloseable, Consumer<DigitalInputEvent>

    public class Button
    extends DigitalInputDevice

    Provides push button related utility methods.

    From the ButtonTest example:

    Button
     
     try (Button button = new Button(inputPin, GpioPullUpDown.PULL_UP)) {
       button.addListener(event -> Logger.debug("Event: {}", event));
       Logger.debug("Waiting for 10s - *** Press the button connected to input pin " + inputPin + " ***");
       SleepUtil.sleepSeconds(10);
     }
     
     

    Controlling an LED with a button ButtonControlledLed:

    Button controlled LED
     
     try (Button button = new Button(buttonPin, GpioPullUpDown.PULL_UP); LED led = new LED(ledPin)) {
       button.whenPressed(nanoTime -> led::on);
       button.whenReleased(nanoTime -> led::off);
       Logger.info("Waiting for 10s - *** Press the button connected to pin {} ***", Integer.valueOf(buttonPin));
       SleepUtil.sleepSeconds(10);
     }
     
     
    • Constructor Detail

      • Button

        public Button​(int gpio)
               throws RuntimeIOException
        Pull up / down configuration defaults to NONE.
        Parameters:
        gpio - GPIO to which the button is connected.
        Throws:
        RuntimeIOException - If an I/O error occurred.
      • Button

        public Button​(int gpio,
                      GpioPullUpDown pud)
               throws RuntimeIOException
        Parameters:
        gpio - GPIO to which the button is connected.
        pud - Pull up / down configuration (NONE, PULL_UP, PULL_DOWN).
        Throws:
        RuntimeIOException - If an I/O error occurred.
    • Method Detail

      • isPressed

        public boolean isPressed()
        Get the current state.
        Returns:
        Return true if the button is currently pressed.
      • isReleased

        public boolean isReleased()
        Get the current state.
        Returns:
        Return true if the button is currently released.
      • whenPressed

        public void whenPressed​(LongConsumer consumer)
        Action to perform when the button is pressed.
        Parameters:
        consumer - Calllback function to invoke when pressed (long parameter is nanoseconds time).
      • whenReleased

        public void whenReleased​(LongConsumer consumer)
        Action to perform when the button is released.
        Parameters:
        consumer - Calllback function to invoke when pressed (long parameter is nanoseconds time).