我们从Python开源项目中,提取了以下39个代码示例,用于说明如何使用RPi.GPIO.RISING。
def measureDistance_HCSRO4(TRIG_ID, ECHO_ID): GPIO.output(TRIG_ID, True) time.sleep(0.00001) GPIO.output(TRIG_ID, False) edge_detect = GPIO.wait_for_edge(ECHO_ID, GPIO.RISING, timeout = 100) if edge_detect is not None: pulse_start = time.time() else: return MAX_DIST edge_detect = GPIO.wait_for_edge(ECHO_ID, GPIO.FALLING, timeout = 100) if edge_detect is not None: pulse_end = time.time() else: return MAX_DIST pulse_duration = pulse_end - pulse_start distance = round(pulse_duration * 17150, 2) return distance
def __initCBs(self): """ Initialises the Callback functions for each Input IO pin """ # Sound Button Callbacks: for i in range(6): bnt = self.__soundBNTs[i] smp = self.__samples[i] GPIO.add_event_detect(bnt, GPIO.RISING, callback=lambda x,y=smp: self.__soundCB(x, y), bouncetime=200) # Step Button Callbacks: for bnt in self.__stepBNTs: GPIO.add_event_detect(bnt, GPIO.RISING, callback=lambda x: self.__stepCB(x), bouncetime=200) # Play Button Callback: GPIO.add_event_detect(self.__playBNT, GPIO.RISING, callback=lambda x: self.__playCB(x), bouncetime=200) # Record Button Callback: GPIO.add_event_detect(self.__recBNT, GPIO.RISING, callback=lambda x: self.__recCB(x), bouncetime=200)
def main(): #if the Low Battery LED is active when the program launches, handle it if GPIO.input(batteryGPIO) is 0: lowBattery(batteryGPIO) #if the Power Switch is active when the program launches, handle it if GPIO.input(powerGPIO) is 1: powerSwitch(powerGPIO) #Add threaded event listeners for the Low Battery and Power Switch try: GPIO.remove_event_detect(batteryGPIO) GPIO.add_event_detect(batteryGPIO, GPIO.FALLING, callback=lowBattery, bouncetime=300) GPIO.remove_event_detect(powerGPIO) GPIO.add_event_detect(powerGPIO, GPIO.RISING, callback=powerSwitch, bouncetime=300) except KeyboardInterrupt: GPIO.cleanup()
def begin(irq): """ This function opens the SPI connection available on the Raspberry Pi using the chip select #0. Normally, spidev can auto enable chip select when necessary. However, in our case, the dw1000's chip select is connected to GPIO16 so we have to enable/disable it manually. It also sets up the interrupt detection event on the rising edge of the interrupt pin. Args: irq : The GPIO pin number managing interrupts. """ global _deviceMode # Wait 5 us to open spi connection to let the chip enter idle state, see 2.3.2 of the DW1000 user manual (INIT). time.sleep(C.INIT_DELAY) GPIO.setmode(GPIO.BCM) spi.open(0, 0) # spi.max_speed_hz = 4000000 _deviceMode = C.IDLE_MODE GPIO.setup(irq, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(irq, GPIO.RISING, callback=handleInterrupt)
def main(PIR_PIN=23, ACTION_PIN=21, DELTA=15): action=False action_time=datetime.now() queue = Queue() GPIO.setmode(GPIO.BCM) GPIO.setup(ACTION_PIN, GPIO.OUT) GPIO.output(ACTION_PIN, GPIO.HIGH) GPIO.setup(PIR_PIN, GPIO.IN) try: GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=partial(interrupt_event, queue), bouncetime=100) while True: sleep(0.01) if not queue.empty(): pin, state, dt = queue.get() action = True action_time = dt GPIO.output(ACTION_PIN, GPIO.LOW) if action and (datetime.now() - action_time).seconds > DELTA: action = False GPIO.output(ACTION_PIN, GPIO.HIGH) except KeyboardInterrupt: print("Quit")
def __init__(self, name = ''): self.importlib = GPIO self.logger = com_logger.Logger(name) # self.setwarnings(False) self.IN = GPIO.IN if GPIO is not None else None self.OUT = GPIO.OUT if GPIO is not None else None self.LOW = GPIO.LOW if GPIO is not None else None self.HIGH = GPIO.HIGH if GPIO is not None else None self.PUD_UP = GPIO.PUD_UP if GPIO is not None else None self.PUD_DOWN = GPIO.PUD_DOWN if GPIO is not None else None self.RISING = GPIO.RISING if GPIO is not None else None
def wait_edge(self, io_number): if self.importlib is not None: # La première consiste à bloquer l'exécution du programme jusqu'à ce que l'événement se produise. return GPIO.wait_for_edge(io_number, GPIO.RISING)
def event_detect(self, io_number): if self.importlib is not None: self.logger.debug('event_detect') GPIO.add_event_detect(io_number, GPIO.RISING) while True: if GPIO.event_detected(io_number): print("Bouton appuye")
def setup(): """ Function to setup raspberry pi GPIO mode and warnings. PIN 7 OUT and PIN 11 IN """ # Setup GPIO on raspberry pi GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(7, GPIO.OUT, initial=GPIO.LOW) # Tell the program you want to use pin number 7 as output. Relay is ACTIVE LOW, so OFF is HIGH GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set GPIO 11 as a PULL DOWN switch GPIO.add_event_detect(11, GPIO.RISING, activate_goal_light, 5000)
def __init__(self, channel, polarity=GPIO.FALLING, pull_up_down=GPIO.PUD_UP): super().__init__() self.channel = channel self.polarity = polarity if polarity not in [GPIO.FALLING, GPIO.RISING]: raise ValueError('polarity must be GPIO.FALLING or GPIO.RISING') self.expected_value = polarity == GPIO.RISING self.event_detect_added = False GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN, pull_up_down=pull_up_down)
def __init__(self, channel, polarity=GPIO.FALLING, pull_up_down=GPIO.PUD_UP, debounce_time=0.08): """A simple GPIO-based button driver. This driver supports a simple GPIO-based button. It works by detecting edges on the given GPIO channel. Debouncing is automatic. Args: channel: the GPIO pin number to use (BCM mode) polarity: the GPIO polarity to detect; either GPIO.FALLING or GPIO.RISING. pull_up_down: whether the port should be pulled up or down; defaults to GPIO.PUD_UP. debounce_time: the time used in debouncing the button in seconds. """ if polarity not in [GPIO.FALLING, GPIO.RISING]: raise ValueError( 'polarity must be one of: GPIO.FALLING or GPIO.RISING') self.channel = int(channel) self.polarity = polarity self.expected_value = polarity == GPIO.RISING self.debounce_time = debounce_time GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN, pull_up_down=pull_up_down) self.callback = None
def initialize_gpio(): GPIO.setmode(GPIO.BOARD) GPIO.setup(Gmail.PIN, GPIO.OUT) GPIO.setup(CHECK_NOW_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(CHECK_NOW_PIN, GPIO.RISING, callback=check_mail_now, bouncetime=1000)
def __init__(self, mm_per_tick=0.306096, pin=27, poll_delay=0.0166, debug=False): import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(pin, GPIO.IN) GPIO.add_event_detect(pin, GPIO.RISING, callback=self.isr) # initialize the odometer values self.m_per_tick = mm_per_tick / 1000.0 self.poll_delay = poll_delay self.meters = 0 self.last_time = time.time() self.meters_per_second = 0 self.counter = 0 self.on = True self.debug = debug
def listen(assistant): while True: GPIO.wait_for_edge(button_pin, GPIO.RISING) sleep(.5) print("Trigger button gedrückt") mute(assistant) assistant.start_conversation() # speak_tts erzeugt aus einem übergebenen Text mittel Googles TTS-Dienst eine # MP3-Datei. Diese wird von sox abgespielt. # Optional kann eine Sprache angegeben werden.
def mute(assistant): global muted while True: GPIO.wait_for_edge(button_pin, GPIO.RISING) sleep(.5) print('button') muted = not muted assistant.set_mic_mute(muted)
def mute(assistant): global muted while True: GPIO.wait_for_edge(button_pin, GPIO.RISING) sleep(.5) print("Mute Button pressed") muted = not muted assistant.set_mic_mute(muted) # speak_tts erzeugt aus einem übergebenen Text mittel Googles TTS-Dienst eine # MP3-Datei. Diese wird von sox abgespielt. # Optional kann eine Sprache angegeben werden.
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
def __init__(self): io.setmode(io.BCM) self.pir_pin = 4 io.setup(self.pir_pin, io.IN) self.pirStream = Subject() io.add_event_detect(self.pir_pin, io.RISING, callback=self.hit_callback)
def init(self): # open SPI and initialize RF95 self.spi.open(0,self.cs) self.spi.max_speed_hz = 488000 self.spi.close() # set interrupt pin GPIO.setmode(GPIO.BCM) GPIO.setup(self.int_pin, GPIO.IN) GPIO.add_event_detect(self.int_pin, GPIO.RISING, callback=self.handle_interrupt) # set reset pin if self.reset_pin != None: GPIO.setup(self.reset_pin, GPIO.OUT) GPIO.output(self.reset_pin, GPIO.HIGH) # wait for reset time.sleep(0.05) # set sleep mode and LoRa mode self.spi_write(REG_01_OP_MODE, MODE_SLEEP | LONG_RANGE_MODE) time.sleep(0.01) # check if we are set if self.spi_read(REG_01_OP_MODE) != (MODE_SLEEP | LONG_RANGE_MODE): return False # set up FIFO self.spi_write(REG_0E_FIFO_TX_BASE_ADDR, 0) self.spi_write(REG_0F_FIFO_RX_BASE_ADDR, 0) # default mode self.set_mode_idle() self.set_modem_config(Bw125Cr45Sf128) self.set_preamble_length(8) return True
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
def initGpio(self): GPIO.setmode(GPIO.BCM) GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(23, GPIO.RISING, callback=self.tickFlow1, bouncetime=20) GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(24, GPIO.RISING, callback=self.tickFlow2, bouncetime=20) self.fm1 = FlowMeter('metric', ["beer"]) self.fm1.enabled = True self.fm2 = FlowMeter('metric', ["beer"]) self.fm2.enabled = True
def button_tests(): LED_State = 1 away_led = cg.get_pin('Alarm_Status', 'away_led') onoff_led = cg.get_pin('Reserved', 'onoff_led') def test_off_led(tmp): global LED_State print 'test_off_led', LED_State cg.set_PWM(away_led, LED_State) LED_State = 1 if LED_State == 0 else 0 def test_nf_led(tmp): global LED_State print 'test_nf_led', LED_State cg.set_PWM(onoff_led, LED_State) LED_State = 1 if LED_State == 0 else 0 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) off_button = cg.get_pin('Input_Pins', 'off_button') GPIO.setup(off_button, GPIO.IN) GPIO.add_event_detect(off_button, GPIO.RISING, callback=test_off_led, bouncetime=300) print "Did the OFF button work? (Press Key)" __ = raw_input() GPIO.remove_event_detect(off_button) onoff_button = cg.get_pin('Reserved', 'onoff_button') GPIO.setup(onoff_button, GPIO.IN) GPIO.add_event_detect(onoff_button, GPIO.RISING, callback=test_nf_led, bouncetime=300) print "Did the ON/OFF button work? (Press Key)" __ = raw_input() GPIO.remove_event_detect(onoff_button)
def init_gpio(self) -> None: """Initializes the GPIO interface.""" # Set SoC as reference. GPIO.setmode(GPIO.BCM) # Set pin as input and activate pull-down resistor. GPIO.setup(self._pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Add interrupt event. GPIO.add_event_detect(self._pin, GPIO.RISING, callback=self._interrupt, bouncetime=self._bounce_time)
def setup(self): """ setup GPIO pins and install GPIO event handler """ from RPi import GPIO GPIO.setup(self.pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(self.pin, GPIO.RISING, callback=self._onrising, bouncetime=1000)
def setup(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(SDI, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(RCLK, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(SRCLK, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(TouchPin, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.add_event_detect(TouchPin, GPIO.RISING, callback = randomISR, bouncetime = 20) # Shift the data to 74HC595
def setup(): GPIO.setmode(GPIO.BCM) # Numbers GPIOs by physical location GPIO.setup(SigPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set Pin's mode is input, and pull up to high level(3.3V) GPIO.add_event_detect(SigPin, GPIO.RISING, callback=count) # wait for rasing
def main(): try: GPIO.add_event_detect(PIR, GPIO.RISING, callback=interrupt_event, bouncetime=100) #keep script running signal.pause() except (KeyboardInterrupt, SystemExit): print "Quit"
def main(PIR_PIN=24): queue = Queue() GPIO.setmode(GPIO.BCM) GPIO.setup(PIR_PIN, GPIO.IN) try: GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=partial(interrupt_event, queue), bouncetime=100) while True: sleep(0.01) if not queue.empty(): pin, state, dt = queue.get() print('[{}] Motion detected'.format( dt.strftime('%d.%m.%Y %H:%M:%S') )) # hier kann man dann zB. mit dem picamera modul ein Bild schiessen ... except KeyboardInterrupt: print("Quit")
def main(): try: GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=interrupt_event, bouncetime=100) #keep script running signal.pause() except KeyboardInterrupt: # does not work if it runs in background. print "Quit"
def add_event_detect(dio_number, callback): """ Wraps around the GPIO.add_event_detect function :param dio_number: DIO pin 0...5 :param callback: The function to call when the DIO triggers an IRQ. :return: None """ GPIO.add_event_detect(dio_number, GPIO.RISING, callback=callback)
def add_events(cb_dio0, cb_dio1, cb_dio2, cb_dio3, cb_dio4, cb_dio5, switch_cb=None): BOARD.add_event_detect(BOARD.DIO0, callback=cb_dio0) BOARD.add_event_detect(BOARD.DIO1, callback=cb_dio1) BOARD.add_event_detect(BOARD.DIO2, callback=cb_dio2) BOARD.add_event_detect(BOARD.DIO3, callback=cb_dio3) # the modtronix inAir9B does not expose DIO4 and DIO5 if switch_cb is not None: GPIO.add_event_detect(BOARD.SWITCH, GPIO.RISING, callback=switch_cb, bouncetime=300)
def wait_for_input(self): GPIO.wait_for_edge(self.GPIO_PIN, GPIO.RISING)
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
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
def run(self): while not self.quit: button_pressed = False if 0 != BUTTONPIN: button_pressed = not GPIO.input(BUTTONPIN) if button_pressed and self.core.current_call is None: # We do not check the time here. They can keep "ringing" the doorbell if they want # but it won't matter once a call is initiated. if self.doorbell_sound: self.doorbell_sound.play() try: if time.time() - self.lastMessageTicks > WAITSECONDS: self.notify_chat_contacts(message_template="Doorbell ring on %s at %s") params = self.core.create_call_params(None) params.audio_enabled = True params.video_enabled = True params.audio_multicast_enabled = False # Set these = True if you want multiple params.video_multicast_enabled = False # people to connect at once. address = linphone.Address.new(doorbellToAddress) logging.info('address = {address}, used_video_codec = {codec}'.format( address=address, codec=params.used_video_codec)) self.current_call = self.core.invite_address_with_params(address, params) if None is self.current_call: logging.error("Error creating call and inviting with params... outgoing call aborted.") if time.time() - self.lastEmailTicks >= WAITEMAILSECONDS: if LEDPINDOORBELL: self.flash_led(ledpin=LEDPINDOORBELL, stay_on=True, blink_cam_led=False, delay=0.25, blink_count=8) else: self.flash_led() self.notify_email_contacts() except KeyboardInterrupt: self.quit = True break elif detectMotion and self.core.current_call is None: motion_detected = False # Incoming calls have been handled, so check the motion detector: if 0 != PIRPIN: # motion_detected = GPIO.wait_for_edge(PIRPIN,GPIO.RISING) # motion_detected = GPIO.event_detected(PIRPIN) motion_detected = GPIO.input(PIRPIN) logging.debug("\rmotion_detected = %s, GPIO.input(PIRPIN) = %s" % ( str(motion_detected), str(GPIO.input(PIRPIN)))) elif 0 != MDPIN: motion_detected = GPIO.input(MDPIN) == 0 if motion_detected: self.motion_detected() # else: # time.sleep(0.01) # self.core.iterate()
def start(user_home): global fade_stage, _running, alarm_on _running = True stage, stage3_rep_counter = 1, 0 cg.send('Set GPIO mode and event detection') if cg.is_pi(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(off_button, GPIO.IN) GPIO.add_event_detect(off_button, GPIO.RISING, callback=alarm_deactivate, bouncetime=300) while stage < 4 and stage3_rep_counter < 3 and user_home: all_off.run() cg.send('\nStarting Stage: {}'.format(stage) + ' for {} seconds'.format(alarm_stage_time[stage])) current_time = 0 # Stage 1 - Green LED Strip for 1 minute if stage == 1 and alarm_on: cg.send('Configuring Stage 1') cg.set_PWM(pin_green, 0.2) cg.set_PWM(pin_red, 0.2) cb = False # Stage 2 - Purple LED Strip and Buzzer if stage == 2 and alarm_on: cg.send('Configuring Stage 2') cg.set_PWM(pin_blue, 0.5) cg.set_PWM(pin_red, 0.5) cg.set_PWM(pin_buzzer, 0.1) cb = beep # Stage 3 - LED Strip, Bed Shaker, and Buzzer if stage == 3 and alarm_on: cg.send('Configuring Stage 3') cg.set_PWM(pin_shaker, 1) cg.set_PWM(pin_buzzer, 0.5) cb = fade_led_strip # Run alarm and check for button interrupt: while alarm_on and current_time < alarm_stage_time[stage]: time.sleep(step_size) current_time += step_size if cb: cb(current_time) cg.send('Completed Step #{0}'.format(stage)) # Prep for the next loop: if stage == 3 and alarm_on: all_off.run() cg.send('\nLooping back through Stage 3') time.sleep(7) fade_stage = 0 stage3_rep_counter += 1 else: stage += 1 current_time = 0 user_home = cg.check_status() cg.send('Checking home (= {}) before next loop'.format(user_home)) stop()
def __init__(self): """Initialize the nRF24 radio and the Raspberry Pi""" self.state = IDLE # current state self.lcd = None # LCD self.radio = None # nRF24 radio self.address = None # address of Cherry keyboard (CAUTION: Reversed byte order compared to sniffer tools!) self.channel = 6 # used ShockBurst channel (was 6 for all tested Cherry keyboards) self.payloads = [] # list of sniffed payloads self.kbd = None # keyboard for keystroke injection attacks try: # disable GPIO warnings GPIO.setwarnings(False) # initialize LCD self.lcd = CharLCD(cols=16, rows=2, pin_rs=15, pin_rw=18, pin_e=16, pins_data=[21, 22, 23, 24]) self.lcd.clear() self.lcd.home() self.lcd.write_string(APP_NAME) self.lcd.cursor_pos = (1, 0) self.lcd.write_string(SYSS_BANNER) # use Raspberry Pi board pin numbers GPIO.setmode(GPIO.BOARD) # set up the GPIO pins GPIO.setup(RED_LED, GPIO.OUT, initial = GPIO.LOW) GPIO.setup(GREEN_LED, GPIO.OUT, initial = GPIO.LOW) GPIO.setup(BLUE_LED, GPIO.OUT, initial = GPIO.LOW) GPIO.setup(RECORD_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(REPLAY_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(ATTACK_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) GPIO.setup(SCAN_BUTTON, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # set callcack functions GPIO.add_event_detect(RECORD_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250) GPIO.add_event_detect(REPLAY_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250) GPIO.add_event_detect(ATTACK_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250) GPIO.add_event_detect(SCAN_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250) # initialize radio self.radio = nrf24.nrf24() # enable LNA self.radio.enable_lna() # show startup info for some time with blinkenlights self.blinkenlights() # start scanning mode self.setState(SCAN) except: # error when initializing Radio Hack Box self.lcd.clear() self.lcd.home() self.lcd.write_string(u"Error: 0xDEAD") self.lcd.cursor_pos = (1, 0) self.lcd.write_string(u"Please RTFM!")
def buttonCallback(self, channel): """Callback function for user input (pressed buttons)""" # record button state transitions if channel == RECORD_BUTTON: # if the current state is IDLE change it to RECORD if self.state == IDLE: # set RECORD state self.setState(RECORD) # empty payloads list self.payloads = [] # if the current state is RECORD change it to IDLE elif self.state == RECORD: # set IDLE state self.setState(IDLE) # play button state transitions elif channel == REPLAY_BUTTON: # if the current state is IDLE change it to REPLAY if self.state == IDLE: # set REPLAY state self.setState(REPLAY) # scan button state transitions elif channel == SCAN_BUTTON: # wait a short a time to see whether the record button is also # press in order to perform a graceful shutdown # remove event detection for record button GPIO.remove_event_detect(RECORD_BUTTON) chan = GPIO.wait_for_edge(RECORD_BUTTON, GPIO.RISING, timeout=1000) if chan != None: # set SHUTDOWN state self.setState(SHUTDOWN) # set callback function for record button GPIO.remove_event_detect(RECORD_BUTTON) GPIO.add_event_detect(RECORD_BUTTON, GPIO.RISING, callback = self.buttonCallback, bouncetime = 250) # if the current state is IDLE change it to SCAN if self.state == IDLE: # set SCAN state self.setState(SCAN) # attack button state transitions elif channel == ATTACK_BUTTON: # if the current state is IDLE change it to ATTACK if self.state == IDLE: # set ATTACK state self.setState(ATTACK) # debug output debug("State: {0}".format(self.state))