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 blink.py. Right-click on the file explorer tab and select New File from the menu; a new prompt will open: name it blink.py and click OK. The file will be created. Alternatively, we can use the terminal.

Now open the empty blink.py file, paste the following code and save it.

blink.py
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")
try:
    while 1:
            print ("OFF")
            GPIO.output(ledPin, GPIO.LOW)
            time.sleep(1.00)
            print ("ON")           
            GPIO.output(ledPin, GPIO.HIGH)
            time.sleep(1) 
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:

python blink.py

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