Raspberry Pi GPIO Programming Part 1

The code for this project may be found on Github. To check out the code, run the following commands:

git clone https://github.com/alfmel/rpi_leds.git
cd rpi_leds
git checkout part1

Disclaimer: I am teaching myself how to program the Raspberry Pi, often following the examples of others. I am not an expert beyond what I put here.

Let's begin the GPIO journey by turning on an LED. The code for this project won't be too different from what I did back when I installed the GPIO library. Here I will focus on writing a clean and simple and script.

I called my script turn_on_led.py. You can find the latest version on Github.

#!/usr/bin/env python

import RPi.GPIO as GPIO
import time

# Use Raspberry Pi pin labels

# OR use Raspberry Pi board pin numbers
# GPIO.setmode(GPIO.BOARD)

# Choose the pin number you want to use
pinNumber = 21

    # Set up GPIO pin as outout
    GPIO.setup(pinNumber, GPIO.OUT)

    # Turn on the LED
    print("Turning on LED...")
    GPIO.output(pinNumber, GPIO.HIGH)

    # Sleep for 10 seconds

    # Turn off LED
    print("Turning off LED...")
    GPIO.output(pinNumber, GPIO.LOW)
except KeyboardInterrupt:
    print("Keyboard interrupt... exiting.")


The script is fairly simple: initialize GPIO, assign the pin number I plan to use (in this case, GPIO pin 21), set the pin for output, set the output high (remember, this 3.3V), wait 10 seconds, and then set it low again. Finally, we clean up GPIO. If we don't clean up all previous settings stay in place which may mean we leave the LED on.

On the hardware side, we need to wire up an LED. I chose GPIO pin 21 (physical pin 40) because there is a ground pin at physical pin 39. They are also at the very bottom so they are easy to locate. At first I ran a resitor through the circuit, but the LED wasn't very bright. So I just wired it up directly. The LED is bright and my Pi Zero did not fry.

Wiring is pretty simple with the help of the breadboard included in the kit and the male-to-female cables:

Image description

Running the script (sudo ./turn_on_led.py or sudo python turn_on_led.py) turns on the LED, as we would expect:

Image description

There you have it! A simple script for turning on an LED on a Rasbperry Pi via a GPIO pin.