Wednesday, March 11, 2015

Control Raspberry Pi 2 GPIO using Python

Example show how to control GPIO of Raspberry Pi 2 using Python.


Connection:


testGPIO.py
import sys
import RPi.GPIO as GPIO
import time

print("sys.version:")
print(sys.version + "\n")

print("GPIO.VERSION: " + GPIO.VERSION)
print("GPIO.RPI_INFO['P1_REVISION'] = " + str(GPIO.RPI_INFO['P1_REVISION']));

io21 = 21

GPIO.setmode(GPIO.BCM)
GPIO.setup(io21, GPIO.OUT)

print("LED at GPIO21 is blinking");
try:
    while(True):
        GPIO.output(io21, GPIO.HIGH)
        time.sleep(1.5)
        GPIO.output(io21, GPIO.LOW)
        time.sleep(0.5)
    
except KeyboardInterrupt:
    print ("\n")
    print ("Exit by KeyboardInterrupt\n")
  
except:
    print ("\n")
    print ("Exit by Other case!\n")
  
finally:  
    GPIO.cleanup(io21)
    print ("Clean up GPIO\n")


No comments: