The most upvoted advice on Raspberry Pi Stack Exchange is also the simplest: don't just pull the plug. Power loss during writes can damage the SD card and the file system. With a keyboard or SSH:
sudo shutdown -h now
Wait until the activity LED stops before removing power. Headless devices in the field need a way to do this without SSH.
Raspberry Pi 5: use the power button
- A short press on the onboard power button starts a clean shutdown on Raspberry Pi OS Lite (the desktop shows a menu; press twice to shut down).
- Pressing it again while the board is off but powered starts it.
- For a case-mounted button, solder a normally-open momentary switch to the J2 pads (between the RTC battery connector and the board edge). It acts like the onboard button.
- A Pi 5 still draws some power when off. See the power supply item for
POWER_OFF_ON_HALT=1.
Earlier models: the gpio-shutdown overlay
Add to config.txt (/boot/firmware/config.txt on current Raspberry Pi OS):
dtoverlay=gpio-shutdown
Wire a momentary button between GPIO3 (pin 5) and GND (pin 6). The overlay makes the pin a power key; systemd-logind shuts down when it's pressed. Because the board wakes when GPIO3 is pulled low, the same button powers it back on. GPIO3 has a fixed pull-up on the board, so no resistor is needed.
Conflict: GPIO3 is the I2C clock
GPIO2/GPIO3 are the default I2C bus (SDA/SCL). With I2C sensors on that bus, the button and the bus share one wire and get in each other's way. Use another pin:
dtoverlay=gpio-shutdown,gpio_pin=17
Then the button only shuts down; power-up by GPIO3 is no longer available through that button.
Other parameters: active_low, gpio_pull (off/down/up) and debounce (default 100 ms).
For devices that lose power anyway
A shutdown button doesn't help against power cuts. Combine it with the measures in the SD card corruption item (good power supply, read-only or overlay root file system, SSD/NVMe on Pi 5), or add a UPS HAT that triggers a shutdown.
Sources: Stack Exchange (CC BY-SA 4.0) — see links.