1

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?

asked Feb 11, 2016 at 13:15
3
  • Unconfirmed suggestion here. Commented Feb 11, 2016 at 13:20
  • 1
    There is no java specific method for this beyond just exec("shutdown"), see here: stackoverflow.com/a/25666/1151724 Commented Feb 11, 2016 at 13:34
  • Goldilocs' answer is better than Runtime.getRuntime().exec("sudo shutdown as it's more portable Commented Feb 11, 2016 at 13:36

1 Answer 1

3

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
1
  • 2
    you 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"); Commented Feb 11, 2016 at 13:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.