Flashing an LED using the Raspberry PI and Python Language

Created on: 28 April 2014

An LED connected to one of the Raspberry PI's GPIO pins can be flashed on and off using a program written in the Python programming language.

In this article, an LED on the Raspberry PI serial port and breakout board is used, but any LED connected to a GPIO pin on the Raspberry PI will work.

Python Source Code

The Python source code for flashing the LED is listed below:

flash.py

#!/usr/bin/python

# library for time delay
import time;
# library for controlling pins (GPIO pins)
import RPi.GPIO as GPIO;

# set GPIO pin 7 as output
GPIO.setmode(GPIO.BCM);
GPIO.setup(7, GPIO.OUT);

# loop until user presses Ctrl + C
while True:
	GPIO.output(7, True);
	time.sleep(1);
	GPIO.output(7, False);
	time.sleep(1);

Running the Python Code

Copy and paste the above source code to a text file and save it to the Raspberry PI, e.g. as flash.py.

To run the code from the command prompt on the Raspberry PI, enter the following:

sudo python flash.py

You must be in the same directory as the flash.py file.

Press Ctrl + C to exit the program.