def main(): global Unreaded LCM.lcd_init() LCM.lcd_string(1, "Welcome LEGOMail") LCM.lcd_string(2, "") mail = Thread(target=check_msg, args=()) mail.setDaemon(True) mail.start() # start the bttom monitor GPIO.setup(BtnGPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: try: GPIO.wait_for_edge(BtnGPIO, GPIO.FALLING) # waiting for falling edge interrupt subprocess.call(["aplay", VoiceMsg_path]) # play the received msg LCM.lcd_string(1, "Wait for Msg") if Unreaded: Unreaded = False LCM.lcd_string(2, "Play old Msg") except KeyboardInterrupt: GPIO.remove_event_detect(BtnGPIO) GPIO.cleanup() print "main terminate"
def sendFrame(self, toAddress, buff, requestACK, sendACK): #turn off receiver to prevent reception while filling fifo self.setMode(RF69_MODE_STANDBY) #wait for modeReady while (self.readReg(REG_IRQFLAGS1) & RF_IRQFLAGS1_MODEREADY) == 0x00: pass # DIO0 is "Packet Sent" self.writeReg(REG_DIOMAPPING1, RF_DIOMAPPING1_DIO0_00) if (len(buff) > RF69_MAX_DATA_LEN): buff = buff[0:RF69_MAX_DATA_LEN] self.spi.xfer([REG_FIFO | 0x80, len(buff) + 3, toAddress, self.address]) if sendACK: self.spi.xfer([0x80]) elif requestACK: self.spi.xfer([0x40]) else: self.spi.xfer([0x00]) self.spi.xfer([int(ord(i)) for i in list(buff)]) self.setMode(RF69_MODE_TX) GPIO.wait_for_edge(self.intPin, GPIO.RISING) self.setMode(RF69_MODE_STANDBY)
def main(): mix = mixer.Mixer(MIXER_STEPS) mix.setValue(STARTING_VOLUME) rot = rotary.RotaryEncoder(ROTARY_PIN_1, ROTARY_PIN_2, mix.setValue, mix.getValue(), 0, MIXER_STEPS) play = player.RadioPlayer(announce) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) announce('Radio Pi Started') time.sleep(.5) if internet(): announce('Internet connection found') else: announce('Internet connection not found') time.sleep(.5) while True: sys.stdout.write('Waiting for press...') sys.stdout.flush() GPIO.wait_for_edge(BUTTON_PIN, GPIO.FALLING) print ' button pressed!' play.nextStation() sys.stdout.write('Sleeping...') sys.stdout.flush() time.sleep(.4) print ' done.'
def run(self): while 1: gpio.wait_for_edge(self.sense.pin_number, gpio.RISING) self.sense.current_count += 1 self.sense.write_data_file() if self.sense.stopping: return
def get_audio(): buf = '' # Setup alsa recording interface for "default" sound card rx = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK, 'sysdefault') rx.setchannels(1) rx.setrate(16000) rx.setformat(alsaaudio.PCM_FORMAT_S16_LE) rx.setperiodsize(341) print "jarvis standing by ..." GPIO.wait_for_edge(18, GPIO.FALLING) # Record for minimum of 500ms timer = time.time() + 0.5 print "recording ..." while (not GPIO.input(18)) or (timer > time.time()): size, data = rx.read() if size: buf += data time.sleep(.001) rx.close() print "analyzing ..." return buf
def run(self): # TODO proper synchronization of _running while self._running: GPIO.wait_for_edge(self._pin, GPIO.BOTH) while self._running: current = not GPIO.input(self._pin) # print("read %s" % current) specificWait = 0 if current: self._count += 1 if self._count > self._veryLongClickDelay: self._veryLongClick() # TODO break here and let owner decide return else: if 0 < self._count <= self._clickDelay: self._click() specificWait = 1 elif self._clickDelay < self._count <= self._longClickDelay: self._longClick() specificWait = 2 # TODO why do we wait longer here? self._count = 0 break if specificWait > 0: time.sleep(specificWait) else: time.sleep(self._delay)
def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN, GPIO.PUD_UP) # Wait until someone hits the button GPIO.wait_for_edge(17, GPIO.FALLING) call(["sudo", "shutdown", "-hP", "now"])
def gpio_falling(pin): print('Event detected at ', door_timestamp(0)) starttime = time.time() emailalert() runtime(starttime) GPIO.wait_for_edge(26, GPIO.RISING) return
def output_toggle_on_input_timeout(self, conn): while True: alreadyon = [] GPIO.wait_for_edge(int(self.trigger), GPIO.BOTH) conn.send("inputchange:"+str(self.trigger)+":on") gui.change_input_state(int(self.trigger), 1, "reg") for i in self.who: if outputs[i].input() == 0: alreadyon.append(i) gui.console("Pin already on") else: outputs[i].output(1) gui.change_output_state(int(i), 1) conn.send("pinchange:"+i+":on") targettime = int(time.time()) + int(self.timeout) changed = False while not targettime == int(time.time()): if GPIO.input(int(self.trigger)): if changed: conn.send("inputchange:"+str(self.trigger)+":on") gui.change_input_state(int(self.trigger), 1, "reg") changed = False targettime = int(time.time()) + self.timeout - 3 else: changed = True conn.send("inputchange:"+str(self.trigger)+":off") gui.change_input_state(int(self.trigger), 0, "reg") time.sleep(0.2) for i in self.who: if not i in alreadyon: outputs[i].output(1) conn.send("pinchange:"+i+":off") gui.change_output_state(int(i), 0)
def testWaitForFalling(self): def makelow(): GPIO.output(LOOP_OUT, GPIO.LOW) GPIO.output(LOOP_OUT, GPIO.HIGH) t = Timer(0.1, makelow) t.start() GPIO.wait_for_edge(LOOP_IN, GPIO.FALLING)
def listen(self): try: time.sleep(0.25) GPIO.wait_for_edge(self.pin, GPIO.FALLING) GPIO.output(self.led1, GPIO.HIGH) time.sleep(0.1) GPIO.output(self.led1, GPIO.LOW) GPIO.output(self.led2, GPIO.HIGH) time.sleep(0.1) GPIO.output(self.led2, GPIO.LOW) GPIO.output(self.led3, GPIO.HIGH) time.sleep(0.1) GPIO.output(self.led3, GPIO.LOW) GPIO.output(self.led1, GPIO.LOW) GPIO.output(self.led2, GPIO.LOW) GPIO.output(self.led1, GPIO.HIGH) GPIO.output(self.led2, GPIO.HIGH) GPIO.output(self.led3, GPIO.HIGH) time.sleep(0.1) GPIO.output(self.led3, GPIO.LOW) GPIO.output(self.led1, GPIO.LOW) GPIO.output(self.led2, GPIO.LOW) call(["sudo", "halt"]) else:
def waitForBtn(t=0): sleep(t)#wait a minimum of this many seconds GPIO.output(ledPin,True) #turn the light on while True: #wait for a button press GPIO.wait_for_edge(btnPin1, GPIO.FALLING) time.sleep(0.2) #debounce break
def testWaitForEventSwitchbounce(self): self.finished = False def bounce(): GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.01) GPIO.output(LOOP_OUT, GPIO.LOW) time.sleep(0.01) GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.01) GPIO.output(LOOP_OUT, GPIO.LOW) time.sleep(0.2) GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.01) GPIO.output(LOOP_OUT, GPIO.LOW) time.sleep(0.01) GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.01) GPIO.output(LOOP_OUT, GPIO.LOW) self.finished = True GPIO.output(LOOP_OUT, GPIO.LOW) t1 = Timer(0.1, bounce) t1.start() starttime = time.time() GPIO.wait_for_edge(LOOP_IN, GPIO.RISING, bouncetime=100) GPIO.wait_for_edge(LOOP_IN, GPIO.RISING, bouncetime=100) finishtime = time.time() self.assertGreater(finishtime-starttime, 0.2) while not self.finished: time.sleep(0.1)
def run(self): counter = 0 try: while self.run_event.is_set(): # waiting for interrupt from button press GPIO.wait_for_edge(self.gpio_pin, GPIO.FALLING, timeout=100) sec = 0 state = 0 while GPIO.input(self.gpio_pin) == GPIO.LOW: time.sleep(self.debounce_timer) sec += self.debounce_timer if sec > 2: data = {'data_type': "button", 'action': 'long_press'} self.queue.put(data) if state == 0: counter += 1 data = {'data_type': "button", 'action': 'press'} self.queue.put(data) state = 1 except KeyboardInterrupt: logger.info("BUTTON THREAD INTERRUPT")
def run(self): print "%s start" %(self.processname) while self.processrun: GPIO.wait_for_edge(self.pin, GPIO.FALLING) print "%s get" %(self.processname) GPIO.cleanup() return
def Measure(): start = 0 GPIO.output(TRIGGER, True) time.sleep(0.00001) GPIO.output(TRIGGER, False) channel = GPIO.wait_for_edge(ECHO, GPIO.BOTH, timeout=200) if channel is None: print("Ultrasonic sensor timed out (pre-echo).") GPIO.remove_event_detect(ECHO) restart() # else: # print("Echo start detected") start = time.time() GPIO.wait_for_edge(ECHO, GPIO.BOTH, timeout=400) if channel is None: print("Ultrasonic sensor timed out (post-echo).") GPIO.remove_event_detect(ECHO) restart() # else: # print("Echo finish detected") stop = time.time() elapsed = stop-start distance = (elapsed * 34300)/2 # Using speed of sound at 20C (68F) return distance
def main(): map(pin_change, SOUND_PINS) print "Waiting for Pin 25 to end script." GPIO.wait_for_edge(25, GPIO.RISING) GPIO.cleanup()
def run(self): print "Comparator thread start" GPIO.wait_for_edge(left_com, GPIO.RISING) while 1: leftEdge = not GPIO.input(left_comp) rightEdge = not GPIO.input(right_comp) time.sleep(0.2)
def test_falling(): def cb(chan): print('Callback called - channel %s'%chan) print('Falling edge test') try: GPIO.add_event_detect(SWITCH_PIN, GPIO.LOW) print('Fail- managed to set LOW as an event') except ValueError: pass print('5 second sample for event_detected function') GPIO.add_event_detect(SWITCH_PIN, GPIO.FALLING) time.sleep(5) if GPIO.event_detected(SWITCH_PIN): print('Event detected') else: print('Event not detected') print('5 seconds for callback function') input('Press return to start: ') GPIO.remove_event_detect(SWITCH_PIN); GPIO.add_event_detect(SWITCH_PIN, GPIO.FALLING, callback=cb) time.sleep(5) GPIO.remove_event_detect(SWITCH_PIN); try: GPIO.wait_for_edge(SWITCH_PIN, GPIO.LOW) print('Fail- managed to wait for a LOW as an event') except ValueError: pass print('Blocking wait for falling edge...') GPIO.wait_for_edge(SWITCH_PIN, GPIO.FALLING)
def wait(self): """ Function sets initiation of trigger event. """ import RPi.GPIO as GPIO GPIO.wait_for_edge(self.port, GPIO.FALLING)
def testWaitForRising(self): def makehigh(): GPIO.output(LOOP_OUT, GPIO.HIGH) GPIO.output(LOOP_OUT, GPIO.LOW) t = Timer(0.1, makehigh) t.start() GPIO.wait_for_edge(LOOP_IN, GPIO.RISING)
def test_rising(): def cb(chan): xprint('Callback 1 - this should produce an exception') def cb2(chan): print('Callback 2 called - channel %s'%chan) print('Rising edge test') print('5 second sample for event_detected function') try: GPIO.add_event_detect(LED_PIN, GPIO.RISING) print('Fail - added event to an output, not produced RuntimeError') except RuntimeError: pass GPIO.add_event_detect(SWITCH_PIN, GPIO.RISING) time.sleep(5) if GPIO.event_detected(SWITCH_PIN): print('Event detected') else: print('Event not detected') print('5 seconds for callback function (which should produce exceptions)') input('Press return to start: ') GPIO.add_event_callback(SWITCH_PIN, cb) GPIO.add_event_callback(SWITCH_PIN, cb2) time.sleep(5) GPIO.remove_event_detect(SWITCH_PIN); print('Blocking wait for rising edge...') GPIO.wait_for_edge(SWITCH_PIN, GPIO.RISING)
def _wait_state(self): """Wait state.""" _log.debug('Entering wait state.') gpio.wait_for_edge(self._sensor, gpio.RISING) gpio.remove_event_detect(self._sensor) self._state = self._photograph_state
def wait_for_release(self): if self.boss: port = self.boss_trigger_port else: port = self.employee_trigger_port GPIO.wait_for_edge(port, GPIO.FALLING)
def test_rising(): def cb(chan): print "Callback 1 - this should produce an exception" def cb2(chan): print "Callback 2 called - channel", s, chan print "Rising edge test" print "5 second sample for event_detected function" try: GPIO.add_event_detect(LED_PIN, GPIO.RISING) print "Fail - added event to an output, not produced RuntimeError" except RuntimeError: pass GPIO.add_event_detect(SWITCH_PIN, GPIO.RISING) time.sleep(5) if GPIO.event_detected(SWITCH_PIN): print "Event detected" else: print "Event not detected" print "5 seconds for callback function (which should produce exceptions)" input ("Press return to start: ") GPIO.add_event_callback(SWITCH_PIN, cb) GPIO.add_event_callback(SWITCH_PIN, cb2) time.sleep(5) GPIO.remove_event_detect(SWITCH_PIN); print "Blocking wait for rising edge..." GPIO.wait_for_edge(SWITCH_PIN, GPIO.RISING)
def irqWait(self): # A race condition may occur here. # TODO: Should set a timeout if GPIO.input(self.irq_pin) == 0: return GPIO.wait_for_edge(self.irq_pin, GPIO.FALLING)
def waitButton(boton): global pulsacionCorta global pulsacionLarga global pulsacionOff print "Waiting..." time.sleep(3) GPIO.output(ledRojo,False) GPIO.output(ledVerde,True) GPIO.remove_event_detect(boton) GPIO.wait_for_edge(boton, GPIO.BOTH) stamp = time.time() GPIO.remove_event_detect(boton) GPIO.wait_for_edge(boton, GPIO.BOTH) now = time.time() if now-stamp > 3: print "Pulsacion muy larga" pulsacionCorta=False pulsacionLarga=False pulsacionOff=True elif now-stamp > 1: print "Pulsacion larga" pulsacionCorta=False pulsacionLarga=True pulsacionOff=False else: print "Pulsacion corta" pulsacionCorta=True pulsacionLarga=False pulsacionOff=False
def main(): # Perform checks on startup print("\n##############################") print("Starting Up...\n") checkSwitch() setPrinter() setPartNumber() print("##############################\n") # Create switch events io.add_event_detect(sw_pos1_pin, io.BOTH, callback=sw_callback, bouncetime=100) io.add_event_detect(sw_pos2_pin, io.BOTH, callback=sw_callback, bouncetime=100) io.add_event_detect(sw_pos3_pin, io.BOTH, callback=sw_callback, bouncetime=100) print("Startup Complete") while True: try: print("\nWaiting for Print Button") io.wait_for_edge(btn_pin, io.FALLING, bouncetime=300) print("Button Pressed") printLabel() except KeyboardInterrupt: io.cleanup() exit_program()
def start(): last = GPIO.input(button) while True: val = GPIO.input(button) if val != last: last = val if val == 1 and recorded == True: rf = open(path+'recording.wav', 'w') rf.write(audio) rf.close() inp = None alexa() GPIO.wait_for_edge(button, GPIO.FALLING) elif val == 0: GPIO.output(25, GPIO.HIGH) inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, device) inp.setchannels(1) inp.setrate(16000) inp.setformat(alsaaudio.PCM_FORMAT_S16_LE) inp.setperiodsize(500) audio = "" l, data = inp.read() if l: audio += data recorded = True elif val == 0: l, data = inp.read() if l: audio += data
def get555PulseHighTime(pin): counter = 0; GPIO.wait_for_edge(pin, GPIO.RISING); while GPIO.input(pin) == GPIO.HIGH: counter += 1; time.sleep(0.001); # may try to change this to 0.0001 for more resolution return float(counter);
Add following line to file /etc/rc.local python /home/pi/trigger_shutdown.py & """ import os import RPi.GPIO as GPIO import time shutdown_pin = 21 GPIO.setmode(GPIO.BCM) GPIO.setup(shutdown_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) def shutdown(): os.system("sudo shutdown -h now") while True: if not GPIO.input(shutdown_pin): shutdown() time.sleep(0.5) try: GPIO.wait_for_edge(shutdown_pin, GPIO.FALLING) shutdown() except: pass GPIO.cleanup()
class tyos(): pullup = GPIO.wait_for_edge(channel, GPIO_RISING) pulldown = GPIO.wait_for_edge(channel, GPIO_RISING) def __init__(self): warnings.filterwarnings("ignore") for arg in sys.argv: if arg == '--power': self.POWER_FONA = True print 'Powering FONA on...' else: self.POWER_FONA = False if arg == '--version': print 'TYOS VERSION ' + VERSION sys.exit() self.VERSION = VERSION if self.POWER_FONA: import power power.Power().toggle() time.sleep(10) #Setup fona self.fona = serialport.SerialPort() self.fona.connect() self.set_audio() #Setup some important objects self.scope = framebuffer.pyscope() self.toolbar = toolbar.Toolbar(self.fona) self.apps = apps.App(self.fona) self.reciever = receive.Receive(self.fona) pygame.init() #Setup surface self.WINDOWWIDTH = 320 self.WINDOWHIEGHT = 480 #self.surface = pygame.display.set_mode((self.WINDOWWIDTH, self.WINDOWHIEGHT)) self.surface = pygame.display.set_mode( (self.WINDOWWIDTH, self.WINDOWHIEGHT), pygame.FULLSCREEN) pygame.mouse.set_visible(True) self.clock = pygame.time.Clock() #Colors R G B self.BLUE = (0, 0, 255) self.WHITE = (255, 255, 255) self.BLACK = (0, 0, 0) self.surface.fill(self.WHITE) self.update = True #Setup logo self.logo = pygame.image.load('/home/pi/tyos/graphics/logo.png') self.logo_rect = self.logo.get_rect() self.logo_rect.y = self.surface.get_rect().centery - 50 self.logo_rect.centerx = self.surface.get_rect().centerx #Setup Battery Icon self.bat = pygame.image.load('/home/pi/tyos/graphics/bat.png') self.bat_rect = self.bat.get_rect() self.bat_rect.centery = 15 self.bat_rect.right = self.WINDOWWIDTH - 10 #Setup Low Battery Icon self.low_bat = pygame.image.load('/home/pi/tyos/graphics/low_bat.png') self.low_bat_rect = self.low_bat.get_rect() self.low_bat_rect.centery = 380 self.low_bat_rect.centerx = self.surface.get_rect().centerx #Setup App Toolbar self.app_toolbar = pygame.Rect(0, 0, 320, 30) #Rectangle Dictionary self.rectangles = {'rects': [self.app_toolbar], 'colors': [self.BLACK]} #Reception Rectangle dictionary self.reception_bars = {'rects': [], 'colors': []} #Battery Left Text self.bat_left = { 'surface': self.toolbar.bat_left, 'rects': self.toolbar.bat_left_rect } #Setup fonts self.font = pygame.font.Font('/home/pi/tyos/fonts/arial.ttf', 20) #Setup clock Text self.clock_text = self.font.render('12:00', True, self.WHITE, self.BLACK) self.clock_text_rect = self.clock_text.get_rect() self.clock_text_rect.centerx = self.surface.get_rect().centerx self.clock_text_rect.centery = 15 #Image Dictionary self.images = { 'surfaces': [self.bat], 'rects': [self.bat_rect, self.clock_text_rect] } self.blit_logo = True self.dead_bat = False def set_audio(self): #Set audio in/out to selected from config file try: #See if config file exists self.audio_file = open('/home/pi/tyos/configure/audio.conf', 'r') except: if not os.path.exists( '/home/pi/tyos/configure' ): #If configure directory doesn't exist, create one os.mkdir('/home/pi/tyos/configure') self.audio_file = open( '/home/pi/tyos/configure/audio.conf', 'w+') #Create config file and add some lines self.audio_file.write('#Audio config file\n') self.audio_file.write('mode=1\n') self.audio_file.close() self.audio_file = open('/home/pi/tyos/configure/audio.conf', 'r') file = self.audio_file.readlines() for i in range(0, len(file)): #Parse file if file[i][0] == '#': pass #Do Nothing. Line is comment else: file[i] = file[i].rstrip() if 'mode' in file[ i]: #Extract audio mode: 1=Built in, 0=External mode = file[i] mode = mode.split('=') mode = mode[1] self.fona.transmit('AT+CHFA=' + mode) def blit_time(self): #Convert to 12 hour time then blit it to surface t = time.strftime("%H:%M") if USE_RAW_TIME == 0: if int(t[0] + t[1]) > 12: t = str(int(t[0] + t[1]) - 12) + t[-3:] #t = t.lstrip('0') self.clock_text = self.font.render(t, True, self.WHITE, self.BLACK) self.surface.blit(self.clock_text, self.images['rects'][1]) def home(self): while True: if pullup: os.system( 'sudo sh -c \'echo "1" > /sys/class/backlight/soc\:backlight/brightness\'' ) elif pulldown: os.sytem( 'sudo sh -c \'echo "0" > /sys/class/backlight/soc\:backlight/brightness\'' ) #handle events and clock self.blit_time() self.handle_events() pygame.display.update() self.clock.tick() #Update battery and reception self.reception_bars, self.bat_left, self.update, self.dead_bat = self.toolbar.clock( self.reception_bars, self.bat_left, self.update, self.apps.pixel) #Move images if necessary self.update, self.images, self.rectangles, self.reception_bars, self.bat_left = self.apps.open( self.update, self.images, self.rectangles, self.reception_bars, self.bat_left) #Open app if tapped self.apps.open_app() #Check for calls and sms self.update = self.reciever.check(self.update) #Close app if opened and call coming in if self.reciever.call_coming: self.apps.app_to_open = None self.apps.blit_logo = True #Update if necessary if self.update: self.blit(self.images, self.rectangles, self.reception_bars, self.bat_left) self.update = False def blit(self, surfaces, rects, reception, bat): self.surface.fill(self.WHITE) if self.apps.app_to_open != None: self.blit_logo = False #Blit images using one image but different rectangles for i in self.apps.app_objects[ self.apps.app_to_open].blit_one_surface['rects']: self.surface.blit( self.apps.app_objects[ self.apps.app_to_open].blit_one_surface['surface'], i) #Blit images using multiple images and rectangles for rect, surface in zip( self.apps.app_objects[self.apps.app_to_open].blit['rects'], self.apps.app_objects[ self.apps.app_to_open].blit['surfaces']): self.surface.blit(surface, rect) #Blit all rectangles for rect, color in zip(rects['rects'], rects['colors']): pygame.draw.rect(self.surface, color, rect) #Blit all reception bars for rect, color in zip(reception['rects'], reception['colors']): pygame.draw.rect(self.surface, color, rect) #Blit all images for surface, rect in zip(surfaces['surfaces'], surfaces['rects']): self.surface.blit(surface, rect) #Blit battery Percentage self.surface.blit(bat['surface'], bat['rects']) #Blit logo if self.apps.blit_logo: self.surface.blit(self.logo, self.logo_rect) if self.dead_bat: self.surface.blit(self.low_bat, self.low_bat_rect) if self.apps.logos['rects'][0].y != -50: for surface, rect in zip(self.apps.logos['surfaces'], self.apps.logos['rects']): self.surface.blit(surface, rect) #Blit incoming call if self.reciever.call_coming: for surface, rect in zip(self.reciever.blit['surfaces'], self.reciever.blit['rects']): self.surface.blit(surface, rect) def handle_events(self): for event in pygame.event.get(): self.update = True self.apps.update_app = True self.app_bar = self.apps.check(event) if self.reciever.call_coming: self.reciever.get_events(event)
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) # GPIO 4 set up as input. It is pulled up to stop false signals GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP) #set state variable state = 0 #state FALSE means nothing is running, state 1 means other python is running while True: try: GPIO.wait_for_edge(4, GPIO.FALLING) print "\nFalling edge detected. Now your program can continue with" print "whatever was waiting for a button press." state = not state if state == True: print "\nStart Script" else: print"\nStop Script" time.sleep(0.5) except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit
def pressButton(self): print("Entrei botao") GPIO.wait_for_edge(self.pin_Bdelete, GPIO.FALLING) print("Botao apertado")
# SW-420 Vibration sensor with the Raspberry Pi. # http://www.piddlerintheroot.com/vibration-sensor/ # Pin Map # https://wiki.seeedstudio.com/Grove-Vibration_Sensor_SW-420/ #GPIO SETUP channel_vibr = 20 # Signal Vibrationssensor GPIO.setmode(GPIO.BCM) GPIO.setup(channel_vibr, GPIO.IN) #func_shakehead() #func_mountbody() # https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/ GPIO.wait_for_edge(channel_vibr, GPIO.BOTH) print("Input is LOW => Vibrationsalarm!!!") # my_list = [func_shakehead, func_mountbody] my_list = [func_shakehead, func_mountbody] random.choice(my_list)( ) # function func_shakehead oder func_mountbody nach Zufall aufrufen # release -> Motor/Spulen ohne Strom (zum Drehen des Kopfes verwenden) # https://forums.adafruit.com/viewtopic.php?f=50&t=185502&p=899416&hilit=stepper+release#p899416 # kit1.stepper1.release(); GPIO.cleanup() wartezeit = 5 # Sekunden print("Warte für", wartezeit, "Sekunden")
def btn_sub(btn, sh): while True: GPIO.wait_for_edge(btn, GPIO.BOTH) if GPIO.input(btn) == 1: btn(sh)
def measurePulseWidth(self): ''' PWM frequency is 50 Hz So a pulse width must be under 20 ms The range of the receiver's signal(ON) is 1.0 ~ 2.0 ms 1.0 ms : LOW 1.5 ms : Neutral 2.0 ms : HIGH There is a little delay, 0.01 ~ 0.03 ms For an error, if range is above 2.0 ms, not counted (M-02) [MODE] above 2.0 ms : DOWN under 1.0 ms : UP [SERVO][THRUSTER] max 1.94 ms : DOWN neutral 1.53 ms min 1.13 ms : UP ''' #print(PwmRead.num_cycles) #a = time.time() # mode sum = 0.0 num_error = 0 for i in range(self.num_cycles): GPIO.wait_for_edge(self.pin_mode, GPIO.RISING) start = time.time() GPIO.wait_for_edge(self.pin_mode, GPIO.FALLING) pulse = (time.time() - start) * 1000 * 1000 if (pulse > 900) and (pulse < 2200): sum = sum + pulse else: num_error = num_error + 1 if self.num_cycles != num_error: ave = sum / (self.num_cycles - num_error) if (ave > 700) and (ave < 2300): self.pulse_width[0] = ave # servo sum = 0.0 num_error = 0 for i in range(self.num_cycles): GPIO.wait_for_edge(self.pin_servo, GPIO.RISING) start = time.time() GPIO.wait_for_edge(self.pin_servo, GPIO.FALLING) pulse = (time.time() - start) * 1000 * 1000 if (pulse > 900) and (pulse < 2200): sum = sum + pulse else: num_error = num_error + 1 if self.num_cycles != num_error: ave = sum / (self.num_cycles - num_error) if (ave > 1000) and (ave < 2000): self.pulse_width[1] = ave # thruster sum = 0.0 num_error = 0 for i in range(self.num_cycles): GPIO.wait_for_edge(self.pin_thruster, GPIO.RISING) start = time.time() GPIO.wait_for_edge(self.pin_thruster, GPIO.FALLING) pulse = (time.time() - start) * 1000 * 1000 if (pulse > 900) and (pulse < 2200): sum = sum + pulse else: num_error = num_error + 1 if self.num_cycles != num_error: ave = sum / (self.num_cycles - num_error) ave = round(ave, -2) if (ave > 1000) and (ave < 2000): if (ave < 1100): self.pulse_width[2] = 1100 elif (ave > 1900): self.pulse_width[2] = 1900 else: self.pulse_width[2] = ave #b = time.time() - a #print("It takes ", b, "[s] to measure PWM") return
if GPIO.input(HNDNDSCHLTR) == 0: break hand(STOP) await asyncio.sleep(1) print("handstopped") save_cntr(cntr) await printtask #Startup print("startup") if GPIO.input(SCHE1) == 0: schere(BACKWARD) GPIO.wait_for_edge(SCHE1, GPIO.RISING) schere(STOP) print("schere ok") if GPIO.input(HNDNDSCHLTR) == 1: hand(BACKWARD) GPIO.wait_for_edge(HNDNDSCHLTR, GPIO.FALLING) hand(STOP) print("hand ok") #Add event callbacks GPIO.add_event_callback(SHTDWN, shutdown) print("before main loop")
def StartDetection(self): oldtime = 0 edges = [] timeout = 10000 while True: res = GPIO.wait_for_edge(23, GPIO.BOTH, timeout=timeout) now = time() if res != None: edges.append(now) timeout = int(self.pulse_lenght * 1000) if timeout < 20: timeout = 20 continue if len(edges) == 0: timeout = 10000 continue #TimeStamp timestamp = edges[0] #Calculate pulse length and increase count pulselenght = edges[-1] - edges[0] #Calculate period period = edges[-1] - oldtime oldtime = edges[-1] #Bounces bounces = len(edges) #Clear databuffer. edges = [] self.PulseCounter += 1 if self.auto_pulselenght: self.pulse_lenght_buf.append(pulselenght) self.pulse_lenght_buf = self.pulse_lenght_buf[-100:] self.pulse_lenght = sum(self.pulse_lenght_buf) / len( self.pulse_lenght_buf) #print self.pulse_lenght, self.pulse_lenght_buf #Check pulse lenght. PulseDeviation = fabs(pulselenght - self.pulse_lenght) self.SendIOEvent(str("%.3f" % timestamp), "%.2f" % period, str(self.PulseCounter), "%.3f" % pulselenght, str(bounces), "%.5f" % PulseDeviation) if self.debug: print( "%.2f Pin: %i \tCount: %i \tPulse lenght: %.3f Bounces: %i \tPeriod: %.3f \tPulseDeviation: %.5f" % (timestamp, self.pin, self.PulseCounter, pulselenght, bounces, period, PulseDeviation)) self.CountEnergy(timestamp, pulselenght, bounces, PulseDeviation)
#!/usr/bin/env python import RPi.GPIO as GPIO from time import sleep import atexit #Variables to change as needed btn_pin = 18 # pin for the button debounce = 0.3 # how long to debounce the button. Add more time if the button triggers too many times. #GPIO setup GPIO.setmode(GPIO.BOARD) GPIO.setup(btn_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) def cleanup(): print('Goodbye.') GPIO.cleanup() atexit.register(cleanup) print('Push Button') print('Press Ctrl+C to exit') while True: GPIO.wait_for_edge(btn_pin, GPIO.FALLING) sleep(debounce) print("Button pressed")
#print "it will connect GPIO port 23 (pin 16) to GND (pin 6)\n" #print "You will also need a second button connected so that when pressed" #print "it will connect GPIO port 24 (pin 18) to 3V3 (pin 1)\n" #print "You will also need a third button connected so that when pressed" #print "it will connect GPIO port 17 (pin 11) to GND (pin 14)" #raw_input("Press Enter when ready\n>") # when a falling edge is detected on port 17, regardless of whatever # else is happening in the program, the function my_callback will be run GPIO.add_event_detect(18, GPIO.BOTH, callback=recording_callback, bouncetime=300) # when a falling edge is detected on port 23, regardless of whatever # else is happening in the program, the function my_callback2 will be run # 'bouncetime=300' includes the bounce control written into interrupts2a.py GPIO.add_event_detect(17, GPIO.BOTH, callback=playback_callback, bouncetime=300) try: print "Listening for stomps..." GPIO.wait_for_edge(24, GPIO.RISING) #print "Rising edge detected on port 24. Here endeth the third lesson." except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit
writeRegister8(STMPE_TSC_CFG, STMPE_TSC_CFG_8SAMPLE | STMPE_TSC_CFG_DELAY_1MS | STMPE_TSC_CFG_SETTLE_1MS) writeRegister8(STMPE_TSC_FRACTION_Z, 0x6) writeRegister8(STMPE_FIFO_TH, 1) writeRegister8(STMPE_FIFO_STA, STMPE_FIFO_STA_RESET) writeRegister8(STMPE_FIFO_STA, 0) # unreset writeRegister8(STMPE_TSC_I_DRIVE, STMPE_TSC_I_DRIVE_50MA) writeRegister8(STMPE_INT_CTRL, STMPE_INT_CTRL_EDGE | STMPE_INT_CTRL_ENABLE) writeRegister8(STMPE_INT_EN, STMPE_INT_EN_TOUCHDET) writeRegister8(STMPE_INT_STA, 0xFF) # reset all ints # MAIN LOOP ---------------------------------------------------------------- foo = [ 0,0,0,0 ] while True: r = gpio.wait_for_edge(irqPin, gpio.FALLING, timeout=1) if r is None: # no edge detected continue blat = True while readRegister8(STMPE_TSC_CTRL) & 0x80: # Allow conversion time before 1st reading, # also prevents heavy CPU load; 40 fps is ample time.sleep(1.0 / 30.0) # 30 FPS avoids glitches for i in range(4): foo[i] = spi.xfer2([0xD7, 0])[1] x = ( foo[0] << 4) | (foo[1] >> 4) y = ((foo[1] & 0x0F) << 8) | foo[2]
for x in range(0, 5): GPIO.output(getReady, True) time.sleep(0.1) GPIO.output(getReady, False) time.sleep(0.1) GPIO.output(pose, True) time.sleep(0.1) GPIO.output(pose, False) time.sleep(0.1) GPIO.output(uploading, True) time.sleep(0.1) GPIO.output(uploading, False) time.sleep(0.1) GPIO.output(done, True) time.sleep(0.1) GPIO.output(done, False) time.sleep(0.1) GPIO.output(lightingTrigger, False) show_image(real_path + "/res/intro.png") while True: GPIO.output( getReady, True) #turn on the light showing users they can push the button input(pygame.event.get() ) # press escape to exit pygame. Then press ctrl-c to exit python. GPIO.wait_for_edge(buzzer, GPIO.FALLING) time.sleep(config.debounce) #debounce start_photobooth()
def wait_for_button(edge): if edge == 'falling': GPIO.wait_for_edge(SPIN, GPIO.FALLING) else: GPIO.wait_for_edge(SPIN, GPIO.RISING) return True
ads1262_Reg_Read(ADC2FSC0) #Ch 1 enabled, gain 6, connected to electrode in sleep(.01) ads1262_Reg_Read(ADC2FSC1) #Ch 1 enabled, gain 6, connected to electrode in sleep(.01) print("finished") sleep(1) #long nap before starting the conversion (data reading) #set start high to begin reading conversion data datafile = open(fileName, 'w') startime = time() errorcount = 0 while 1: GPIO.output(STRT, 1) incoming = GPIO.wait_for_edge(DRDY, GPIO.FALLING, timeout=100) datain = spi.readbytes(6) GPIO.output(STRT, 0) ads1262_Reg_Write(INPMUX, 0x89) #change to thermocouple input (Ain8 + and Ain9 -) if datain[5] != sum(datain[1:5]) + 0x9B & 255: print("ERRO2") combined_data = datain[1] << 24 | datain[2] << 16 | datain[ 3] << 8 | datain[4] if (combined_data & (1 << 31)) != 0: combined_data = combined_data - (1 << 32) ads1262_Reg_Write(MODE2, 0x09) O2_data = combined_data * (2.5 / 2**31) GPIO.output(STRT, 1) GPIO.wait_for_edge(DRDY, GPIO.FALLING) datain = spi.readbytes(6)
def wait_for_press(): GPIO.wait_for_edge(self.pin,GPIO.FALLING,timeout=100)
delay_length.append(delay) if tones[i_tone] == 0:#standard ###set LEDs as green### pixels.fill(green) trig = 1 elif tones[i_tone] == 1:#targets ###set LEDs as blue### pixels.fill(blue) trig = 2 trig_type.append(trig) GPIO.output(pi2trig(trig),1) trig_time.append(time.time() - start_exp) ###now try and get a response### start_resp = time.time() wait_resp = 0 edge_detect = GPIO.wait_for_edge(pin,GPIO.RISING, timeout = 1000) if edge_detect is not None: GPIO.output(pi2trig(255),0) resp = time.time() - start_resp resp_time.append(resp) GPIO.output(pi2trig(int(tones[i_tone])+3),1) time.sleep(1 - resp) wait_resp = 1 GPIO.output(pi2trig(255),0) pixels.fill(blank) start_resp = time.time() edge_detect = GPIO.wait_for_edge(pin,GPIO.RISING, timeout = int(delay*1000)) if edge_detect is not None and wait_resp == 0: GPIO.output(pi2trig(255),0) resp = time.time() - start_resp resp_time.append(resp)
def get_input(pin): global count while True: GPIO.wait_for_edge(pin, GPIO.FALLING) print 'Button pressed' count = count+1
# -*- coding: utf-8 -*- # Start with the usual... import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) # PUD_UP because GND GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Another Example while True: try: GPIO.wait_for_edge(7, GPIO.FALLING) # Waiting print "Hello World!" except KeyboardInterrupt: GPIO.cleanup() # clean up GPIO on CTRL+C exit GPIO.cleanup() # clean up GPIO on normal exit
import RPi.GPIO as GPIO import time KEY = 20 GPIO.setmode(GPIO.BCM) GPIO.setup(KEY, GPIO.IN, GPIO.PUD_UP) while True: GPIO.wait_for_edge(KEY, GPIO.RISING, bouncetime=200) print('KEY PRESS')
print("Relays 1 & 2 on ") # echo which relay/s on print(elapsed_time) return def relay_1_ctl_off(arg): print("Relay 1 selected -timer started - rising") start_time = time.time() elapsed_time == 0 return GPIO.add_event_detect(Input_Button_1, GPIO.RISING, callback=relay_1_ctl_off, bouncetime=200) GPIO.wait_for_edge(Input_Button_1, GPIO.RISING) GPIO.add_event_detect(Input_Button_1, GPIO.FALLING, callback=relay_1_ctl_on, bouncetime=200) GPIO.wait_for_edge(Input_Button_1, GPIO.FALLING) while True: try: if (GPIO.input(Input_Button_2)): print("Relay 2 on") GPIO.output(Output_Relay_2, GPIO.HIGH) # turn relay 2 on if (GPIO.input(Input_Button_3)): print("Relay 3 on") GPIO.output(Output_Relay_3, GPIO.HIGH) # turn relay 3 on
import RPi.GPIO as GPIO import os import time GPIO.setmode(GPIO.BCM) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) time.sleep(0.5) GPIO.wait_for_edge(13, GPIO.RISING) print("Shutting down, NOW!") os.system("shutdown -h now") GPIO.cleanup()
time.sleep(SLEEP_TIME) set_color(0x000000) time.sleep(SLEEP_TIME) return # ----------------------------------------------------------------------------- blink_light(3, 0xFFFF00) set_color(0x00FF00) GPIO.setup(POWER_BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_UP) # PIN 5 on board (GND to 6) # Wait for the power button to be pressed GPIO.wait_for_edge(POWER_BUTTON, GPIO.FALLING) blink_light(5, 0xFF0000) # Display image before shutdown happens image_view = '/usr/bin/fbi -T 2 -once -t 5 -noverbose' image_view += ' -a /root/winners-dont-use-drugs.png' os.system(image_view) # set up GPIO output channel for SHUTDOWN, RED, LED GPIO.cleanup() # Shut us down! subprocess.call(['shutdown', '-h', 'now'], shell=False)
def wait4button(self): GPIO.wait_for_edge(self.button, GPIO.RISING) j.debug("button press")
import time import RPi.GPIO as GPIO PIN_RADAR = 4 # #define PIN_RADAR 2 GPIO.setmode(GPIO.BCM) GPIO.setup(PIN_RADAR, GPIO.IN) try: # void loop() while True: NUM_CYCLES = 2 start = time.time() for impulse_count in range(NUM_CYCLES): GPIO.wait_for_edge(PIN_RADAR, GPIO.FALLING) duration = time.time() - start # seconds to run for loop frequency = NUM_CYCLES / duration # in Hz #speed = frequency / float(31.36) # 31.36 Hz to MPH according to sensor datasheet speed = frequency / float( 19.49) # 19.49 Hz to KMH according to sensor datasheet print(speed) except KeyboardInterrupt: # press Ctrl + C to stop GPIO.cleanup()
#!/usr/bin/env python3 import subprocess import RPi.GPIO as GPIO LEDPIN = 23 # Our chosen LED pin to blink during shutdown (laser pin) PWRBTN = 3 # FYI, Pin 3 on the Pi ships with a physical pull-up resistor attached GPIO.setmode(GPIO.BCM) GPIO.setup(PWRBTN, GPIO.IN) GPIO.wait_for_edge(PWRBTN, GPIO.FALLING) # Stop all synth and send shutdown command print("Calling 'stopsynth'") subprocess.call(['stopsynth']) print("Executing shutdown -h now command") subprocess.call(['shutdown', '-h', 'now']) GPIO.cleanup() # Disable all previous GPIO settings GPIO.setmode(GPIO.BCM) GPIO.setup(LEDPIN, GPIO.OUT) # Blink the LED wired to the our chosen LED pin while True: GPIO.output(LEDPIN, 1) # Turn on sleep(0.1) GPIO.output(LEDPIN, 0) # Turn off sleep(0.1)
def _working(self): while True: GPIO.wait_for_edge(21, GPIO.BOTH) # GPIO.FALLING 下降 GPIO.RISING 上升 print(f'state={GPIO.input(21)}')
#set LED to OFF GPIO.output(ledPin, GPIO.LOW) def map_pots(start, finish): # change this math based on experiments scaled_start = start / 1 scaled_finish = finish / 1 return scaled_start, scaled_finish while True: #wait for button to be pressed time.sleep(0.2) GPIO.wait_for_edge(buttonPin, GPIO.FALLING) frames = [] try: stream = audio.open(format = FORMAT,rate = RATE,channels = CHANNELS, \ input_device_index = dev_index,input = True, \ frames_per_buffer=CHUNK) #turn on LED when recording starts GPIO.output(ledPin, GPIO.HIGH) print("Recording") #record as long as button held down while GPIO.input(buttonPin) == 1: print("button held down") data = stream.read(CHUNK) frames.append(data)
time.sleep(config.restart_delay) show_image(real_path + "/start.png") GPIO.output(config.led_pin, True) #turn on the LED #################### ### Main Program ### #################### ## clear the previously stored pics based on config settings if config.clear_on_startup: clear_pics(1) print "Photo booth app running..." for x in range(0, 5): #blink light to show the app is running GPIO.output(config.led_pin, True) sleep(0.25) GPIO.output(config.led_pin, False) sleep(0.25) show_image(real_path + "/start.png") while True: GPIO.output(config.led_pin, True) #turn on the light showing users they can push the button input(pygame.event.get() ) # press escape to exit pygame. Then press ctrl-c to exit python. GPIO.wait_for_edge(config.btn_pin, GPIO.FALLING) time.sleep(config.debounce) #debounce start_photobooth()
q = i * i + j * j + k * k + w * w if q > 0.99 and q < 1.01: print str(i) + ", " + str(j) + ", " + str(k) + ", " + str(w) if __name__ == "__main__": GPIO.setmode(GPIO.BCM) GPIO.setup(BNO_INTN, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(BNO_RSTN, GPIO.OUT, initial=GPIO.HIGH) GPIO.output(BNO_RSTN, 0) time.sleep(0.1) GPIO.output(BNO_RSTN, 1) GPIO.wait_for_edge(BNO_INTN, GPIO.FALLING, timeout=1000) #first all 0 bus.read_i2c_block_data(address, 0, 18) time.sleep(0.01) #enable 100Hz GRV bus.write_i2c_block_data(address, 0x05, enableSensor) while True: if GPIO.input(BNO_INTN): GPIO.wait_for_edge(BNO_INTN, GPIO.FALLING, timeout=1) if GPIO.input(BNO_INTN) == False: sensorData = bus.read_i2c_block_data(address, 0, 18) #print sensorData printSensor(sensorData) # else: