First install Python's Raspberry Pi GPIO module, it should be installed by default but let's just be sure.
$ sudo apt-get install python-rpi.gpio
Then import the module into the python script.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
We are using the BCM
mode because we want to make sure that we refer to the pin diagram and connect them appropriately and be careful with our connections which, if they are wrong might result in our board being fried. The other mode available to us is the BOARD
mode.
Next let's set up the GPIO pins using python.
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)
time.sleep(10) # Light up LED for 10 secs
GPIO.output(18, GPIO.LOW)
GPIO.cleanup()
Here we turn on the GPIO pin 18 to high and let it be high for 10 seconds and then switch it to low, then we "clean up" the GPIO to make sure they return to their default statuses.
Below: the full script.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.HIGH)
time.sleep(10) # Light up LED for 10 secs
GPIO.output(18, GPIO.LOW)
GPIO.cleanup()