gpio_inputs_-_button_led_control_using_an_interrupt
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revisionNext revisionBoth sides next revision | ||
gpio_inputs_-_button_led_control_using_an_interrupt [2016/08/09 22:56] – created walkeradmin | gpio_inputs_-_button_led_control_using_an_interrupt [2016/08/09 23:04] – walkeradmin | ||
---|---|---|---|
Line 2: | Line 2: | ||
\\ | \\ | ||
\\ | \\ | ||
+ | The previous example of using a button to light an LED, everything worked fine, but our processor was at 100%, this needs fixing, so in this example instead of constantly polling and setting GPIO pins, we are using a interrupt where by we do nothing until a button is actually pressed. | ||
+ | \\ | ||
+ | Create a new file in the normal way ( you can download the python file {{ : | ||
+ | \\ | ||
+ | #import modules | ||
+ | import RPi.GPIO as GPIO # This imports the GPIO library that allows the use of the GPIO pins, | ||
+ | import time # This imports the time library (for delays among other things) | ||
+ | # These libraries are built in to Raspbian. | ||
+ | |||
+ | GPIO.setmode (GPIO.BOARD) | ||
+ | # so we can reference it by using BOARD as pin 12. However there is | ||
+ | # another option (BCM) where we can reference a pin by it's name, pin | ||
+ | # 12 is called GPIO18 (a reference to its place on the chip). | ||
+ | |||
+ | GPIO.setup(11, | ||
+ | # the resistor to Pull Down (PUD_DOWN) | ||
+ | # this is the pin the button is connected to | ||
+ | # button is connected from pin 11 to the | ||
+ | # +3.3v pin on the GPIO | ||
+ | |||
+ | # this def buttonPressed needs to be defined before it can be reference in the GPIO.add_event_detect | ||
+ | def buttonPressed(channel): | ||
+ | print " | ||
+ | GPIO.output(12, | ||
+ | |||
+ | # this is where we setup the GPIO input to use the event buttonPressed that was | ||
+ | # defined previously. bouncetime is a simple switch debouncer in mS. | ||
+ | GPIO.add_event_detect(11, | ||
+ | |||
+ | GPIO.setup(12, | ||
+ | # from the LED to 0v via a 330 Ohm resistor. | ||
+ | |||
+ | GPIO.output(12, | ||
+ | |||
+ | try: | ||
+ | while True: # start a loop | ||
+ | time.sleep(1) | ||
+ | GPIO.output(12, | ||
+ | except KeyboardInterrupt: | ||
+ | GPIO.cleanup() | ||
+ | |||
+ | #End |