Friday, September 12, 2014

Python RPi.GPIO: Button and LED

This example read button input from pin 17 (set as input with pull-up resister) and set output to pin 18 to turn ON/OFF LED accordingly.



The code GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) set pin 17 as input with pull-up resistor. If you omit the option pull_up_down=GPIO.PUD_UP, the pin will have no pull-up resistor, and become un-stable.

led.py
import RPi.GPIO as GPIO


GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

while(True):
 if (GPIO.input(17)):
  GPIO.output(18, False)
 else:
  GPIO.output(18, True)


Next:
Read Button using GPIO.add_event_detect() with callback

No comments: