def loop(): print "PRET" presence = time.time() while True: if GPIO.input(GPIO_MODE) == GPIO.HIGH: print "PRESSION" # declenchement par pression if GPIO.event_detected(GPIO_BOUTON): print "PLAY" play() else: print "DISTANCE" # declenchement par presence distance = mesure() print "distance: %d cm" %(distance) # declenchement par pression if GPIO.event_detected(GPIO_BOUTON): print "PLAY" play() else: if distance > PROXIMITE: presence = time.time() else: if time.time() - presence > DELAI: print "PLAY" play() presence = time.time() else: print "DELAI PRESENCE" # attendre une seconde avant de tester a nouveau time.sleep(0.5)
def main(): try: output_test() global psu global hw_off_time global ch_off_time psu=False log("Running...") while True: start_loop=time.time() if GPIO.event_detected(hw_switch): real,ptime = button_press(hw_switch) if real and ptime > 1.5: # Long press on left button means toggle main power psu=activate_board(not get_gpio_state(psu_relay)) elif real: # Toggle HW if psu: state = hw_state(not get_gpio_state(hw_on_relay)) else: error_flash() elif GPIO.event_detected(ch_switch): real,ptime = button_press(ch_switch) if real: if psu: state=ch_state(not get_gpio_state(ch_on_relay)) else: error_flash() else: if psu: schedule() active(psu) rest(psu,start_loop) finally: print "Cleaning up" GPIO.cleanup() server.stop()
def __init__(self): print("START") self.selfpath = path.abspath(path.dirname(__file__)) + "/" print(self.selfpath) parser = argparse.ArgumentParser() parser.add_argument("alarmName") args = parser.parse_args() self.section = args.alarmName self.config = configparser.ConfigParser() self.config.read(self.selfpath + "config") loop = self.config.get(self.section, 'Loop') self.audiofile = self.selfpath + self.config.get(self.section, 'SoundFile') print(self.audiofile) self.volume = float(self.config.get(self.section, 'Volume')) self.player = Gst.ElementFactory.make("playbin", "player") fakesink = Gst.ElementFactory.make("fakesink", "fakesink") self.player.set_property("video-sink", fakesink) audiosink = Gst.ElementFactory.make("alsasink", "alsasink") self.player.set_property("audio-sink", audiosink) if os.path.exists(self.audiofile): if(loop == '1'): self.player.connect("about-to-finish",self._loop) self.player.set_property("volume", self.volume) self.player.set_property("uri", "file://" + self.audiofile) self.player.set_state(Gst.State.PAUSED) bus = self.player.get_bus() if(loop == '1' ): automute = float(self.config.get(self.section, 'AutoMute'))*60 else: bus.timed_pop_filtered(Gst.CLOCK_TIME_NONE, Gst.MessageType.ASYNC_DONE) automute = math.ceil(self.player.query_duration(Gst.Format.TIME)[1]/1000000000) self.player.set_state(Gst.State.PLAYING) startAlarm=time.perf_counter() while (time.perf_counter()-startAlarm < automute) and (True): time.sleep(1) if GPIO.event_detected(24): self._reschedule() print("Button repeat") break if GPIO.event_detected(23): print("Button stop") break self.player.set_state(Gst.State.NULL) GPIO.cleanup() else: print("No such file") print("END")
def main(): """ Main Funtion: Runs in constant while loop checking status of alarm (on/off), If alarm on it calls F_Alarm_Active function """ #set up initial variables Alarm1_Happened = False Alarm2_Happened = False Alarm1ButtonPressed = False # IR Button Input for deactivating alarm Alarm2ButtonPressed = False Alarm1Time = 1 Alarm2Time = 1 LEDFlash = False Buzzer = False Alarm_Number = None try: while True: try: with open('Alarm1Active.pickle' , 'rb') as A1: Alarm1Active = pickle.load(A1) except EOFError: Alarm1Active = Alarm1Active if Alarm1Active or Alarm1_Happened: Alarm_Number = 1 Alarm1Time = Get_AlarmTime_in_Seconds(Alarm1Time, Alarm_Number) ActualTime = Get_ActualTime_in_Seconds() if GPIO.event_detected(8): Alarm1ButtonPressed = F_AlarmButtonPressed() [Alarm1_Happened, Alarm1ButtonPressed, LEDFlash, Buzzer] = F_Alarm_Active(Alarm1Time, ActualTime, \ Alarm1ButtonPressed, LEDFlash, Buzzer, Alarm1_Happened) else: sleep(0.5) #preserve processor try: with open('Alarm2Active.pickle' , 'rb') as A2: Alarm2Active = pickle.load(A2) except EOFError: Alarm2Active = Alarm2Active if Alarm2Active or Alarm2_Happened: Alarm_Number = 2 Alarm2Time = Get_AlarmTime_in_Seconds(Alarm2Time, Alarm_Number) ActualTime = Get_ActualTime_in_Seconds() if GPIO.event_detected(7): Alarm2ButtonPressed = F_AlarmButtonPressed() [Alarm2_Happened, Alarm2ButtonPressed, LEDFlash, Buzzer] = F_Alarm_Active(Alarm2Time, ActualTime, \ Alarm2ButtonPressed, LEDFlash, Buzzer, Alarm2_Happened) else: sleep(0.5) #preserve processor except KeyboardInterrupt: print ("Keyboard Interuption in main") GPIO.cleanup() quit()
def button_test(self, but): return False if self.last_button != None and (time.time() - self.last_button) < 5: ### clear any events until then GPIO.event_detected(but) return False if GPIO.event_detected(but): self.last_button = time.time() #GPIO.remove_event_detect(but) return True return False
def testRisingEventDetected(self): GPIO.output(LOOP_OUT, GPIO.LOW) GPIO.add_event_detect(LOOP_IN, GPIO.RISING) time.sleep(0.01) self.assertEqual(GPIO.event_detected(LOOP_IN), False) GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.01) self.assertEqual(GPIO.event_detected(LOOP_IN), True) GPIO.output(LOOP_OUT, GPIO.LOW) time.sleep(0.01) self.assertEqual(GPIO.event_detected(LOOP_IN), False) GPIO.remove_event_detect(LOOP_IN)
def standby(): for team in teams: # All teams are in the next question team.alive = True GPIO.output(team.led_op, False) GPIO.output(team.led_table, False) GPIO.wait_for_edge(op, GPIO.RISING) # Clean up team event detection for team in teams: GPIO.event_detected(team.button) GPIO.remove_event_detect(op) state = QUESTION
def testFallingEventDetected(self): GPIO.output(LOOP_OUT, GPIO.HIGH) GPIO.add_event_detect(LOOP_IN, GPIO.FALLING) time.sleep(0.01) self.assertEqual(GPIO.event_detected(LOOP_IN), False) GPIO.output(LOOP_OUT, GPIO.LOW) time.sleep(0.01) self.assertEqual(GPIO.event_detected(LOOP_IN), True) GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.01) self.assertEqual(GPIO.event_detected(LOOP_IN), False) GPIO.remove_event_detect(LOOP_IN)
def boo(): if GPIO.event_detected(powerButton): if(DEBUG):print("Wait 2 seconds") time.sleep (2) #After button press wait 2 seconds if GPIO.input(powerButton): #Test for continued button press. If not pressed run brew script. if(DEBUG):print("Run Brew script") os.system('/home/pi/Ridiculous/brew.sh') # Execute the brew.sh bash script. zeroMode() # Clear the accidental button presses. elif GPIO.input(powerButton) == False: # If button press continues, wait 3 more seconds. if(DEBUG):print("Waiting 2 more") os.system('/home/pi/Ridiculous/vibrate.sh') # Effector movement to signal that the \ zeroMode() time.sleep (2) if GPIO.input(powerButton): #If button press does not continue, run the cable function. if(DEBUG):print("Clearing zero position") os.system('/home/pi/Ridiculous/clear_coordinates.sh') # Execute the brew.sh bash script. #os.system('/home/pi/Ridiculous/all_tighten.sh') zeroMode() if GPIO.input(powerButton) == False: # If button press continues, wait 3 more seconds. if(DEBUG):print("Waiting another 2 seconds.") os.system('/home/pi/Ridiculous/vibrate.sh') # Effector movement to signal that the \ zeroMode() time.sleep (2) if GPIO.input(powerButton): #If button press does not continue, run the cable function. if(DEBUG):print("Going into cable") cable() elif GPIO.input(powerButton) == False: #If button press still continues, run shutdown script. if(DEBUG):print("Shutting Down") os.system('/home/pi/Ridiculous/vibrate.sh') # Effector movement to signal that the \ time.sleep (2) os.system('sudo shutdown -h now') # Execute the brew.sh bash script. if GPIO.event_detected(northButton): if(DEBUG):print("North button pressed") os.system('/home/pi/Ridiculous/north.sh') #Moves effector "north" by a step number specified in "north.sh" if GPIO.event_detected(westButton): if(DEBUG):print("West button pressed") os.system('/home/pi/Ridiculous/west.sh') #Moves effector "west" by a step number specified in "west.sh" if GPIO.event_detected(eastButton): if(DEBUG):print("East button pressed") os.system('/home/pi/Ridiculous/east.sh') #Moves effector "east" by a step number specified in "east.sh" if GPIO.event_detected(southButton): if(DEBUG):print("South button pressed") os.system('/home/pi/Ridiculous/south.sh') #Moves effector "south" by a step number specified in "south.sh"
def EDO11(entrada): global estado global repetir_id_qr_code_string global id_qr_code_string global flag_usuario_nova_garrafa global pontos global array_garrafas global usuario global mylcd print ('Estado 11') mylcd.lcd_clear() #GPIO.cleanup() print ("Deseja inserir mais uma garrafa?") mylcd.lcd_display_string(" Deseja inserir mais", 1) mylcd.lcd_display_string("garrafa? ", 2) time.sleep(2) # motor(-4800) try: if (GPIO.event_detected(35) == True) and (GPIO.event_detected(37) == False): repetir_id_qr_code_string = id_qr_code_string flag_usuario_nova_garrafa = 1 estado = 1 mylcd.lcd_clear() print('Pontuacao atual: %d . ' % (pontos)) mylcd.lcd_display_string("Pontuacao atual: %d" %(pontos), 1) time.sleep(0.3) elif (GPIO.event_detected(37) == True) and (GPIO.event_detected(35) == False): flag_usuario_nova_garrafa = 0 estado = 0 data_array_garrafas = {"bottles" : array_garrafas} url_operation = API_ENDPOINT_OPERATION + usuario['id'] + "/operation" #Se o qr_code_string for uma string ok, se não alterar r_operation = requests.post(url = url_operation, data = data_array_garrafas) mylcd.lcd_clear() print('Pontuação final: %d . ' % (pontos)) mylcd.lcd_display_string("Pontuacao final: %d" %(pontos), 1) pontos = 0 array_garrafas = [] time.sleep(15) GPIO.output(7,GPIO.LOW) else: estado = 11 except: mylcd.lcd_clear() print ("Deseja inserir mais uma garrafa? ") mylcd.lcd_display_string(" Deseja inserir mais", 1) mylcd.lcd_display_string("garrafa? ", 2) estado = 11
def main(): while (True): if GPIO.event_detected(BUTTON_PIN): # Check to see if button has been pushed activate = True while (activate is True): # Execute this code until the button is pushed again GPIO.output(LED_PIN, True) # Turn LED on sleep(0.01) GPIO.output(LED_PIN, False) # Turn LED off sleep(0.01) if GPIO.event_detected(BUTTON_PIN): # Check for a 2nd button push activate = False else: GPIO.output(LED_PIN, False) # Turn LED off
def testBothEventDetected(self): GPIO.output(LOOP_OUT, GPIO.LOW) GPIO.add_event_detect(LOOP_IN, GPIO.BOTH) time.sleep(0.001) self.assertEqual(GPIO.event_detected(LOOP_IN), False) GPIO.output(LOOP_OUT, GPIO.HIGH) time.sleep(0.001) self.assertEqual(GPIO.event_detected(LOOP_IN), True) self.assertEqual(GPIO.event_detected(LOOP_IN), False) GPIO.output(LOOP_OUT, GPIO.LOW) time.sleep(0.001) self.assertEqual(GPIO.event_detected(LOOP_IN), True) GPIO.remove_event_detect(LOOP_IN)
def autoriser(self): GPIO.add_event_detect(10, GPIO.RISING) GPIO.add_event_detect(11, GPIO.RISING) GPIO.add_event_detect(12, GPIO.RISING) GPIO.add_event_detect(13, GPIO.RISING) if GPIO.event_detected(10): Buzzer.repondre(1) if GPIO.event_detected(11): Buzzer.repondre(2) if GPIO.event_detected(12): Buzzer.repondre(3) if GPIO.event_detected(13): Buzzer.repondre(4)
def bakePie(): while True: global yellowScored global blackScored yellowScored = False blackScored = False if GPIO.event_detected(yellowPin): print "yellow goal!" yellowScored = True elif GPIO.event_detected(blackPin): print "black goal" blackScored = True time.sleep(1)
def answer(team_buzzed): # Turn off all teams that failed to answer for team in teams: if team is not team_buzzed: GPIO.output(team.led_table, False) # Light up the team on the operator board GPIO.output(team_buzzed.led_op, True) # Wait for them to answer if GPIO.event_detected(yes): state = STANDBY elif GPIO.event_detected(no): state = QUESTION team_buzzed.alive = False
def main(): global number if(GPIO.event_detected(btnDecrease)): if(number==0): number=8 number=number-1 listOfDigits=changeToBinary(number) turnOnLeds(listOfDigits) elif(GPIO.event_detected(btnIncrease)): if(number==7): number=-1 number=number+1 listOfDigits=changeToBinary(number) turnOnLeds(listOfDigits)
def test_event_detected(): GPIO_DEVEL.Reset() GPIO.setmode(GPIO.BCM) GPIO.add_event_detect(18, GPIO.FALLING, bouncetime=1) GPIO.event_detected(18) assert GPIO.event_detected(18) == False # Manufacture a false positive GPIO_DEVEL.State_Access().event_ls.append(18) assert GPIO.event_detected(18) == True GPIO_DEVEL.Reset()
def main(): global count #Set count to zero when seven is reached if GPIO.event_detected(13): if (count==7): count =0 else: count = count +1 #Set count to seven when zero is reached elif GPIO.event_detected(15): if (count==0): count = 7 else: count = count - 1
def get_string(): strlist = [] zdlist = [["A","B","C","D","E","F","G","H","I","J","K","L","M","N"]\ ,["O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","q"]] ys = 0 zz = 0 get_string_print_data(ys,zz) while True: if GPIO.event_detected(blue_p): if zz == 13: zz = 0 else: zz = zz + 1 get_string_print_data(ys,zz) elif GPIO.event_detected(green_p): zz = 0 if ys == 1: ys = 0 else: ys = ys + 1 get_string_print_data(ys,zz) elif GPIO.event_detected(red_p): if zz == 13 and ys == 1: break strlist.append(zdlist[ys][zz]) zz = 0 ys = 0 get_string_print_data(ys,zz) restr = "" for x in strlist: restr = restr + x print(restr) return restr
def main(): global led0 global on_btn global off_btn if GPIO.event_detected(on_btn): #pin 23 is up button. HIGH connected print('on button pressed') GPIO.output(led0, GPIO.HIGH) if GPIO.event_detected(off_btn): #pin 24 is down button. HIGH connected print('Off button pressed') GPIO.output(led0, GPIO.LOW)
def zeroMode(): if GPIO.event_detected(northButton): if(DEBUG):print("North button accidentally pressed") if GPIO.event_detected(westButton): if(DEBUG):print("West button accidentally pressed") if GPIO.event_detected(eastButton): if(DEBUG):print("East button accidentally pressed") if GPIO.event_detected(southButton): if(DEBUG):print("South button accidentally pressed") if GPIO.event_detected(powerButton): if(DEBUG):print("Power button accidentally pressed")
def BackupTape(device): if IsConnected(): ForceDir(MOUNT_DIR) mountpath = GetMountPath() print(' > OP-1 device path: %s', mountpath) MountDevice(mountpath, MOUNT_DIR, 'ext4', 'rw') print(' > Device mounted at %s' % MOUNT_DIR) if os.path.exists(OP1_PATH) == 1: DrawText(device, ['BACKUP TAPE?', ' 1-CANCEL', ' 2-CONFIRM']) while True: if GPIO.event_detected(key['key2']): print('copying') cdate = datetime.datetime.now() tdate = datetime.date.today() dpath = STORAGE_DIR + PROJECT_DIR + '/op1-tapebackups/' + str( tdate) + ' ' + cdate.strftime('%I:%M%p') copyList = [ str(OP1_PATH) + '/tape/' + str(trackList[i]) for i in range(len(trackList)) ] if os.path.exists(dpath) == 0: os.mkdir(dpath) #else throw exception? DrawProgress(device, 'backing up tape...', 0) for iFile, fileName in enumerate(copyList): sh.copy(fileName, dpath) print('%s copied' % trackNames[iFile]) DrawProgress(device, ('backed up %s' % trackNames[iFile]), (iFile + 1) * 0.20) UnmountDevice(MOUNT_DIR) DrawProgress(device, 'back up done!', 1) return elif GPIO.event_detected(key['key1']): return else: print('no op1 detected') print('Is your device connected and in disk mode?') print(' 1-Return to Menu') DrawText(device, ['OP1 NOT CONNECTED', '1-RETURN']) WaitForKey('key1') return
def resetValuesIfResetPressed(): global Storedbitvalue global Displayedbitvalue if GPIO.event_detected(ResetValuePin): Storedbitvalue = 0 Displayedbitvalue = 0
def main(): script_set_up() board_set_up() update = True now = datetime.datetime.now() chour = now.hour while True: # Update handling if update: update_weather_and_led() update = False # Button Pressed handler if GPIO.event_detected(BUTPIN): led_blink() update = True now = datetime.datetime.now() if now.hour != chour: update = True chour = now.hour # Wait for next loop time.sleep(0.5)
def loop(): print "PRET" presence = time.time() btnrebound = time.time() while True: if GPIO.input(GPIO_MODE) == GPIO.HIGH: # print "PRESSION" # declenchement par pression if GPIO.event_detected(GPIO_BOUTON): if time.time() - btnrebound < DELAIBTN: print "trop rapide" else: btnrebound = time.time() print "PLAY" play() else: # declenchement par presence distance = mesure() print "distance: %d cm" %(distance) if distance > PROXIMITE: presence = time.time() else: if time.time() - presence > DELAI: print "PLAY" play() presence = time.time() else: print "EN ATTENTE" # attendre une seconde avant de tester a nouveau time.sleep(0.5)
def flush(self): """ Flush event device. """ logger.debug('Flushing port') while GPIO.event_detected(self.pin): pass
def sr_once_block(self): self._sr_start() while not GPIO.event_detected(sr_echo): time.sleep(0.001) now = time.time() intercept = (now - self._st)*170 return intercept
def sr_once(self): self._sr_start() while not GPIO.event_detected(sr_echo): yield from asyncio.sleep(0.001) now = time.time() intercept = (now - self._st) * 170 return intercept
def run(): # add falling edge detection on a channel io.add_event_detect(button, io.FALLING) print('listening for button press') sleep(1) while True: # blink the button blinkButton(0.5) if io.event_detected(button): print('button pressed') # button pressed, take photos capture() # post photos to Flowdock postToFlowdock() # transfer photos to printer to print printPhoto() print("done - ready for button press") time.sleep(0.5) displayScroll('.')
def event_detected(self): """ Return true if the gpio event was detected """ if gpio.event_detected(self.gpio_pin): return True else: return False
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 __read_message(self, timeout=0): """ Tries to read a message. """ self.__configure_for_reading() tm_start = time.time() while True: try: stat = self.__read_status() if stat & Bits.Stat_RX_FIFO_Empty != Bits.Stat_RX_FIFO_Empty: fifoStatus = self.__read_8bit_register_value(Register.FIFO_STATUS) if fifoStatus & Bits.FifoStat_RX_FULL > 0: if self.__debug: print "RX FIFO was full!" return self.__read_payload() else: self.__reset_status() GPIO.output(self.__output_pin, GPIO.HIGH) # time.sleep(0.1) max_wait = 5 if timeout <= 0 else (time.time() - tm_start) / 0.001 while max_wait > 0 and not GPIO.event_detected(self.__input_pin): max_wait -= 1 time.sleep(0.001) GPIO.output(self.__output_pin, GPIO.LOW) # time.sleep(0.5) # TODO a sleep interval should be shorter than the max transmission interval (with retries) finally: if timeout > 0: tm = time.time() if tm - tm_start >= timeout: break
async def time(websocket, path): while True: currentState = GPIO.input(4) print(currentState) now = datetime.datetime.utcnow().isoformat() + 'Z' if (GPIO.event_detected(4)): await websocket.send(now + str(GPIO.input(4)))
def loop(): session = False count = 0 last_rev = None start_time = None tag = None rfid_reading = False while (button_pressed[0] == False): if (rfid_reading == False and GPIO.input(rfid)): rfid_reading = True junk1 = ser.read(1) rawtag = ser.read(10) tag = int(rawtag, 16) junk2 = ser.read(5) print('Animal', tag) if (rfid_reading == True): if last_rev is not None: check_close_result = checkClose(last_rev, count, start_time, tag) if check_close_result: print("session data in if check close result check", session_data[0]) return session_data[0] if GPIO.event_detected(hall): if not session: session = True start_time = datetime.now() print("Session starting at {}".format(start_time)) count += 0.5 last_rev = datetime.now() print("Animal {} has run {} revolutions".format( tag, count))
def clock(): while True: lcd.clear() lcd.message(datetime.now().strftime('%b %d %H:%M:%S\n')) sleep(1) if(GPIO.event_detected(16)): break
def detection(): cpm = 0 endtime = time.time() + 1 while time.time() < endtime: if GPIO.event_detected(32): cpm = cpm + 1 return cpm
def evento_detectado(self): """Proceso que devuelve cuando un sonido es detectado """ sonido = False if GPIO.event_detected(self._canal): sonido = True return sonido
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 observe(self, channel): while True: if GPIO.event_detected(channel): self.logger.info("Detected button press for: " + self.property_name) self.update_property(self.get_timestamp()) time.sleep(0.25)
def main(): print "main" script_set_up() print "script is setup" board_set_up() update = True now = datetime.datetime.now() chour = now.hour while True: # Update handling if update: update = False #change update before attempting to update_weather_and_led() in case update fails update_weather_and_led() # Button Pressed handler if GPIO.event_detected(BUTPIN): led_blink() update = True now = datetime.datetime.now() if now.hour != chour: update = True chour = now.hour # Wait for next loop time.sleep(0.5)
def heightHoming(): global HeightHomePos global Height_Actual data = {"target": "height_homing", "value" : "images/HeightNoHome.png"} data = json.dumps(data) ws.write_message(data) print('Height Homing Started') GPIO.add_event_detect(34, GPIO.RISING) # try: while True: runHeight.step(50, "right", speed=2); #steps, dir, speed, stayOn if GPIO.event_detected(34): GPIO.remove_event_detect(34) time.sleep(0.5) runHeight.step(1500, "left", speed=4) time.sleep(0.5) runHeight.cleanGPIO heightFineHoming() break # except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C # print "Aborted" # except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging # so only use it once your code is working # print "Other error or exception occurred!" # finally: print('Height Homed') Height_Actual = 0.1 HeightHomePos = 10
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 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 zeroHeight(): global HeightZero global Height_Actual data = {"target": "height_probe", "value" : "images/ProbeRunning.png"} data = json.dumps(data) ws.write_message(data) print('Height Zero Started') GPIO.add_event_detect(31, GPIO.RISING) # try: while True: runHeight.step(1, "left", speed=3); #steps, dir, speed, stayOn # time.sleep(0.1) if GPIO.event_detected(31): GPIO.remove_event_detect(31) # runHeight.step(probeDistance, "right"); #steps, dir, speed, stayOn # time.sleep(0.5) runHeight.cleanGPIO # heightFineZero() break # except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C # print "Aborted" # except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging # so only use it once your code is working # print "Other error or exception occurred!" # finally: print('Height Zeroed') Height_Actual = 0.1 HeightZero = 0.0 data = {"target": "height_probe", "value" : "images/HeightProbe.png"} data = json.dumps(data) ws.write_message(data)
def move_angle(self, direction, angle, timeout): target_angle = self.angle + (direction * 2 - 1) * angle GPIO.output(self.direction_pin, direction) while direction * (self.angle <= target_angle) or (direction ^ 1) * ( self.angle >= target_angle): if self.angle >= self.max_angle or self.angle < 0 or GPIO.event_detected( self.switch_pin): if self.debug: print( f"\nMotor {self.motor_id}, Angle out of bounds. Angle: {self.angle}" ) if self.angle >= self.max_angle: self.edge_handling(self.cc_dirr, int(self.max_angle / 2), 0.0008) elif not GPIO.input(self.switch_pin): self.angle = 0 self.edge_handling(self.cw_dirr, int(self.max_angle / 2), 0.0008) sys.stdout.flush() break self.take_step(timeout) self.angle += direction * 2 - 1 if self.debug > 1: sys.stdout.write( f"\rMotor {self.motor_id} Angle: {self.angle}") sys.stdout.flush() if self.debug > 1: print("") sys.stdout.flush()
def loop(): while True: # Add event detection to a pin. This statement is non-blocking. # The subsequent code is executed (in this case, the LED is blinking). # If during any of this time, the button is pressed, this will be remembered. Afterward, the # 'event_detected' code is executed accordingly. # Possible options are: GPIO.RISING, GPIO.FALLING or GPIO.BOTH GPIO.add_event_detect(BtnPin, GPIO.FALLING) print('Start checking') for i in range(50): toggleLED() time.sleep(0.1) if GPIO.event_detected(BtnPin): print('Button was pressed') toggleLED() else: print('Button was not pressed') # Disable event handling GPIO.remove_event_detect(BtnPin) time.sleep(2)
def mqttPublishLines(buttonPin): topic = "rupesh/gpiotopic" broker = "192.168.1.200" port = 8883 filepath = "/home/pi/mqtt/data/access_log.txt" file = open(filepath, "r") line = file.readlines() count = 0 while True: if GPIO.input(buttonPin) == GPIO.LOW: time.sleep(0.1) count += 1 payload = { "iottimestamp": str(datetime.utcnow()), "accesslogs": line[count] } message = json.dumps(payload) print("Button Pressed", GPIO.input(buttonPin)) print("Event Detected", GPIO.event_detected(buttonPin)) GPIO.output(lightPin, True) mqttClient.main(broker, port, topic, message) else: GPIO.output(lightPin, False)
def main(): slack_notification = SlackNotification() GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.IN) sleep(2) GPIO.add_event_detect(18, GPIO.RISING) # photo, person_identifier を import した場合、コメントアウトを外す # CircularIO, UploadGoogleDrive を import した場合、コメントアウト try: while True: if GPIO.event_detected(18): print('動体を検知しました。分析にかけます。') photo_name = photo() num_faces, filename = person_identifier(photo_name) with open(filename, 'rb') as f: if num_faces >= 1: photo_comment = '人物を検知!写真を送ります。' else: photo_comment = '動体を検知しましたが人物ではありませんでした。' print(photo_comment) slack_notification.upload_file(filename, photo_comment, f) # photo, person_identifier を import した場合、コメントアウト # CircularIO, UploadGoogleDrive を import した場合、コメントアウトを外す # upload_google_drive = UploadGoogleDrive() # circular_io = CircularIO() # # print('エッジイベント検出中') # # try: # while True: # if GPIO.event_detected(18): # movie_name = circular_io.movie() # # movie_comment = 'イベント録画を行いました。動画を送信します。' # slack_notification.send_message(movie_comment) # sleep(3) # upload_google_drive.upload_movie(movie_name) # sleep(5) except KeyboardInterrupt: print('\nCtrl + C により、動体検知が終了しました。') finally: for p in glob.glob('*.jpg', recursive=True): if os.path.isfile(p): os.remove(p) for p in glob.glob('*.h264', recursive=True): if os.path.isfile(p): os.remove(p) print('deleted unnecessary files :)') GPIO.remove_event_detect(18)
def zeroFence(): global FenceZero global Fence_Actual global TouchPlateDim global FenceOffsetRadius print('Height Zero Started') data = {"target": "fence_probe", "value" : "images/ProbeRunning.png"} data = json.dumps(data) ws.write_message(data) GPIO.add_event_detect(31, GPIO.RISING) # try: while True: runFence.step(1, "left", speed=3); #steps, dir, speed, stayOn # time.sleep(0.1) if GPIO.event_detected(31): GPIO.remove_event_detect(31) # runFence.step(probeDistance, "right"); #steps, dir, speed, stayOn # time.sleep(0.5) runFence.cleanGPIO # FenceFineZero() break print('Fence Zeroed') Fence_Actual = TouchPlateDim + FenceOffsetRadius FenceZero = 0.0 data = {"target": "fence_probe", "value" : "images/FenceProbe.png"} data = json.dumps(data) ws.write_message(data)
def open_door(SWITCH, LED): print('Door Opened!') # 문 열기 - 모터 등을 연결해서 실제 움직임 표현한다면 이곳에. pass # 노란불은 끄고 초록불 켜고 led_onoff(search_pin_led(LED, 'LED_Y'), OFF) led_onoff(search_pin_led(LED, 'LED_G'), ON) # 비번변경 키 비활성화 event_disable(search_pin_switch(SWITCH, 'MODE')) # Enter키가 눌릴때까지 아무것도 하지 않는다. while (True): if GPIO.event_detected(search_pin_switch(SWITCH, 'ENTER')) is True: break else: time.sleep(0.1) # 비번변경 키 활성화 event_enable(search_pin_switch(SWITCH, 'MODE')) # 노란불은 켜고 초록불 끄고 led_onoff(search_pin_led(LED, 'LED_Y'), ON) led_onoff(search_pin_led(LED, 'LED_G'), OFF)
def test_high(): print('High detect test') GPIO.set_high_event(18) time.sleep(5) if GPIO.event_detected(18): print('Event detected') else: print('Event not detected')
def show_titlescreen(): """ Show the main title screen, and wait for the user to press <SPACE>. If the user presses the 'ESCape' key we will quit the game. IDEA: You could add a difficulty selection option here. Perhaps detect if the user pressed 'E', 'M', or 'H' for Easy/Medium/Hard? IDEA: For the more adventurous you could even allow the user to start a two player game! """ time.sleep(WAIT_TIME) global titleImage titleMusic = pygame.mixer.Sound("Resources/titlemusic.ogg") titleMusic.set_volume(0.5) titleMusic.play(-1) titleFont = pygame.font.Font("Resources/matt_smith_doctor_who.ttf", 72) label = titleFont.render("PRESS A BUTTON", True, (255, 255, 255)) # BLUE: 167, 192, 216 textRect = label.get_rect() textRect.center = (screen_width_pixels - 230, 125) while True: # Make the 'PRESS SPACE' text flash. screen.blit(titleImage, (0, 0)) if math.fmod(pygame.time.get_ticks(), 1000) > 500: screen.blit(label, textRect) for event in pygame.event.get(): if event.type == QUIT: quitGame() if event.type == KEYDOWN: if event.key == K_SPACE: titleMusic.fadeout(500) return elif event.key == K_ESCAPE: quitGame() if ( GPIO.event_detected(BUTTON1) or GPIO.event_detected(BUTTON2) or GPIO.event_detected(BUTTON3) ): # NAM START WITH GPIO Button titleMusic.fadeout(500) return pygame.display.update()
def test_falling(): print('Falling edge test') GPIO.set_falling_event(18) time.sleep(5) if GPIO.event_detected(18): print('Event detected') else: print('Event not detected')
def MOTION(PIR_PIN): if GPIO.event_detected(PIR_PIN): buildOutputDir() global free_pct free_pct = diskFree(working_dir) print "%s%% free on disk" % str(free_pct) recordImage2(working_dir) return free_pct
def play(): # call(["./play.sh"]) # subprocess.call(["./stop.sh"], shell=True) process = subprocess.Popen("./play.sh", shell=True) #time.sleep(1) while process.poll() is None: if GPIO.event_detected(GPIO_BOUTON): print "STOP" subprocess.call(["./stop.sh"], shell=True)
def synchronize(self): # car lights self.tl_car.set_red(self.car.red) self.tl_car.set_yellow(self.car.yellow) self.tl_car.set_green(self.car.green) # ped lights self.tl_ped.set_red(self.ped.red) self.tl_ped.set_green(self.ped.green) self.tl_ped.set_request(self.ped.request) # ped request button if GPIO.event_detected(self.tl_ped.btn_req): self.system.raise_pedestrianrequest() # sys onoff button if GPIO.event_detected(self.btn_onoff): self.system.raise_onoff() # sys exit button if GPIO.event_detected(self.btn_exit): self.exit()
def test_event_detected(self): self.switchcount = 0 print "\nGPIO.event_detected() switch bounce test. Press switch at least 10 times and count..." GPIO.add_event_detect(SWITCH_PIN, GPIO.FALLING, bouncetime=200) while self.switchcount < 10: if GPIO.event_detected(SWITCH_PIN): self.switchcount += 1 print 'Button press',self.switchcount GPIO.remove_event_detect(SWITCH_PIN)
def play(): # call(["./play.sh"]) process = subprocess.Popen("./play.sh", shell=True) while process.poll() is None: if GPIO.event_detected(GPIO_BOUTON): print "STOP" GPIO.remove_event_detect(GPIO_BOUTON) subprocess.call(["./stop.sh"], shell=True) time.sleep(1) GPIO.add_event_detect(GPIO_BOUTON, GPIO.RISING, bouncetime=300)
def check_expired_motion(): global cur_motion global off_time global new_lights_list if datetime.datetime.now() > off_time and not GPIO.event_detected(pir_in): # if time has elapsed print 'motion expired' for i in range(count): if new_lights_list[i].motion: # if a light is set to toggle on motion new_lights_list[i].toggle_from_button() # toggle that light to OFF cur_motion = False