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)
python类remove_event_detect()的实例源码
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 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 rightCounterOld(channel):
global rightCount, lastR, intCountR
intCountR += 1
val = GPIO.input(lineRight)
time.sleep(0.02)
if val == GPIO.input(lineRight) and val != lastR:
rightCount -= 1
lastR = val
if rightCount <= 0:
a.ChangeDutyCycle(0)
b.ChangeDutyCycle(0)
GPIO.remove_event_detect (channel)
print "Done right", intCountR
# ======== End of Old deprecated functions =========
# End of Motor Functions
#======================================================================
#======================================================================
# RGB LED Functions
# (Full version only)
#
# setLED(LED, Red, Green, Blue): Sets the LED specified to required RGB value. 0 >= LED <= 3; 0 <= R,G,B <= 4095
def stop():
global _running
_running = False
cg.send("\nAlarm Cycles Finished\n")
cg.ifttt('PiAlarm_SendText', {'value1': 'PiAlarm Completed'})
# Cleanup tasks:
all_off.run()
GPIO.remove_event_detect(off_button)
#
# GPIO.cleanup() # Removed to avoid interference with clock
#
# release_PWM(pin_shaker)
# etc...
# # Then stop pi-blaster for good measure:
# stopPiB = "sudo kill $(ps aux | grep [b]laster | awk '{print $2}')"
# subprocess.call(stopPiB, shell=True)
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 remove_callback(self, io_number):
if self.importlib is not None:
GPIO.remove_event_detect(io_number)
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 cleanup():
""" Function to cleanup raspberry pi GPIO at end of code """
# Restore GPIO to default state
GPIO.remove_event_detect(15) #Add to end of function
GPIO.cleanup()
print("GPIO cleaned!")
def ignore(self):
GPIO.remove_event_detect(self.button_pin)
def wait_for_press(self):
"""Waits for the button to be pressed.
This method blocks until the button is pressed.
"""
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)
controller_rpi.py 文件源码
项目:SX127x_driver_for_MicroPython_on_ESP8266
作者: Wei1234c
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
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
controller_rpi.py 文件源码
项目:SX127x_driver_for_MicroPython_on_ESP8266
作者: Wei1234c
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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 eventEnd(self, object=0):
# eventEnd()
# eventEnd(object)
# ** object: set Interrupt pin: 1=Button, 2=Encoder >> default: 0(all)
if self.__eventStatus!=0x00:
if (object==0 or object==1) and self.__eventStatus&0x03!=0x00:
GPIO.remove_event_detect(self.PinSW)
self.__eventStatus&=0xFC
if (object==0 or object==2) and self.__eventStatus&0x0C!=0x00:
GPIO.remove_event_detect(self.PinA )
self.__eventStatus&=0xF3
def stop(self):
GPIO.remove_event_detect(self.clockPin)
GPIO.remove_event_detect(self.buttonPin)
def leftCounterOld(channel):
global leftCount, lastL, intCountL
intCountL += 1
val = GPIO.input(lineLeft)
time.sleep(0.02)
if val == GPIO.input(lineLeft) and val != lastL:
leftCount -= 1
lastL = val
if leftCount <= 0:
p.ChangeDutyCycle(0)
q.ChangeDutyCycle(0)
GPIO.remove_event_detect (channel)
print "Done left", intCountL
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 stop(self):
GPIO.remove_event_detect(self.clockPin)
GPIO.remove_event_detect(self.switchPin)
def __exit__(self, exc_type, exc_value, traceback):
for channel in self._inputs_by_channel:
GPIO.remove_event_detect(channel)
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)
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()
def del_sensor(self):
GPIO.remove_event_detect(self.pin)
def clear_events(self):
GPIO.remove_event_detect(self.pin)
self.has_callback = False
# Alias handlers
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)
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))