Our team is using the Raspberry Pi. The standard Raspbian OS runs on the device. All code is written in Java.
We are using the Java library package (pi4j). The package listens to the voltage change in GPIO pins.
I want to make Java shut down the Raspberry Pi whenever the Shutdown
button is clicked.
Question: how to shut down the Raspberry Pi using Java?
mercury0114mercury0114
asked Feb 11, 2016 at 13:15
1 Answer 1
There looks to be a complete Java example using pi4j here:
import java.io.IOException;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListener;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
public class Shutdown {
public static void main(String[] args) throws InterruptedException {
final GpioController gpio = GpioFactory.getInstance();
final GpioPinDigitalInput input = gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);
input.addListener(new GpioPinListenerDigital() {
@Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
System.out.println(event.getPin() + " = " + event.getState());
//Wenn der Pin#2 auf High geht, fährt sich der Rasperry Pi runter.
if (input.getState()==PinState.HIGH) {
try {
Process p = Runtime.getRuntime().exec("sudo shutdown -h now");
p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
});
while (true) {
Thread.sleep(1000);
}
}
}
answered Feb 11, 2016 at 13:24
-
2you could leave the whole pi4j part out here. Even though Goldilocks answered in a comment, all that is relevant here is
Runtime.getRuntime().exec("sudo shutdown -h now");
Havnar– Havnar2016年02月11日 13:37:10 +00:00Commented Feb 11, 2016 at 13:37
lang-java
exec("shutdown")
, see here: stackoverflow.com/a/25666/1151724Runtime.getRuntime().exec("sudo shutdown
as it's more portable