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

published on 7th 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):

/usr/local/bin/set_green_led copy
1#!/bin/bash
2echo 0 > /sys/class/leds/PWR/brightness
3echo 1 > /sys/class/leds/ACT/brightness
/usr/local/bin/set_red_led copy
1#!/bin/bash
2echo 0 > /sys/class/leds/ACT/brightness
3echo 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:

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

Here is the full script:

/home/alarm/wifi.sh copy
 1#!/bin/bash
 2set -eu -o pipefail
 3PASS=""
 4USER=""
 5SERVER=""
 6SSH_OPTS="-o ServerAliveInterval=4 -o TCPKeepAlive=yes -o PubkeyAuthentication=no"
 7
 8until sudo /usr/local/bin/set_green_led; sshpass -p "$PASS" ssh "$SSH_OPTS" "$USER@$SERVER"; do
 9  sudo /usr/local/bin/set_red_led
10  echo -e "crashed $? at $(date)\n"
11  sleep 5
12done

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

alarm's crontab copy
1@reboot /home/alarm/init.sh
/home/alarm/init.sh copy
1/usr/bin/tmux new-session -d -s ENTER
2/usr/bin/tmux detach -s ENTER
3sleep 3
4/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 copy
1@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.