Set the state of the GPIOs at the boot of Raspberry Pi (/sys/class/gpio method)

Upon reboot, the Raspberry Pi automatically sets the GPIO state to "in". With this script we can set our personalized state.

In order to have a command or program run when the Pi boots, you can add commands to the rc.local file. This is especially useful if you want to be able to plug your Pi in to power headless, and have it run a program without configuration or a manual start.

On your Pi, edit the file /etc/rc.local using the editor of your choice. For example:

sudo nano /etc/rc.local

 

Add commands below the comment, but leave the line exit 0 at the end, then save the file and exit.
Insert the content of the script following this example (you have to adapt it to your needs).

 

Finally save the content of the file pressing CTRL + X (to exit from nano), respond “Yes” at the request of saving, then confirm with ENTER.

#!/bin/sh -e
#
# rc.local
#

echo "8" > /sys/class/gpio/export
sleep 0.1
echo "out" > /sys/class/gpio/gpio8/direction
echo "0" > /sys/class/gpio/gpio8/value
sleep 0.1

echo "9" > /sys/class/gpio/export
sleep 0.1
echo "out" > /sys/class/gpio/gpio9/direction
echo "0" > /sys/class/gpio/gpio9/value
sleep 0.1

echo "10" > /sys/class/gpio/export
sleep 0.1
echo "out" > /sys/class/gpio/gpio10/direction
echo "1" > /sys/class/gpio/gpio10/value
sleep 0.1

echo "11" > /sys/class/gpio/export
sleep 0.1
echo "out" > /sys/class/gpio/gpio11/direction
echo "1" > /sys/class/gpio/gpio11/value

exit 0

Example script

Set the state of the GPIOs at the boot of Raspberry Pi (config.txt method)

This method allows you to set the GPIO mode at startup.

If the /sys/class/gpio method does not work you can use the new method that uses the config.txt file

Edit the file by typing in the terminal:
sudo nano /boot/firmware/config.txt

Add the following to the end of the file:
gpio=8=op,dl

Finally save the content of the file pressing CTRL + X (to exit from nano), respond “Yes” at the request of saving, then confirm with ENTER. Now reboot the device.

You can find more information here: https://www.raspberrypi.com/documentation/computers/config_txt.html#gpio-control

# Set GPIO8 to be an output
gpio=8=op,dl

# Set GPIO9 to be an output set to 1
gpio=9=op,dh

# Set GPIO10 and GPIO12 to be an output set to 1
gpio=10,12=op,dh

# Set GPIO15 to GPIO18 to be an output set to 1
gpio=15-18=op,dh

Example

Nano shortkeys:

CTRL+6: Enable text selection (Alternative: ALT+SHIFT+A)

ALT+6: Copy (Alternative: ALT+SHIFT+6)

CTRL+U: Paste