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
python类RISING的实例源码
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
assistant_button.py 文件源码
项目:ct-google-assistant-sdk
作者: merlinschumacher
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
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.
assistant_mini.py 文件源码
项目:ct-google-assistant-sdk
作者: merlinschumacher
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
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.
controller_rpi.py 文件源码
项目:SX127x_driver_for_MicroPython_on_ESP8266
作者: Wei1234c
项目源码
文件源码
阅读 21
收藏 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
项目源码
文件源码
阅读 21
收藏 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 __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)
14_dice.py 文件源码
项目:SunFounder_Super_Kit_V3.0_for_Raspberry_Pi
作者: sunfounder
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
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
09_ne555.py 文件源码
项目:SunFounder_Super_Kit_V3.0_for_Raspberry_Pi
作者: sunfounder
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
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"