Preventing SD Card Corruption on a Raspberry Pi

Author: John Gauthier

The Problem:

One vulnerability of the Raspberry Pi is its susceptibility to micro-SD card corruption. Power interruption during a SD card write is the main culprit. Such interruptions can corrupt the file or even make the entire micro-SD card unusable. The problem is worst in designs where the Raspberry Pi runs headless, leaving no convenient way to request a graceful shutdown.

The Solution:

The solution consists of four parts: a Python script, a service, a shell script and a switch. The code and installation instructions are at https://github.com/zizumara/GPIOshutdown.

How it works:

The GPIOshutdown Python script, when run as a service, provides a way to initiate a graceful shutdown of the operating system by grounding one of its GPIO pins through a switch. The script monitors pin #26 by default. The value of SHUTDOWN_PIN in GPIOshutdown.py controls the monitored pin. When launched, the script will wait for a fixed period before beginning to monitor the GPIO pin. This is a failsafe to allow the user to login via SSH and stop the service to prevent continuous rebooting if the GPIO pin is damaged or otherwise accidentally shorted. The delay defaults to 180 seconds but is modifiable by editing the value of ARMING_DELAY in GPIOshutdown.py. Marking the switch to indicate which position initiates shutdown is highly recommended. In this application, shutdown occurs when the switch is closed.