Python RPi.GPIO.add_event_detect() Examples

The following are 30 code examples of RPi.GPIO.add_event_detect(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module RPi.GPIO , or try the search function .
Example #1
Source File: deskcycle_test.py    From BlogCode with MIT License 7 votes vote down vote up
def event_loop(self):

            count =0

            keys_per_rev=5
            key_press_delay=0.05
            inter_key_delay=0.1
            last_time=0
            current_time=0

            GPIO.add_event_detect(DeskCycle.PIN, GPIO.FALLING, callback=self.pin_event,bouncetime=100) 

            while True:

                if(self.hitCount >0):
                    count+=1
                    print "Hit ",count
                    self.hitCount-=1

                time.sleep(0.01) 
Example #2
Source File: Midi.py    From OP_Manager with MIT License 7 votes vote down vote up
def startKeyEvent(self):
        print('Start Key Event Catcher')
        # Add return key to interrupt callback
        pins = [27, 23, 4, 17, 22, 5, 6]  # [L, R, C, U, D, A, B]
        # Add each to to key detect
        for i in pins:
            GPIO.add_event_detect(i, GPIO.RISING)

        # GPIO.add_event_callback(27, callback=self._semitone_down)
        # GPIO.add_event_callback(23, callback=self._semitone_up)
        # GPIO.add_event_callback(4, callback=self._reset_change)
        # GPIO.add_event_callback(17, callback=self._octave_up)
        # GPIO.add_event_callback(22, callback=self._octave_down)
        GPIO.add_event_callback(5, callback=self.stopInterruptCallBack)
        # GPIO.add_event_callback(6, callback=self.stopInterruptCallBack)

        # GPIO.add_event_callback(27, callback=self.leftKey)
        # GPIO.add_event_callback(23, callback=self.rightKey)
        # GPIO.add_event_callback(4, callback=self.centerKey)
        # GPIO.add_event_callback(17, callback=self.upKey)
        # GPIO.add_event_callback(22, callback=self.downKay)
        # GPIO.add_event_callback(5, callback=self.aKey)
        # GPIO.add_event_callback(6, callback=self.bKey) 
Example #3
Source File: __init__.py    From phat-beat with MIT License 7 votes vote down vote up
def setup():
    global _is_setup

    if _is_setup:
        return True

    atexit.register(_exit)

    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup([DAT, CLK], GPIO.OUT)
    GPIO.setup(BUTTONS, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    for button in BUTTONS:
        GPIO.add_event_detect(button, GPIO.FALLING, callback=_handle_button, bouncetime=200)

    _is_setup = True 
Example #4
Source File: joystick.py    From displayotron with MIT License 7 votes vote down vote up
def on(buttons, bounce=BOUNCE):
    """Handle a joystick direction or button push

    Decorator. Use with @joystick.on(joystick.UP)

    :param buttons: List, or single instance of joystick button constant
    :param bounce: Debounce delay in milliseconds: default 300

    """

    buttons = buttons if isinstance(buttons, list) else [buttons]

    def register(handler):
        for button in buttons:
            GPIO.remove_event_detect(button)
            GPIO.add_event_detect(button, GPIO.FALLING, callback=handler, bouncetime=bounce)

    return register 
Example #5
Source File: __init__.py    From OctoPrint-Enclosure with GNU General Public License v3.0 6 votes vote down vote up
def start_filament_detection(self):
        self.stop_filament_detection()
        try:
            for filament_sensor in list(filter(
                    lambda item: item['input_type'] == 'gpio' and item['action_type'] == 'printer_control' and item[
                        'printer_action'] == 'filament', self.rpi_inputs)):
                edge = GPIO.RISING if filament_sensor['edge'] == 'rise' else GPIO.FALLING
                if GPIO.input(self.to_int(filament_sensor['gpio_pin'])) == (edge == GPIO.RISING):
                    self._printer.pause_print()
                    self._logger.info("Started printing with no filament.")
                else:
                    self.last_filament_end_detected.append(dict(index_id=filament_sensor['index_id'], time=0))
                    self._logger.info("Adding GPIO event detect on pin %s with edge: %s", filament_sensor['gpio_pin'],
                        edge)
                    GPIO.add_event_detect(self.to_int(filament_sensor['gpio_pin']), edge,
                        callback=self.handle_filamment_detection, bouncetime=200)
        except Exception as ex:
            self.log_error(ex) 
Example #6
Source File: _button.py    From ai-makers-kit with MIT License 6 votes vote down vote up
def wait_for_press(self):
        GPIO.add_event_detect(self.channel, self.polarity)
        while True:
            if GPIO.event_detected(self.channel) and self._debounce():
                GPIO.remove_event_detect(self.channel)
                return
            time.sleep(0.02) 
Example #7
Source File: tact.py    From SAKS-tutorials with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, pin, real_true = GPIO.HIGH):
        '''
        Init the tact
        :param pin: pin number in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pin = pin
        self.__real_true = real_true

        if self.__real_true:
            self.__status = GPIO.input(self.__pin)
        else:
            self.__status = not GPIO.input(self.__pin)

        GPIO.add_event_detect(pin, GPIO.BOTH, callback = self.make_event, bouncetime = 1)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
        except:
            print "Error: Unable to start thread by Tact"


    #Stauts. 
Example #8
Source File: tact.py    From SAKS-tutorials with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, pin, real_true = GPIO.HIGH):
        '''
        Init the tact
        :param pin: pin number in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pin = pin
        self.__real_true = real_true

        if self.__real_true:
            self.__status = GPIO.input(self.__pin)
        else:
            self.__status = not GPIO.input(self.__pin)

        GPIO.add_event_detect(pin, GPIO.BOTH, callback = self.make_event, bouncetime = 1)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
        except:
            print "Error: Unable to start thread by Tact"


    #Stauts. 
Example #9
Source File: tact.py    From SAKS-tutorials with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, pin, real_true = GPIO.HIGH):
        '''
        Init the tact
        :param pin: pin number in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pin = pin
        self.__real_true = real_true

        if self.__real_true:
            self.__status = GPIO.input(self.__pin)
        else:
            self.__status = not GPIO.input(self.__pin)

        GPIO.add_event_detect(pin, GPIO.BOTH, callback = self.make_event, bouncetime = 1)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
        except:
            print "Error: Unable to start thread by Tact"


    #Stauts. 
Example #10
Source File: tact.py    From SAKS-tutorials with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, pin, real_true = GPIO.HIGH):
        '''
        Init the tact
        :param pin: pin number in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pin = pin
        self.__real_true = real_true

        if self.__real_true:
            self.__status = GPIO.input(self.__pin)
        else:
            self.__status = not GPIO.input(self.__pin)

        GPIO.add_event_detect(pin, GPIO.BOTH, callback = self.make_event, bouncetime = 1)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
        except:
            print "Error: Unable to start thread by Tact"


    #Stauts. 
Example #11
Source File: acceptor_test.py    From LightningATM with MIT License 6 votes vote down vote up
def main():
    global pulses

    ## We're using BCM Mode
    GPIO.setmode(GPIO.BCM)

    ## Setup coin interrupt channel
    GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    # GPIO.setup(PIN_COIN_INTERRUPT,GPIO.IN)
    GPIO.add_event_detect(6, GPIO.FALLING, callback=coinEventHandler)

    while True:
        time.sleep(0.5)
        if (time.time() - lastImpulse > 0.5) and (pulses > 0):
            if pulses == 1:
                print("Coin 1")
            pulses = 0

    GPIO.cleanup()


# handle the coin event 
Example #12
Source File: RotaryDial.py    From aselektriskbureau with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        # Set GPIO mode to Broadcom SOC numbering
        GPIO.setmode(GPIO.BCM)

        # Listen for rotary movements
        GPIO.setup(self.pin_rotary, GPIO.IN)
        GPIO.add_event_detect(self.pin_rotary, GPIO.BOTH, callback = self.NumberCounter)
        
        # Listen for on/off hooks
        GPIO.setup(self.pin_onhook, GPIO.IN)
        GPIO.add_event_detect(self.pin_onhook, GPIO.BOTH, callback = self.HookEvent, bouncetime=100)
        
        self.onhook_timer = Timer(2, self.verifyHook)
        self.onhook_timer.start()

    # Handle counting of rotary movements and respond with digit after timeout 
Example #13
Source File: garage.py    From GarageQTPi with MIT License 6 votes vote down vote up
def __init__(self, config):

        # Config
        self.relay_pin = config['relay']
        self.state_pin = config['state']
        self.id = config['id']
        self.mode = int(config.get('state_mode') == 'normally_closed')
        self.invert_relay = bool(config.get('invert_relay'))

        # Setup
        self._state = None
        self.onStateChange = EventHook()

        # Set relay pin to output, state pin to input, and add a change listener to the state pin
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.relay_pin, GPIO.OUT)
        GPIO.setup(self.state_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(self.state_pin, GPIO.BOTH, callback=self.__stateChanged, bouncetime=300)


        # Set default relay state to false (off)
        GPIO.output(self.relay_pin, self.invert_relay)

    # Release rpi resources 
Example #14
Source File: TipiWatchDogService.py    From tipi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        self.__RESET = 26

        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)

        GPIO.setup(self.__RESET, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        # Do not proceed unless the reset signal has turned off
        # attempt to prevent restart storm in systemd

        print("waiting for reset to complete.")
        while GPIO.input(self.__RESET) != 1:
            time.sleep(0.100)
            pass

        GPIO.add_event_detect(
            self.__RESET, GPIO.FALLING, callback=onReset, bouncetime=100
        )
        print("GPIO initialized.") 
Example #15
Source File: __init__.py    From explorer-hat with MIT License 6 votes vote down vote up
def _setup_callback(self, bouncetime):
        if self.has_callback:
            return False

        def handle_callback(pin):
            if self.read() == 1 and callable(self.handle_pressed):
                self.handle_pressed(self)
            elif self.read() == 0 and callable(self.handle_released):
                self.handle_released(self)
            if callable(self.handle_changed):
                self.handle_changed(self)

        self._setup_gpio()
        GPIO.add_event_detect(self.pin, GPIO.BOTH, callback=handle_callback, bouncetime=bouncetime)
        self.has_callback = True
        return True 
Example #16
Source File: controller.py    From GaragePi with MIT License 6 votes vote down vote up
def __init__(self, port="5550"):
        self.__bind_addr = "tcp://*:%s" % port
        app.logger.info("Bind address: " + self.__bind_addr)

        self.__relay_lock = threading.Lock()

        self.__db = GarageDb(app.instance_path, app.resource_path)

        # Get initial reed state and subscribe to events
        GPIO.setup(app.config['REED_PIN'], GPIO.IN)
        GPIO.add_event_detect(app.config['REED_PIN'], GPIO.BOTH, callback=self.door_opened_or_closed)
        self.__door_state = None                            # 1 for open, 0 for closed, None for uninitialized
        self.door_opened_or_closed(app.config['REED_PIN'])  # force update

        # Set up warning timer if there's a setting
        if app.config['DOOR_OPEN_WARNING_TIME']:
            app.logger.info('Starting schedule to check door at {0}...'.format(app.config['DOOR_OPEN_WARNING_TIME']))
            schedule.every().day.at(app.config['DOOR_OPEN_WARNING_TIME']).do(self.check_door_open_for_warning)
            t = Thread(target=self.run_schedule)
            t.start()
        else:
            app.logger.info('No schedule to run.') 
Example #17
Source File: polapizero_09.py    From polapi-zero with MIT License 6 votes vote down vote up
def haltSystem():
    print 'Halt...'
    os.system("sudo halt")
    
# GPIO.add_event_detect(HALT_PIN, GPIO.FALLING, callback = haltSystem, bouncetime = 2000) 
Example #18
Source File: KY040.py    From KY040 with MIT License 5 votes vote down vote up
def start(self):
        GPIO.add_event_detect(self.clockPin, GPIO.FALLING, callback=self._clockCallback, bouncetime=self.rotaryBouncetime)

        if None != self.switchPin:
            GPIO.add_event_detect(self.switchPin, GPIO.FALLING, callback=self._switchCallback, bouncetime=self.switchBouncetime) 
Example #19
Source File: tact.py    From SAKS-tutorials with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, pin, real_true = GPIO.HIGH):
        '''
        Init the tact
        :param pin: pin number in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pin = pin
        self.__real_true = real_true

        if self.__real_true:
            self.__status = GPIO.input(self.__pin)
        else:
            self.__status = not GPIO.input(self.__pin)

        GPIO.add_event_detect(pin, GPIO.BOTH, callback = self.make_event, bouncetime = 1)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
            #t1.start()
        except:
            print("Error: Unable to start thread by Tact")


    #Stauts. 
Example #20
Source File: assistant.py    From voicetools with Apache License 2.0 5 votes vote down vote up
def set_voice_sensor():
    GPIO.setup(GPIOConfig.VOICE_SENSOR, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.add_event_detect(GPIOConfig.VOICE_SENSOR, GPIO.FALLING) 
Example #21
Source File: dip_switch_2bit.py    From SAKS-tutorials with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, pins, real_true = GPIO.HIGH):
        '''
        Init the dip switch
        :param pin: pin numbers in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pins = pins
        self.__real_true = real_true
        for p in pins:
            self.__status.append(not real_true)

        if self.__real_true:
            self.__status[0] = GPIO.input(self.__pins[0])
            self.__status[1] = GPIO.input(self.__pins[1])
        else:
            self.__status[0] = not GPIO.input(self.__pins[0])
            self.__status[1] = not GPIO.input(self.__pins[1])


        GPIO.add_event_detect(self.__pins[0], GPIO.BOTH, callback = self.make_event, bouncetime = 50)
        GPIO.add_event_detect(self.__pins[1], GPIO.BOTH, callback = self.make_event, bouncetime = 50)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
            #t1.start()
        except:
            print("Error: Unable to start thread by DipSwitch")

    #Stauts. 
Example #22
Source File: dip_switch_2bit.py    From SAKS-SDK with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, pins, real_true = GPIO.HIGH):
        '''
        Init the dip switch
        :param pin: pin numbers in array
        :param real_true: GPIO.HIGH or GPIO.LOW
        :return: void
        '''
        self.__pins = pins
        self.__real_true = real_true
        for p in pins:
            self.__status.append(not real_true)

        if self.__real_true:
            self.__status[0] = GPIO.input(self.__pins[0])
            self.__status[1] = GPIO.input(self.__pins[1])
        else:
            self.__status[0] = not GPIO.input(self.__pins[0])
            self.__status[1] = not GPIO.input(self.__pins[1])


        GPIO.add_event_detect(self.__pins[0], GPIO.BOTH, callback = self.make_event, bouncetime = 50)
        GPIO.add_event_detect(self.__pins[1], GPIO.BOTH, callback = self.make_event, bouncetime = 50)

        try:
            t1 = Thread(target = self.watching)
            t1.setDaemon(True)
            #t1.start()
        except:
            print("Error: Unable to start thread by DipSwitch")

    #Stauts. 
Example #23
Source File: rotary_class.py    From piradio with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pinA, pinB, button,callback,revision):
        self.pinA = pinA
        self.pinB = pinB
        self.button = button
        self.callback = callback

        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        
        if revision == 1:
            # For version 1 (old) boards 
            GPIO.setup(self.pinA, GPIO.IN)
            GPIO.setup(self.pinB, GPIO.IN)
            GPIO.setup(self.button, GPIO.IN)
        else:
            # The following lines enable the internal pull-up resistors
            # on version 2 (latest) boards
            GPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP)
            GPIO.setup(self.pinB, GPIO.IN, pull_up_down=GPIO.PUD_UP)
            GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        # Add event detection to the GPIO inputs
        GPIO.add_event_detect(self.pinA, GPIO.BOTH, callback=self.switch_event)
        GPIO.add_event_detect(self.pinB, GPIO.BOTH, callback=self.switch_event)
        GPIO.add_event_detect(self.button, GPIO.BOTH, callback=self.button_event, bouncetime=200)


    # Call back routine called by switch events 
Example #24
Source File: fake_gpio_for_testing.py    From makerspace-auth with Apache License 2.0 5 votes vote down vote up
def __init__(self, fake_time=None):
        self.pin_states = [0] * 10
        self.events = {}
        self.time = fake_time or time

        self.t_zero = self.time.time()
        self.log = []

        GPIO.output = self.output
        GPIO.input = self.input
        GPIO.add_event_detect = self.add_event_detect 
Example #25
Source File: io_raspberry.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bus, pin_number, name, debounce_time_ms = 20):
        self.pin = pin_number
        self.name = name
        self.bus = bus
        if self.pin:
            GPIO.setup(self.pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
            GPIO.add_event_detect(self.pin, GPIO.BOTH, callback = self.button_changed, bouncetime = debounce_time_ms)
            self.button_state = GPIO.input(self.pin)
        else:
            logger.warn("Cannot init button {0}, pin not specified".format(self.name)) 
Example #26
Source File: io_raspberry.py    From foos with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bus, pin_number, team):
        self.bus = bus
        self.pin = pin_number
        self.team = team
        if self.pin:
            #GPIO.setup(self.pin, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
            GPIO.setup(self.pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
            GPIO.add_event_detect(self.pin, GPIO.FALLING, callback=self.on_goal, bouncetime=10)
        else:
            logger.warn("Cannot init GoalDetector {0}, pin not specified".format(self.team)) 
Example #27
Source File: gengpioin.py    From genmon with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, gpio = None, trigger = GPIO.FALLING, resistorpull = GPIO.PUD_UP, log = None, callback = None, uselibcallbacks = False, bouncetime = None):
        super(MyGPIOInput, self).__init__()
        self.Trigger = trigger
        self.ResistorPull = resistorpull
        self.GPIO = gpio
        self.log = log
        self.TimeoutSeconds = 1
        self.BounceTime = bouncetime
        self.Callback = callback
        self.UseLibCallbacks = uselibcallbacks
        self.Exiting = False

        try:

            GPIO.setmode(GPIO.BOARD)
            GPIO.setwarnings(True)
            GPIO.setup(gpio, GPIO.IN, pull_up_down=resistorpull)

            if callback != None and callable(callback):
                if self.BounceTime > 0:
                    GPIO.add_event_detect(gpio  = self.GPIO, edge = self.Trigger, bouncetime = self.BounceTime)
                else:
                    GPIO.add_event_detect(gpio  = self.GPIO, edge = self.Trigger)
                if self.UseLibCallbacks:
                    GPIO.add_event_callback(gpio = self.GPIO, callback = self.Callback)
                else:
                    # setup callback
                    self.Threads["GPIOInputMonitor"] = MyThread(self.GPIOInputMonitor, Name = "GPIOInputMonitor", start = False)
                    self.Threads["GPIOInputMonitor"].Start()

        except Exception as e1:
            self.LogErrorLine("Error in MyGPIOInput:init: " + str(gpio) + " : " + str(e1))

    #-----------------GPIOInputMonitor------------------------------------------ 
Example #28
Source File: pi_power.py    From pi_power with MIT License 5 votes vote down vote up
def user_shutdown_setup(shutdown_pin):
    # setup the pin to check the shutdown switch - use the internal pull down resistor
    GPIO.setup(shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    # create a trigger for the shutdown switch
    GPIO.add_event_detect(shutdown_pin, GPIO.RISING, callback=user_shutdown, bouncetime=1000)

# User has pressed shutdown button - initiate a clean shutdown 
Example #29
Source File: controller_rpi.py    From SX127x_driver_for_MicroPython_on_ESP8266 with GNU General Public License v3.0 5 votes vote down vote up
def prepare_irq_pin(self, pin_id):
        pin = self.prepare_pin(pin_id, GPIO.IN)
        if pin:
            pin.set_handler_for_irq_on_rising_edge = \
                lambda handler: GPIO.add_event_detect(pin.pin_id,
                                                      GPIO.RISING,
                                                      callback = handler)
            pin.detach_irq = lambda: GPIO.remove_event_detect(pin.pin_id)
            return pin 
Example #30
Source File: rotary_class_alternative.py    From piradio with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self,pinA,pinB,button,callback,revision):
		self.pinA = pinA
		self.pinB = pinB
		self.button = button
		self.callback = callback

		GPIO.setmode(GPIO.BCM)
		GPIO.setwarnings(False)
		
		if revision == 1:
			# For version 1 (old) boards comment out the above four lines
			GPIO.setup(self.pinA, GPIO.IN)
			GPIO.setup(self.pinB, GPIO.IN)
			GPIO.setup(self.button, GPIO.IN)
		else:
			# The following lines enable the internal pull-up resistors
			# on version 2 (latest) boards
			GPIO.setup(self.pinA, GPIO.IN, pull_up_down=GPIO.PUD_UP)
			GPIO.setup(self.pinB, GPIO.IN, pull_up_down=GPIO.PUD_UP)
			GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_UP)

		# Add event detection to the GPIO inputs
		GPIO.add_event_detect(self.pinA, GPIO.FALLING, callback=self.switch_event)
		GPIO.add_event_detect(self.pinB, GPIO.FALLING, callback=self.switch_event)
		GPIO.add_event_detect(self.button, GPIO.BOTH, callback=self.button_event, bouncetime=200)
		return

	# Call back routine called by switch events