Control a Raspberry Pi GPIO with Python

28 March 2021

Updated: 03 September 2023

Circuit Diagram

This script will make use of the GPIO Pins to flicker an LED

The circuit diagram is below:

Circuit diagram

I’ve used a 330Ω330\Omega resistor for the resistor connected in series RLEDR_LED, however the resistance for a given LED can be calculated with this equation (From Circuit Specialists):

RLED=VsourceVLEDILEDR_{LED} = \frac{V_{source} - V_{LED}}{I_{LED}}

It’s important to connect the LED in the correct direction on the circuit

Code

Below is a simple python script which will handle turning the GPIO pins on and off using the RPi.GPIO library

1
import RPi.GPIO as GPIO
2
import time
3
4
pin = 21
5
dur = 1
6
7
GPIO.setmode(GPIO.BCM)
8
GPIO.setwarnings(False)
9
GPIO.setup(pin, GPIO.OUT)
10
11
while True:
12
GPIO.output(pin, GPIO.HIGH)
13
print "LED ON"
14
time.sleep(dur)
15
16
GPIO.output(pin, GPIO.LOW)
17
print "LED OFF"
18
time.sleep(dur)