Blink - Controlling an LED

Let’s write our first program to toggle an LED connected with GPIO pin on our virtual target. First, we need to create a file named Right-click on the file explorer tab and select New File from the menu; a new prompt will open: name it and click OK. The file will be created. Alternatively, we can use the terminal.

Now open the empty file, paste the following code and save it.
import RPi.GPIO as GPIO    # Importing the GPIO controller module
import time

print("Hello LED")
ledPin = 9

print("Setting Broadcom Mode")
# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme

print("Setting LED as an output")
GPIO.setup(ledPin, GPIO.OUT) 

print("Here we go! Press CTRL+C to exit")
    while 1:
            print ("OFF")
            GPIO.output(ledPin, GPIO.LOW)
            print ("ON")           
            GPIO.output(ledPin, GPIO.HIGH)
except KeyboardInterrupt: # If CTRL+C is pressed, exit cleanly
    GPIO.cleanup() # cleanup all GPIO

Now the program is ready and we just need to run it. Go to the terminal and write:


The program will run in a loop and toggle the LED on Pin number 9.

To stop the program press Ctrl+C.

Congratulations! We now know how to control the GPIO pins.

Last updated