Python RPi.GPIO 模块,BOTH 实例源码

我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用RPi.GPIO.BOTH

项目:Venenfinder    作者:Myrijam    | 项目源码 | 文件源码
def __init__(self,pinA,pinB,callback):
      self.pinA = pinA
      self.pinB = pinB
      #self.button = button
      self.callback = callback
      GPIO.setmode(GPIO.BCM)
      # The following lines enable the internal pull-up resistors
      # on version 2 (latest) boards
      GPIO.setwarnings(False)
      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)
      # For version 1 (old) boards comment out the above four lines
      # and un-comment the following 3 lines
      #GPIO.setup(self.pinA, GPIO.IN)
      #GPIO.setup(self.pinB, GPIO.IN)
      #GPIO.setup(self.button, GPIO.IN)
      # 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
项目:Webradio_v2    作者:Acer54    | 项目源码 | 文件源码
def __init__(self,pinA,pinB,button,callback, parent):
        self.pinA = pinA
        self.pinB = pinB
        self.button = button
        self.callback = callback
        self.parent = parent
        if self.pinA is not None and self.pinB is not None:
            GPIO.setmode(GPIO.BOARD)

            GPIO.setwarnings(False)
            GPIO.setup(self.pinA, GPIO.IN)
            GPIO.setup(self.pinB, GPIO.IN)
            GPIO.add_event_detect(self.pinA, GPIO.FALLING,
            callback=self.switch_event)
            GPIO.add_event_detect(self.pinB, GPIO.FALLING,
            callback=self.switch_event)

        if self.button is not None:
            GPIO.setup(self.button, GPIO.IN)
            GPIO.add_event_detect(self.button, GPIO.BOTH,
            callback=self.button_event, bouncetime=200)

        return
        # Call back routine called by switch events
项目:phony    作者:littlecraft    | 项目源码 | 文件源码
def _configure_input(self, name, configuration):
    pin = configuration['pin']

    self.log().debug('Pin %d -> %s' % (pin, name))

    if configuration['pull_up_down'] == 'up':
      pull_up_or_down = GPIO.PUD_UP
    else:
      pull_up_or_down = GPIO.PUD_DOWN

    if 'debounce' in configuration:
      debounce = configuration['debounce']
    else:
      debounce = 0

    GPIO.setup(pin, GPIO.IN, pull_up_down = pull_up_or_down)
    GPIO.add_event_detect(pin, GPIO.BOTH, callback = self._channel_changed, bouncetime = debounce)
项目:StratoBalloon    作者:delattreb    | 项目源码 | 文件源码
def callback(self, io_number):
        """
        if self.importlib is not None:
            self.logger.debug('callback')

            def my_callback(io_number):
                self.logger.debug('Evenent')

                # ici on ajoute une tempo de 75 ms pour eviter l'effet rebond
                GPIO.add_event_detect(io_number, GPIO.BOTH, callback = my_callback, bouncetime = 75)
                # votre programme ici
        """
        pass
项目:52-Weeks-of-Pi    作者:grantwinney    | 项目源码 | 文件源码
def initialize_gpio():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup([11, 32, 36], GPIO.OUT)  # LEDs: Blue (metronome), Green (ok), Red (error)
    GPIO.setup(31, GPIO.IN)
    GPIO.output([32, 36], GPIO.LOW)
    GPIO.add_event_detect(31, GPIO.BOTH, callback=intercept_morse_code)


# Blink a blue LED on/off (one full cycle per BASE_TIME_SECONDS)
项目:auxilia    作者:GHP2017    | 项目源码 | 文件源码
def __init__(self):
        self.button_callback = None
        self.button_held_callback = None
        self.reset_callback = None
        self.pressed_at = None
        self.time_to_hold = 1
        self.time_to_reset = 5

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(18, GPIO.BOTH, callback=self.button_state_changed,bouncetime=200)
项目:RaspberryPi-MPD-CharDisplay    作者:bill6300gp    | 项目源码 | 文件源码
def eventBegin(self, callback, object=0, edge='BOTH'):
    # eventBegin(callback)
    # eventBegin(callback, object, edge)
    # ** callback: call function when Interrupt
    # ** object: set Interrupt pin: 1=Button, 2=Encoder  >> default: 0(all)
    # ** edge: set edge detection: RISING, FALLING, BOTH >> default: BOTH
    self.Callback=callback

    if object==0 and ((self.__SWtype==1 and self.__eventStatus&0x03!=0x00) or (self.__SWtype==2 and self.__eventStatus&0x0F!=0x00)):
      self.eventEnd(0)
    elif object==1 and self.__eventStatus&0x03!=0x00:
      self.eventEnd(1)
    elif object==2 and (self.__SWtype==2 and self.__eventStatus&0x0C!=0x00):
      self.eventEnd(2)

    if object==0 or object==1:
      if edge.upper().find('RISING')>=0:
        GPIO.add_event_detect(self.__PinSW, GPIO.RISING, callback=self.eventButton, bouncetime=40)
        self.__eventStatus|=0x01
      elif edge.upper().find('FALLING')>=0:
        GPIO.add_event_detect(self.__PinSW, GPIO.FALLING, callback=self.eventButton, bouncetime=40)
        self.__eventStatus|=0x02
      elif edge.upper().find('BOTH')>=0:
        GPIO.add_event_detect(self.__PinSW, GPIO.BOTH, callback=self.eventButton, bouncetime=40)
        self.__eventStatus|=0x03
    if (object==0 or object==2) and self.__SWtype==2:
      if edge.upper().find('RISING')>=0:
        GPIO.add_event_detect(self.__PinA , GPIO.RISING, callback=self.eventEncoder, bouncetime=20)
        self.__eventStatus|=0x04
      elif edge.upper().find('FALLING')>=0:
        GPIO.add_event_detect(self.__PinA , GPIO.FALLING, callback=self.eventEncoder, bouncetime=20)
        self.__eventStatus|=0x08
      elif edge.upper().find('BOTH')>=0:
        GPIO.add_event_detect(self.__PinA , GPIO.BOTH, callback=self.eventEncoder, bouncetime=20)
        self.__eventStatus|=0x0C
项目:rainbow-hat    作者:pimoroni    | 项目源码 | 文件源码
def __init__(self, index, gpio_pin):
        self.pressed = False
        self._on_press_handler = None
        self._on_release_handler = None
        self._gpio_pin = gpio_pin
        self._index = index
        GPIO.setup(self._gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(self._gpio_pin, GPIO.BOTH, bouncetime=1, callback=self._handle_button)
项目:TanzoBot    作者:tanzilli    | 项目源码 | 文件源码
def main():

    GPIO.setmode(GPIO.BOARD)
    GPIO.setwarnings(False)

    GPIO.setup(LAMP_SX, GPIO.OUT)
    GPIO.setup(LAMP_DX, GPIO.OUT)

    GPIO.output(LAMP_SX, 0)
    GPIO.output(LAMP_DX, 0)

    GPIO.setup(INT_SX, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(INT_DX, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    GPIO.add_event_detect(INT_SX, GPIO.BOTH, callback=handler_int_sx, bouncetime=100)
    GPIO.add_event_detect(INT_DX, GPIO.BOTH, callback=handler_int_dx, bouncetime=100)

    try:  

        #Entro in un loop infinito dove conto i secondi che passano
        while True:
            time.sleep(1)

    except KeyboardInterrupt:  
        print "Exit"    
        GPIO.cleanup()       # clean up GPIO on CTRL+C exit  

    GPIO.cleanup()           # clean up GPIO on normal exit
项目:ropi    作者:ThumbGen    | 项目源码 | 文件源码
def stepForwardOld(speed, stepsL, stepsR):
    # TODO don't allow nested call backs
    global leftCount, rightCount, intCountL, intCountR
    GPIO.add_event_detect(lineRight, GPIO.BOTH, callback=rightCounter, bouncetime=5)
    GPIO.add_event_detect(lineLeft, GPIO.BOTH, callback=leftCounter, bouncetime=5)
    leftCount = stepsL
    rightCount = stepsR
    lastL = 0
    lastR = 0
    intCountL = 0
    intCountR = 0
#    turnForward(speed, int (speed * stepsR / stepsL))
    forward(speed)
项目:photoberry    作者:briandilley    | 项目源码 | 文件源码
def __init__(self, pin):
        GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.add_event_detect(pin, GPIO.BOTH, callback=self._gpio_event)
        self._pin = pin
        self._pressed = False
        self._was_pressed = False
        self._was_released = False
项目:PiAlarm    作者:KyleKing    | 项目源码 | 文件源码
def test_off_btn():
    print 'Checking that the alarm off button works'
    off_button = cg.get_pin('Input_Pins', 'off_button')
    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(off_button, GPIO.IN)
    GPIO.add_event_detect(off_button, GPIO.BOTH, callback=gen_button_cb)
    sleep(5)

    print 'Checking that Pi-Blaster is booted'
    os.system('sudo python ./bootPiBlaster.py')
    print '** Getting started! Turning everything off **'
    all_off.run()
    print ''
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def main(switch=18, green=8, red=7):
    GPIO.setmode(GPIO.BCM)
    #GPIO.setup(switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(switch, GPIO.IN)
    GPIO.setup(green, GPIO.OUT)
    GPIO.setup(red, GPIO.OUT)
    queue = Queue()
    GPIO.add_event_detect(switch, GPIO.BOTH, callback=partial(interrupt_Event, queue), bouncetime=150)

    start=False
    try:
        while True:
            sleep(0.1)
            if not queue.empty():
                if not start:
                    start = queue.get()
                    GPIO.output(green, False)
                    GPIO.output(red, True)
                else:
                    end = queue.get()
                    print_duration(start, end)
                    GPIO.output(green, True)
                    GPIO.output(red, False)
                    start=False

    except (KeyboardInterrupt, SystemExit):
        GPIO.cleanup()
        print("\nQuit\n")
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def main():
    queueFalling = Queue.Queue()
    queueRising = Queue.Queue()
    rising_thread = Thread(target=rising_edge, args=(queueRising,))
    falling_thread = Thread(target=falling_edge, args=(queueFalling,))
    rising_thread.start()
    falling_thread.start()
    GPIO.setup(Taster, GPIO.IN)
    GPIO.add_event_detect(Taster, GPIO.BOTH, callback=partial(interrupt_event, queueFalling, queueRising), bouncetime=200)
    #keep script running
    while True:
        time.sleep(5)
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def main():
    GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL)
    slave = pigpio.pi(slaveHost, slavePort)
    slave.set_mode(slaveGPIO, pigpio.OUTPUT)
    GPIO.add_event_detect(Taster1, GPIO.BOTH, callback=interrupt_event)
    #keep script running
    while True:
        time.sleep(0.5)
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def main(switch=18, green=8, red=7):
    GPIO.setmode(GPIO.BCM)
    #GPIO.setup(switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(switch, GPIO.IN)
    GPIO.setup(green, GPIO.OUT)
    GPIO.setup(red, GPIO.OUT)
    queue = Queue()
    GPIO.add_event_detect(switch, GPIO.BOTH, callback=partial(interrupt_Event, queue), bouncetime=150)

    running=True
    start=datetime.now()
    end=datetime.now()
    try:
        while running:
            sleep(0.1)
            if not queue.empty():
                pin, state = queue.get()
                if state == GPIO.LOW:
                    start = datetime.now()
                    GPIO.output(green, False)
                    GPIO.output(red, True)
                elif state == GPIO.HIGH:
                    print_duration(start, datetime.now())
                    GPIO.output(green, True)
                    GPIO.output(red, False)

    except (KeyboardInterrupt, SystemExit):
        running=False
        GPIO.cleanup()
        print("\nQuit\n")
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def main():
    try:
        GPIO.add_event_detect(PIR_PIN, GPIO.BOTH, callback=interrupt_event, bouncetime=100)
        #keep script running
        signal.pause()
    except KeyboardInterrupt: # does not work if it runs in background.
        print "\nQuit"
项目:phony    作者:littlecraft    | 项目源码 | 文件源码
def main():
  GPIO.setmode(GPIO.BCM)

  GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
  GPIO.add_event_detect(pin, GPIO.BOTH, callback = _hook_switch_changed, bouncetime = 200)

  while True:
    time.sleep(100)
项目:phony    作者:littlecraft    | 项目源码 | 文件源码
def main():
  GPIO.setmode(GPIO.BCM)

  GPIO.setup(reset_switch, GPIO.IN, pull_up_down = GPIO.PUD_UP)
  GPIO.setup(hook_switch, GPIO.IN, pull_up_down = GPIO.PUD_UP)
  GPIO.add_event_detect(reset_switch, GPIO.BOTH, callback = _io_pulsed, bouncetime = 200)
  GPIO.add_event_detect(hook_switch, GPIO.BOTH, callback = _io_pulsed, bouncetime = 200)

  while True:
    time.sleep(1000)
项目:phony    作者:littlecraft    | 项目源码 | 文件源码
def main():
  GPIO.setmode(GPIO.BCM)

  GPIO.setup(pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)
  GPIO.add_event_detect(pin, GPIO.BOTH, callback = _encoder_pulse, bouncetime = 200)

  while True:
    time.sleep(1000)
项目:Octoprint-Filament-Reloaded    作者:kontakt    | 项目源码 | 文件源码
def on_event(self, event, payload):
        # Early abort in case of out ot filament when start printing, as we
        # can't change with a cold nozzle
        if event is Events.PRINT_STARTED and self.no_filament():
            self._logger.info("Printing aborted: no filament detected!")
            self._printer.cancel_print()
        # Enable sensor
        if event in (
            Events.PRINT_STARTED,
            Events.PRINT_RESUMED
        ):
            self._logger.info("%s: Enabling filament sensor." % (event))
            if self.sensor_enabled():
                GPIO.remove_event_detect(self.pin)
                GPIO.add_event_detect(
                    self.pin, GPIO.BOTH,
                    callback=self.sensor_callback,
                    bouncetime=self.bounce
                )
        # Disable sensor
        elif event in (
            Events.PRINT_DONE,
            Events.PRINT_FAILED,
            Events.PRINT_CANCELLED,
            Events.ERROR
        ):
            self._logger.info("%s: Disabling filament sensor." % (event))
            GPIO.remove_event_detect(self.pin)
项目:AlarmPI    作者:bkbilly    | 项目源码 | 文件源码
def add_sensor(self, sensor, settings=None):
        self.pin = int(sensor['pin'])
        GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        GPIO.remove_event_detect(self.pin)
        GPIO.add_event_detect(
            self.pin, GPIO.BOTH,
            callback=self._checkInputPinState,
            bouncetime=600)
        self._checkInputPinState(self.pin)
        self.setAlertStatus()
项目:rotary-controlled-oled-menu    作者:amnuts    | 项目源码 | 文件源码
def set_menu(self, menu):
        self.menu = menu
        GPIO.add_event_detect(self.clk, GPIO.BOTH, callback=self.__pulse)
        GPIO.add_event_detect(self.dt, GPIO.BOTH, callback=self.__pulse)
        GPIO.add_event_detect(self.btn, GPIO.RISING, callback=self.__button, bouncetime=200)
        self.rotaryLastState = None
        self.btnLastState = GPIO.input(self.btn)
        self.clkLevel = 0
        self.dtLevel = 0
项目:picraftzero    作者:WayneKeenan    | 项目源码 | 文件源码
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)
        GPIO.add_event_detect(self.pin, GPIO.BOTH, callback=handle_callback, bouncetime=bouncetime)
        self.has_callback = True
        return True
项目:GBZ-Power-Monitor_PB    作者:Camble    | 项目源码 | 文件源码
def lowBattery(channel):
  #Checking for LED bounce for the duration of the battery Timeout
  for bounceSample in range(1, int(round(batteryTimeout / sampleRate))):
    time.sleep(sampleRate)

    if GPIO.input(batteryGPIO) is 1:
       break

  global playerFlag
  while playerFlag is 1:
    time.sleep(1)

  #If the LED is a solid condition, there will be no bounce.  Launch shutdown video and then gracefully shutdown
  if bounceSample is int(round(batteryTimeout / sampleRate)) - 1:
    playerFlag = 1
    os.system("/usr/bin/omxplayer --no-osd --layer 999999 " + shutdownVideo + " --alpha 180;")
    if GPIO.input(batteryGPIO) is 0:
      os.system("sudo shutdown -h now")
      playerFlag = 0
      sys.exit(0)

  #If the LED is a solid for more than 10% of the timeout, we know that the battery is getting low.  Launch the Low Battery alert.
  if bounceSample > int(round(batteryTimeout / sampleRate * 0.1)):
    playerFlag = 1
    os.system("/usr/bin/omxplayer --no-osd --layer 999999 " + lowalertVideo + " --alpha 160;")
    playerFlag = 0

    #Discovered a bug with the Python GPIO library and threaded events.  Need to unbind and rebind after a System Call or the program will crash
    GPIO.remove_event_detect(batteryGPIO)
    GPIO.add_event_detect(batteryGPIO, GPIO.BOTH, callback=lowBattery, bouncetime=300)

    #If we know the battery is low, we aggresively monitor the level to ensure we shutdown once the Power Timeout is exceeded.
    lowBattery(batteryGPIO)
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
def edge_detect(port, event_callback, bounce):
    """Add detection for RISING and FALLING events."""
    import RPi.GPIO as GPIO
    GPIO.add_event_detect(
        port,
        GPIO.BOTH,
        callback=event_callback,
        bouncetime=bounce)
项目:BlogCode    作者:yaptb    | 项目源码 | 文件源码
def event_loop(self):

            """main loop. sets up the GPIO callback then polls the hit state to detect a key press.
            """

            self.key_down=False
            key_up_sent=False    
            key_down_sent=False

            GPIO.add_event_detect(BtkGpioClient.PIN, GPIO.BOTH, callback=self.pin_event,bouncetime=250) 


            while True:


                if(self.key_down ):

                        #the pin is set on

                        if(BtkGpioClient.REPEAT_KEY and key_down_sent):
                                #finish the current key and repeat        
                                self.send_key_up()
                                key_down_sent=False
                                time.sleep(BtkGpioClient.REPEAT_KEY_DELAY)

                        if(not key_down_sent):
                                #start a key press
                                self.send_key_down()
                                key_down_sent=True


                else:

                        #the pin is set off

                        if(key_down_sent):
                                #finish the key press
                                self.send_key_up()
                                key_down_sent=False


                time.sleep(BtkGpioClient.MIN_KEY_TIME)  #seems like the minimum delay required for a keypress to be registered