One of the most common hurdles to running a Raspberry Pi headless is having a way to shut it down gracefully.

Fortunately, there is a little-known built-in toolkit for doing exactly that.

Foreword: This approach uses GPIO3, physical pin 5. Unfortunately, this pin is also used for I2C, so some adjustments must be made when I2C is enabled (Not necessarily “in use”).

Starting in mid-2017, Raspibian has included a Device Tree Overlay (dtoverlay) called “gpio-shutdown”. Deep in the Linux kernel, this essentially performs a halt command when called.

Device Tree Overlays are declared in /boot/config.txt .

If you open the README file at /boot/overlays/README , it has a section for the gpio-shutdown overlay starting at line 1430 and ending at line 1494.

Default Config: When I2C is not enabled

By default, adding dtoverlay=gpio-shutdown to /boot/config.txt will add a kernel call to GPIO3, Physical Pin 5. Connecting this pin to ground will queue the halt command in the Linux OS, performing a graceful shutdown. Connecting this pin to ground again while the pi is halted will wake the Pi and perform a normal boot-up, just as a manual power cycle would do.

Alternate config: When I2C is enabled

When I2C is enabled, GPIO3 is not available to the kernel. As a result, the default pin assignment must be changed. If the overlay is left as default, grounding GPIO3 has no affect on the system.

dtoverlay=gpio-shutdown,gpio_pin=n , where n represents the GPIO pin number (not the physical pin number).

The pin you choose for this may vary depending on any HATs you are using and/or what other communication modes are in use. However, if you want to avoid all conflicts, the selection of non-communication pins is short: 17, 27, 22, 23, 24, 25, 5, 6, 16, and 26.
Unfortunately, the start pin assignment cannot be changed away from GPIO3. There are 2 ways to work around this:

1) You can have 2 buttons. One exclusively for start on GPIO3 and one exclusively for shutdown on a pin of your choosing.
2) You can use a DPDT button. One side will be for GPIO3 to start and one side will be for a pin of your choosing for shutdown.

References:

Raspberry Pi Power-Up and Shutdown with a Physical Button – Embedded Computing Design

Raspberry pi powerdown and powerup button

Raspberry Pi hardware – Raspberry Pi Documentation

Raspberry Pi GPIO Pin Map
Raspberry Pi GPIO Pin Map