Raspberry Pi – Ping IP Address and Toggle LED

The following script is for monitoring if an IP address is reachable or not. If it becomes unavailable the script will turn on a LED that is plugged into one of the GPIO pins of the Raspberry Pi. View pinout here

Script

#!/bin/bash
# Script to ping ip address and turn on LED on if device is unreachable.
                                                                                                                                                                                                 nPin="18"  # Change if GPIO pin is different                                                                                                     
ledPin="gpio${nPin}"                                                                                                                                                                                                                            toPing="8.8.8.8"  # Change to address you want to ping

echo "${nPin}" > /sys/class/gpio/export
echo "out" > /sys/class/gpio/${ledPin}/direction

if ( fping -r1 $toPing | grep -v alive ); then
         echo "Internet unreachable"
         # Turn on LED
         echo "1" > /sys/class/gpio/${ledPin}/value
 else
         # Turn off LED 
         echo "0" > /sys/class/gpio/${ledPin}/value
 fi

Save script as ping_led.sh and make it executable.

chmod +x ping_led.sh

and run the script.

sh ping_led.sh

Run script in crontab

You can setup the script to run every minute using a crontab

crontab -e

Add the following line

*/1 * * * * /home/pi/ping_led.sh

Should now execute the script every minute and not need any human interaction.

Leave a Reply

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