Raspberry Pi – Blink Light – Python

A Simple Python script to blink a Raspberry Pi LED.

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)  # Uses the physical pin numbering
GPIO.setup(7, initial=GPIO.LOW)  # Set GPIO pin to off

while True:
    GPIO.output(7, GPIO.HIGH)
    GPIO.output(7, GPIO.LOW)

Change pin numbers as needed.

We can also do this with BASH.

Control LED using BASH

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 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=""  # 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
         # Turn off LED 
         echo "0" > /sys/class/gpio/${ledPin}/value

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.

Control LED from Command Line – Raspberry Pi

Replace “4” with the GPIO pin your using.

echo "4" > /sys/class/gpio/export

Setup the direction.  If it was a button or switch we would change “out” to “in”.

echo "out" > /sys/class/gpio/gpio4/direction

Turn the LED on.

echo "1" > /sys/class/gpio/gpio4/value

Turn the LED off.

echo "0" > /sys/class/gpio/gpio4/value

1 = on and 0 = off.