Wednesday, March 11, 2015

Read/Write GPIO of Raspberry Pi 2 using Python

This example show how to read button on GPIO 20 and turn ON/OFF LED on GPIO 21 accordingly, for 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']));
io20 = 20
io21 = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(io20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(io21, GPIO.OUT)
print("Press button to turn ON LED");
try:
 while(True):
 if (GPIO.input(io20)):
 GPIO.output(io21, GPIO.LOW)
 else:
 GPIO.output(io21, GPIO.HIGH)
 
except KeyboardInterrupt:
 print ("\n")
 print ("Exit by KeyboardInterrupt\n")
 
except:
 print ("\n")
 print ("Exit by Other case!\n")
 
finally: 
 GPIO.cleanup(io20)
 GPIO.cleanup(io21)
 print ("Clean up GPIO\n")


More Python examples for Raspberry Pi/Raspberry Pi 2:
- Control RPi.GPIO PWM
- Make a hardware button to shutdown Raspberry Pi

No comments:

Post a Comment

Subscribe to: Post Comments (Atom)

AltStyle によって変換されたページ (->オリジナル) /