Raspberry Pi GPIO Start-up Script

On powering/reset of the Raspberry Pi connected to a relay board, the state of the relays needs to be defined or they just sit in limbo until their first use, this might be fine in some application but not others..

For my Raspberry Pi  aquarium system, the ‘original‘ Web UI does have a script on loading the webpage to define the pin modes but if there is a power cut and the RPi is restarted, we need these values set and activated when the RPi boots in case nobody loads the piTank webpage directly after a reboot – thus critical components wont be turned on.

The fix to this issue is gpiobootscript.sh

GPIO Readall

You will need to change the pin numbers below to what you need, This script is controlling an 8 way relay and 1 pin for a temperature  probe. I am using pins 0-6 and pin 21 for the relays with pin 7 being used for the temp probes.

IMPORTANT: The pin numbers below are GPIO.X and not bcm or board.

As this script is being run before login you will need to enclose the absolute paths of your folder structure as the OS might not be fully aware of the ‘short’ paths within the boot process.


# this script is run on boot of the Pi to set 
# the initial state of the GPIO pins before the # first loading of index.php

#set gpio.7 to input mode
/usr/local/bin/gpio mode 7 in;

#set mode to output
for i in 0 1 2 3 4 5 6 21; do /usr/local/bin/gpio mode $i out; done;

#turn OFF lights/rain/spare
for i in 0 1 2 3 4 21; do /usr/local/bin/gpio write $i 1; done;

#turn ON filter and heater
for i in 5 6; do /usr/local/bin/gpio write $i 0; done;

This script is saved in the Pi’s home folder located at /home/pi/scripts/.  Set the file as executable (seen as this is only a ‘.local’ thing I give the file all permissions…)

Define when the file is be executed using Crontab, this file is to be run using the ‘@reboot’ command (which also works for the initial boot).

As this file is to be run before the actual login, Crontab needs to run as ‘sudo’;

sudo crontab -e

Add the below string to the last line of the file that opens using the above command. Make sure there are no empty lines at the bottom of the file.

@reboot bash /home/pi/scripts/gpiobootscript.sh &

To save the change of crontab use Ctrl + O

To exit the text editor after saving the file use Ctrl + X

Reboot the Pi.

Using the ‘GPIO readall’ command, check to see if the outcome is as expected – input ports are set how you want and out ports set with the state you wanted.

One thought on “Raspberry Pi GPIO Start-up Script”

Leave a Reply

Your email address will not be published. Required fields are marked *