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.
import RPi.GPIO as GPIO

# 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)

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

Read Button using GPIO.add_event_detect() with callback

No comments: