GPIO Input Not Detecting Button Press #441
-
I am using Pi4J in a Java application on a Raspberry Pi to read button presses from GPIO pin 17. However, the event listener does not trigger when the button is pressed. ///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.slf4j:slf4j-api:1.7.35
//DEPS org.slf4j:slf4j-simple:1.7.35
//DEPS com.pi4j:pi4j-core:2.3.0
//DEPS com.pi4j:pi4j-plugin-raspberrypi:2.3.0
//DEPS com.pi4j:pi4j-plugin-pigpio:2.3.0
import com.pi4j.Pi4J;
import com.pi4j.io.gpio.digital.DigitalInput;
import com.pi4j.io.gpio.digital.DigitalOutput;
import com.pi4j.io.gpio.digital.DigitalState;
import com.pi4j.io.gpio.digital.PullResistance;
import com.pi4j.util.Console;
public class Pi4JMinimalExample {
private static final int PIN_BUTTON = 17;
private static int pressCount = 0;
public static void main(String[] args) throws Exception {
final var console = new Console();
var pi4j = Pi4J.newAutoContext();
var buttonConfig = DigitalInput.newConfigBuilder(pi4j)
.id("button")
.name("Press button")
.address(PIN_BUTTON)
.pull(PullResistance.PULL_DOWN)
.debounce(3000L)
.provider("pigpio-digital-input");
var button = pi4j.create(buttonConfig);
button.addListener(e -> {
if (e.state() == DigitalState.LOW) {
pressCount++;
console.println("Button was pressed for the " + pressCount + "th time");
}
});
while (pressCount < 5) {
console.println("Press Count: " + pressCount);
Thread.sleep(1000 / (pressCount + 1));
}
pi4j.shutdown();
}
} Here is the output of the script:
If I terminate this program and run python script to check if that works I get the console logs for the button press as expected. #!/usr/bin/env python3
import gpiozero
import time
import logging
# Logging setup
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def main():
# Dictionary to hold GPIO pins being monitored
gpio_pins = {}
# Specify GPIO pins to test (modify as needed for your hardware)
pins_to_test = range(2, 28) # Example range for Raspberry Pi GPIO pins
# Initialize GPIO pins as Button objects and add event listeners
for pin in pins_to_test:
try:
gpio_device = gpiozero.Button(pin, pull_up=True)
gpio_device.when_pressed = lambda pin=pin: logging.info(f"GPIO Pin {pin} triggered (HIGH -> LOW)")
gpio_device.when_released = lambda pin=pin: logging.info(f"GPIO Pin {pin} released (LOW -> HIGH)")
gpio_pins[pin] = gpio_device
logging.info(f"Monitoring GPIO Pin {pin}")
except gpiozero.BadPinFactory:
logging.error(f"Failed to initialize GPIO Pin {pin}. It might be reserved or unavailable.")
except Exception as e:
logging.error(f"Error initializing GPIO Pin {pin}: {e}")
logging.info("GPIO Diagnostics Tool is running. Press CTRL+C to exit.")
try:
while True:
time.sleep(0.1) # Prevent CPU overuse
except KeyboardInterrupt:
logging.info("GPIO Diagnostics Tool has been stopped.")
finally:
# Clean up GPIO
for device in gpio_pins.values():
device.close()
logging.info("GPIO pins have been cleaned up.")
if __name__ == "__main__":
main() Here is my Raspberry Pi information:
Any ideas where is the problem? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
I'm not quite sure, but in the python program you are registering all the pins and logging their state changes. Perhaps you are using the wrong pin in Java? Since you are using BCM Pin 17, is your button connected to physical pin 11? See the chart here: https://pinout.xyz/pinout/pin11_gpio17/ Also see the following documentation page: https://www.pi4j.com/getting-started/understanding-the-pins/ |
Beta Was this translation helpful? Give feedback.
-
I copied your program to my Pi5 . As this is a Pi5 i had to change to use the gpiod digital provider //DEPS org.slf4j:slf4j-api:1.7.35 Your test case functions correctly. As the program test for the button being low it is when when you move gpio 17 to the ground terminal that the count is incremented. |
Beta Was this translation helpful? Give feedback.
-
I mentioned earlier the way your prgm is written the GPIO listener tests for a LOW. If you change this test to HIGH, I think you will see the button press completing a connection to 3.3v will be a 'Button Press' |
Beta Was this translation helpful? Give feedback.
-
@moreorover Isn't it possibly to do with the pullup/down? Have you tried changing it? Especially since your python program is using Pullup. |
Beta Was this translation helpful? Give feedback.
@moreorover Isn't it possibly to do with the pullup/down? Have you tried changing it? Especially since your python program is using Pullup.