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)
python类add_event_detect()的实例源码
def on_press(self, callback):
"""Calls the callback whenever the button is pressed.
Args:
callback: a function to call whenever the button is pressed. It should
take a single channel number. If the callback is None, the previously
registered callback, if any, is canceled.
Example:
def MyButtonPressHandler(channel):
print "button pressed: channel = %d" % channel
my_button.on_press(MyButtonPressHandler)
"""
GPIO.remove_event_detect(self.channel)
if callback is not None:
self.callback = callback
GPIO.add_event_detect(
self.channel, self.polarity, callback=self._debounce_and_callback)
def init_gpio(self, rpi_settings):
"""
Initialize GPIO pin to a default value. Leds are off by default
Mute button is set as an input
:param rpi_settings: RpiSettings object
"""
# All led are off by default
if self.rpi_settings.pin_led_muted:
GPIO.setup(rpi_settings.pin_led_muted, GPIO.OUT, initial=GPIO.LOW)
if self.rpi_settings.pin_led_started:
GPIO.setup(rpi_settings.pin_led_started, GPIO.OUT, initial=GPIO.LOW)
if self.rpi_settings.pin_led_listening:
GPIO.setup(rpi_settings.pin_led_listening, GPIO.OUT, initial=GPIO.LOW)
if self.rpi_settings.pin_led_talking:
GPIO.setup(rpi_settings.pin_led_talking, GPIO.OUT, initial=GPIO.LOW)
# MUTE button
if self.rpi_settings.pin_mute_button:
GPIO.setup(rpi_settings.pin_mute_button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(rpi_settings.pin_mute_button, GPIO.FALLING,
callback=self.switch_kalliope_mute_led,
bouncetime=500)
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)
def button_press_switch(channel):
global button_status
GPIO.remove_event_detect(channel)
logging.info('Button pressed')
pressed_time = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_time
pressed_time = dif.seconds
if pressed_time > 6:
shutdown()
button_status = BUTTON_SHUTDOWN
elif pressed_time > 2:
button_status = BUTTON_MONITOR_SWITCH
else:
button_status = BUTTON_SENSOR_SWITCH
logging.info("Button status = %s", button_status)
GPIO.add_event_detect(channel, GPIO.FALLING, callback=button_press_switch, bouncetime=200)
# Run cleanup routines
def shutdown(channel):
"""
Calls system shutdown after a button press of more than 2 seconds
"""
GPIO.remove_event_detect(channel)
pressed_timestamp = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_timestamp
pressed_time = dif.seconds
logging.debug('Pressed time = %s', pressed_time)
if pressed_time > 2:
logging.info('Button initiated shutdown')
os.system("sudo shutdown -h now")
GPIO.add_event_detect(channel, GPIO.FALLING, callback=shutdown, bouncetime=200)
# Add button pressed event detects
def shutdown(channel): # Change to lowercase function name
# Modify function to require the shutdown button to be pressed and held
# for at least 2 seconds before shutting down.
GPIO.remove_event_detect(channel)
pressed_time = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_time
pressed_time = dif.seconds
logging.debug('Pressed time = %s', pressed_time)
if pressed_time > 2:
pass
#os.system("sudo shutdown -h now")
GPIO.add_event_detect(channel, GPIO.FALLING, callback=shutdown, bouncetime=200)
##
##
def button_press_switch(channel):
GPIO. remove_event_detect(channel)
print('Button pressed')
pressed_time = datetime.datetime.now()
while not GPIO.input(channel):
time.sleep(.5)
dif = datetime.datetime.now() - pressed_time
pressed_time = dif.seconds
if pressed_time < 2:
button_status = 1
elif pressed_time < 6:
button_status = 2
else:
button_status = 4
print(button_status)
GPIO.add_event_detect(channel, GPIO.FALLING, callback=button_press_switch, bouncetime=200)
##
##
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
def __init__(self, button_pins, bounce_time):
# Set bounce time
self.bounce_time = bounce_time
# Set buttons
self.buttons = button_pins
# Initialize display client
self.display = False
# We don't need warnings from GPIO
GPIO.setwarnings(False)
# Set button GPIO pins as inputs and enable interrupts
for button in button_pins:
if (button_pins[button] != False):
GPIO.setup(button_pins[button], GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.add_event_detect(button_pins[button], GPIO.FALLING, callback=self.button_pressed, bouncetime=self.bounce_time)
# Initalize MPD
self.mpd = False
# Register MPD client to send it commands
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 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.FALLING, callback=lowBattery, bouncetime=300)
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 __initGPIOs(self):
#setup GPIO using Board numbering (pins, not GPIOs)
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setmode(GPIO.BOARD)
#setup defined pins and event_detectors or outputs and initial states (initial is always 0, low)
for pin in pins_in_use:
if pins_in_use[pin][0] == GPIO.IN:
if pin == 5:
GPIO.setup(pin, pins_in_use[pin][0], pull_up_down=GPIO.PUD_UP)
else:
GPIO.setup(pin, pins_in_use[pin][0])
GPIO.add_event_detect(pin, pins_in_use[pin][1], callback=self.shoutItOut, bouncetime=100)
self.gpio_states.update({pin: 1})
elif pins_in_use[pin][0] == GPIO.OUT:
GPIO.setup(pin, pins_in_use[pin][0], initial=0)
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
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)
12_rotaryEncoder.py 文件源码
项目:SunFounder_Super_Kit_V3.0_for_Raspberry_Pi
作者: sunfounder
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
def setup():
global counter
global Last_RoB_Status, Current_RoB_Status
GPIO.setmode(GPIO.BCM)
GPIO.setup(RoAPin, GPIO.IN)
GPIO.setup(RoBPin, GPIO.IN)
GPIO.setup(RoSPin,GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Set up a falling edge detect to callback clear
GPIO.add_event_detect(RoSPin, GPIO.FALLING, callback=clear)
# Set up a counter as a global variable
counter = 0
Last_RoB_Status = 0
Current_RoB_Status = 0
# Define a function to deal with rotary encoder
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 main():
try:
GPIO.setmode(GPIO.BCM)
GPIO.setup(START_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
root = tk.Tk()
root.overrideredirect(True)
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry('{0}x{1}+0+0'.format(width, height))
root.wm_title('Stoppuhr')
stopwatch = Stopwatch(LOG_FILENAME)
GPIO.add_event_detect(START_PIN, GPIO.FALLING, stopwatch.start)
stopwatch_ui = StopwatchUI(root, stopwatch)
stopwatch_ui.pack()
root.mainloop()
finally:
GPIO.cleanup()
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)
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."
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 0:
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.FALLING, callback=powerSwitch, bouncetime=300)
except KeyboardInterrupt:
GPIO.cleanup()
def loop():
GPIO.add_event_detect(ButtonPin, GPIO.FALLING, callback=buttonPress)
while True:
pass
# When running directly, make sure to cleanup GPIO
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 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
def haltSystem():
print 'Halt...'
os.system("sudo halt")
# GPIO.add_event_detect(HALT_PIN, GPIO.FALLING, callback = haltSystem, bouncetime = 2000)
def haltSystem():
print 'Halt...'
os.system("sudo halt")
# GPIO.add_event_detect(HALT_PIN, GPIO.FALLING, callback = haltSystem, bouncetime = 2000)
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)
def loop():
# ???
handler = BaseHandler()
try:
while True:
# ?????
if GPIO.event_detected(GPIOConfig.VOICE_SENSOR):
GPIO.remove_event_detect(GPIOConfig.VOICE_SENSOR)
handler.worker()
GPIO.add_event_detect(GPIOConfig.VOICE_SENSOR, GPIO.FALLING)
time.sleep(0.5)
except KeyboardInterrupt:
pass
GPIO.cleanup()
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 listen(self, callback):
if not callback:
callback = self.callback
GPIO.add_event_detect(self.button_pin,
GPIO.FALLING,
callback=callback,
bouncetime=500)