Starting Electronics needs your help! Please make a donation to help cover our hosting and other costs. Click the donate button to send a donation of any amount.

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.

This video shows the LED being flashed by the Raspberry PI:

Can't see the video? View on YouTube →

Python Source Code

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


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

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

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

Books that may interest you:

C Programming with Arduino Book Ultimate Arduino MEGA 2560 Hardware Manual Ultimage Arduino Uno Hardware Manual

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

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

sudo python

You must be in the same directory as the file.

Press Ctrl + C to exit the program.

New Book: Explore ATtiny Microcontrollers using C and Assembly Language

Explore ATtiny Microcontrollers using C and Assembly Language book Ultimate Arduino Uno Hardware Manual

As an Amazon Associate I earn from qualifying purchases: