Raspberry Pi: CPU usage monitoring using GPIO

Cet article est également disponible en français: Raspberry Pi: monitoring de l’utilisation CPU grâce au GPIO

If you’re the owner of a Raspberry Pi, your surely know what are those vertical pins.

By grabbing around some dels, I’ve been able to play with them, using scripts. Using some bash commands, it is very simple to switch on or off a del (connected to gpio4 for example):

# Has to be done once at the begging of the script
echo "4" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/gpio4/direction

# Switch the del on:
echo "1" > /sys/class/gpio/gpio4/value
# Switch the del off:
echo "0" > /sys/class/gpio/gpio4/value

Quite simple, isn’t it ? Using those commands, it is very simple to do a lot of things, like the Raspberry Pi’s CPU usage monitoring with several leds ! First of all, here is a quick view of what we are going to do (the video shows 3 dels, but the script allows you to use 5 dels):

It is actually very simple. Here are the main commands used in this scripts (available at the end of the article):

# At the begining of the scripts, we'll be declaring all the dels
# "2> /dev/null" allow you to mask the errors
echo "4" > /sys/class/gpio/export 2> /dev/null
# Main functions of the script:
function ON { [...] }
function OFF { [...] }
function allON { [...] }
function allOFF { [...] }
function flash { [...] }
while [ ${i} -lt 200 ]
# Processing the current CPU usage
idle=`vmstat 2 3 | tail -n1 | sed "s/  */ /g [...]

Be careful: the number of the del is actually its final physical order, (1 to 5 if you have 5 leds), not the GPIO number. Indeed, the GPIO number is the number of the pin the del is plugged on. You have to adapt the code depending on how maning dels are plugged on your Raspberry. If you think that any enhancement could be done on this script, don’t hesitate to post it in comment !

The hardest thing wich had to be done in this script was to find the current CPU usage. In this script, we grab the idle value.

To use this script, all you have to do is to copy it in a .sh file on your Raspberry, and execute it using the following command:

sudo ./script.sh

Grab the script on Pastebin

(source image 1)