← nunq.net

using the raspberry pi's built-in leds as status lights

published on 07 March 2024

At home, I have to run an SSH tunnel to activate the network connection (for reasons), which is kind of inconvenient since one device on the network always has to stay on and keep this tunnel alive, so I automated it using a Raspberry Pi.

A very simple script I wrote does this on my Raspberry Pi 3b+ and I thought it would be nice to have some sort of connection status indicator. But since I didn’t have any GPIO LEDs lying around, I did some googling and it turns out that you can override the built-in LEDs on the board itself. There is a red LED (PWR) that indicates if the Pi receives enough voltage, and a green LED (ACT) that blinks when the SD card is being accessed.

I wanted to show a green light when the connection is alive and a red light when it somehow dies, so I just created these two little scripts in PATH (make sure they have the executable bit set):

echo 0 > /sys/class/leds/PWR/brightness
echo 1 > /sys/class/leds/ACT/brightness
echo 0 > /sys/class/leds/ACT/brightness
echo 1 > /sys/class/leds/PWR/brightness

However, these commands require root privileges, so add this to the sudoers file to let your regular user run them without a password prompt:

alarm ALL = NOPASSWD: /usr/local/bin/set_red_led, /usr/local/bin/set_green_led
alarm is my username

Here is the full script:

set -eu -o pipefail
SSH_OPTS="-o ServerAliveInterval=4 -o TCPKeepAlive=yes -o PubkeyAuthentication=no"

until sudo /usr/local/bin/set_green_led; sshpass -p "$PASS" ssh "$SSH_OPTS" "$USER@$SERVER"; do
  sudo /usr/local/bin/set_red_led
  echo -e "crashed $? at $(date)\n"
  sleep 5

I usually just run this script automatically after boot in a tmux session using a cronjob:

alarm's crontab
@reboot /home/alarm/init.sh
/usr/bin/tmux new-session -d -s ENTER
/usr/bin/tmux detach -s ENTER
sleep 3
/usr/bin/tmux send-keys -t 0 "cd /home/alarm;./wifi.sh" ENTER

The LEDs also need to be reset at boot:

root's crontab
@reboot echo 0 > /sys/class/leds/ACT/brightness && echo 0 > /sys/class/leds/PWR/brightness

And while we’re at it, I would also recommend setting up NTP time synchronization for the Pi, timedatectl somehow didn’t work for me so I resorted to just doing ntpdate in the root crontab every so often.

You can also find all the files mentioned in this repository.