def _shutdown(restart=False): action = 'h' if restart: action = 'r' GPIO.cleanup() command = "/usr/bin/sudo /sbin/shutdown -%s now" % action subprocess.Popen(command.split(), stdout=subprocess.PIPE)
def mainFunction(): """ This is the mainfunction. Here we chose wich other function we want to run using a keypad that is connected to the raspberry pi. """ global keypad print("Voer een getal in door middel van de keypad.") try: functions = [login, adUser, treadmill, device2, device3, device4, device5]#create a list of functions while True: if keypad.getKey() and 0 < int(keypad.getKey()) < 7: print("key pressed") keypadCharacter = int(keypad.getKey())#store the pressed key in the keypadCharacter variable keypadCharacter-=1 functions[keypadCharacter]() elif keypad.getKey() and not 0 < int(keypad.getKey()) < 7: print("Het getal dat u ingevoerd heeft is te hoog of te laag") #needed to be split in to high or low? sleep(2) sleep(0.1) # except ValueError: # print("Dit is geen getal voer altublieft een getal in.") # mainFunction() # except: # sleep(1) # sys.exit() finally: print("exiting") GPIO.cleanup()
def reset(self): if self._rst > 0: GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(self._rst, GPIO.OUT) # toggle pin GPIO.output(self._rst, GPIO.HIGH) sleep(0.1) GPIO.output(self._rst, GPIO.LOW) sleep(0.1) GPIO.output(self._rst, GPIO.HIGH) sleep(0.2) # give it some time to come back GPIO.cleanup(self._rst)
def get_ir_readings(): global customer_counter from time import time, ctime, sleep import RPi.GPIO as GPIO # + in physical pin 2 # - in physical pin 6 GPIO.setmode(GPIO.BCM) PIR_PIN = 4 #physically 7 GPIO.setup(PIR_PIN, GPIO.IN) #set up input period_average_customers = 0 GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MOTION) #####Start: Do a task for 12 minutes then return now = ctime() #get a formatted time string now_plus_12 = time() + (2) #store the time it'll be in 2 seconds /// replace (2) with time() + (60 * 12) now_plus_12 = ctime(now_plus_12) #convert to formatted time string print("now is :", now) print("This time period finishes at :", now_plus_12) sub_routine = True while ctime() != now_plus_12: sub_routine = True GPIO.cleanup() period_average_customers = customer_counter / 12 #12 minutes return period_average_customers #quit sub-routine
def distance(measure): gpio.setmode(gpio.BOARD) gpio.setup(TRIG, gpio.OUT) gpio.setup(ECHO, gpio.IN) gpio.output(TRIG, False) gpio.output(TRIG, True) time.sleep(0.00001) gpio.output(TRIG, False) sig = 0 nosig = 0 while gpio.input(ECHO) == 0: nosig = time.time() while gpio.input(ECHO) == 1: sig = time.time() if nosig != None and sig != None: tl = sig - nosig distance = tl * 17150 distance = round(distance, 2) gpio.cleanup() return distance
def main(): GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(DISPLAY_E, GPIO.OUT) GPIO.setup(DISPLAY_RS, GPIO.OUT) GPIO.setup(DISPLAY_DATA4, GPIO.OUT) GPIO.setup(DISPLAY_DATA5, GPIO.OUT) GPIO.setup(DISPLAY_DATA6, GPIO.OUT) GPIO.setup(DISPLAY_DATA7, GPIO.OUT) GPIO.setup(DISPLAY_E2, GPIO.OUT) display_init(DISPLAY_E) display_init(DISPLAY_E2) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD,DISPLAY_E) lcd_string("Schnatterente",DISPLAY_E) lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD,DISPLAY_E) lcd_string("Nak nak nak!",DISPLAY_E) lcd_byte(DISPLAY_LINE_1, DISPLAY_CMD,DISPLAY_E2) lcd_string("Dein Display",DISPLAY_E2) lcd_byte(DISPLAY_LINE_2, DISPLAY_CMD,DISPLAY_E2) lcd_string("funktioniert! :)",DISPLAY_E2) time.sleep(25) GPIO.cleanup()
def cleanup(): GPIO.cleanup() print "GPIO CLEANED" hotconn.close() histconn.close() print "DATABASE CONNECTION CLOSED" print "PROGRAM TERMINATED SUCCESSFULLY"
def right_stop_at_black(): cap = cv2.VideoCapture(0) time.sleep(2) GPIO.setmode (GPIO.BCM) GPIO.setwarnings (False) GPIO.setup (23, GPIO.OUT) GPIO.setup (22, GPIO.OUT) PWML = GPIO.PWM (22,1) PWMR1 = GPIO.PWM (23,1) PWMR1.start(0) PWML.start(0) counter =0 while(1): ret, img = cap.read() PWMR1.ChangeDutyCycle(100) PWML.ChangeDutyCycle(100) ret,thresh = cv2.threshold(img,100,255,cv2.THRESH_BINARY) b1,g1,r1 = thresh[240,500] if b1==255: counter+=1 continue if counter>0: PWMR1.stop() PWML.stop() break GPIO.cleanup() cap.release() return
def cleanup(): #Stop all the PWM objects RED.stop() GREEN.stop() BLUE.stop() #Tidy up and remaining connections. GPIO.cleanup()
def main(): GPIO.cleanup() GPIO.setmode(GPIO.BCM) #Relais als Ausgang schalten GPIO.setup(RELAIS, GPIO.OUT) #Eimersensor als Eingang schalten GPIO.setup(SENSOR_BUCKET_PIN,GPIO.IN) #Datenbank initialisieren db = DATABASE() # Aktuelle Luftfeuchtigkeit holen humidity = db.getLatestHumidity() # Checken ob Wasser im Eimer ist if isBucketEmpty(): db.saveBucketEmpty() else: db.saveStatus("OK") # Giessen wenn Luftfeuchtigkeit unter 90 % if humidity < HUMIDITY_LIMIT: db.saveWatering(WATERING_TIME) GPIO.output(RELAIS, GPIO.HIGH) time.sleep(WATERING_TIME) GPIO.output(RELAIS, GPIO.LOW) else: GPIO.output(RELAIS, GPIO.LOW)
def cleanup (self): self.__off() if Heating.__instances == 1: io.cleanup() else: with Heating.__instances_lock: Heating.__instances -= 1
def rightTurn(t): gpio.output(7, False) gpio.output(11,True) gpio.output(13, False) gpio.output(15, True) time.sleep(t) gpio.cleanup()
def leftTurn(t): gpio.output(7,True) gpio.output(11,False) gpio.output(13,True) gpio.output(15,False) time.sleep(t) gpio.cleanup()
def forward(t): gpio.output(7, False) gpio.output(11, True) gpio.output(13, True) gpio.output(15, False) time.sleep(t) gpio.cleanup()
def reverse(t): gpio.output(7, True) gpio.output(11, False) gpio.output(13, False) gpio.output(15, True) time.sleep(t) gpio.cleanup()
def __del__(self): GPIO.output(self._gpio_map["PWM1"], GPIO.LOW) GPIO.output(self._gpio_map["PWM2"], GPIO.LOW) GPIO.output(self._gpio_map["PWM3"], GPIO.LOW) GPIO.output(self._gpio_map["PWM4"], GPIO.LOW) self._motoLatch(0) GPIO.cleanup()
def main(): # tell the GPIO module that we want to use the # chip's pin numbering scheme GPIO.setmode(GPIO.BCM) # setup pin 25 as an output GPIO.setup(17,GPIO.IN) GPIO.setup(18,GPIO.IN) while True: if GPIO.input(17): print "Vision Api activated" try: rc = subprocess.call("cd /home/pi/unblind && sh /home/pi/unblind/visionapi.sh && cd -", shell=True) except OSError as e: print( e ) print "button17 true" if GPIO.input(18): print "OCR Api activated" try: rc = subprocess.call("cd /home/pi/unblind && sh /home/pi/unblind/ocr.sh && cd -", shell=True) except OSError as e: print( e ) print "button18 true" time.sleep(0.1) GPIO.cleanup()
def main(): # tell the GPIO module that we want to use the # chip's pin numbering scheme GPIO.setmode(GPIO.BCM) # setup pin 25 as an output GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(17, GPIO.OUT) # GPIO.setup(25,GPIO.OUT) # GPIO.output(25,True) while True: pressed = not GPIO.input(18) if pressed: # the button is being pressed, so turn on the green LED # and turn off the red LED GPIO.output(17,True) # GPIO.output(25,False) print "button true" else: # the button isn't being pressed, so turn off the green LED # and turn on the red LED GPIO.output(17,False) # GPIO.output(25,True) print "button false" time.sleep(0.1) print "button pushed" GPIO.cleanup()
def __init__(self): self._gpio_map = {"PWM2":37, "DIR_CLK":38, "PWM3":35, "PWM4":36, "DIR_EN":33, "DIR_UP":31, "PWM1":32, "DIR_LATCH":29} self._pwm_map = [] GPIO.cleanup() GPIO.setmode(GPIO.BOARD) # set GPIO OUT mode for i in iter(self._gpio_map): GPIO.setup(self._gpio_map[i], GPIO.OUT) # set PWM #GPIO.output(self._gpio_map["PWM1"], GPIO.HIGH) #GPIO.output(self._gpio_map["PWM2"], GPIO.HIGH) #GPIO.output(self._gpio_map["PWM3"], GPIO.HIGH) #GPIO.output(self._gpio_map["PWM4"], GPIO.HIGH) # set PWM p1 = GPIO.PWM(self._gpio_map["PWM1"], 255) p2 = GPIO.PWM(self._gpio_map["PWM2"], 255) p3 = GPIO.PWM(self._gpio_map["PWM3"], 255) p4 = GPIO.PWM(self._gpio_map["PWM4"], 255) self._pwm_map = [p1, p2, p3, p4] for i in self._pwm_map: i.start(100)
def activation_main2(): GPIO.setup(right_button, GPIO.IN, GPIO.PUD_UP) GPIO.setup(left_button, GPIO.IN, GPIO.PUD_UP) try: while True: alarmstatus = getAlarm() if alarmstatus == 1: GPIO.output(RedLed, 1) GPIO.output(GreenLed, 0) else: GPIO.output(GreenLed, 1) GPIO.output(RedLed, 0) if GPIO.input(right_button) == False: setAlarm2(1) sendNotification(getToken(getUsername())) if GPIO.input(left_button) == False: setAlarm2(0) except KeyboardInterrupt: GPIO.cleanup()
def main(): parser = argparse.ArgumentParser('3ch PWM controller') parser.add_argument("-c","--channel", type=int, help="output channel", default = 3) parser.add_argument("-v","--value", type=int, help="pwm value (maybe in percentage)") parser.add_argument("-f","--freq", type=int, help="pwm frequency", default = 50) args = parser.parse_args() channel = args.channel value = args.value freq = args.freq GPIO.setwarnings(False) #pinRed = 3 #pinGreen = 5 #pinBlue = 7 GPIO.setup(channel, GPIO.OUT) #GPIO.setup(pinRed, GPIO.OUT) #GPIO.setup(pinGreen, GPIO.OUT) #GPIO.setup(pinBlue, GPIO.OUT) p = GPIO.PWM(channel, freq) # channel=pinRed frequency=50Hz #chGreen = GPIO.PWM(pinGreen, 200) # channel=pinRed frequency=50Hz #chBlue = GPIO.PWM(pinBlue, 200) # channel=pinRed frequency=50Hz p.start(100) p.ChangeFrequency(50) # where freq is the new frequency in Hz p.ChangeDutyCycle(value) raw_input('Press return to stop:') # use raw_input for Python 2 p.stop() GPIO.cleanup()
def destroy(self): logger.debug("GPIO.destroy()") # shutdown all output-pins for output_pin in self.__OutputPins: self.set_output(output_pin, 0, False) RPiGPIO.cleanup() doorpi.DoorPi().event_handler.unregister_source(__name__, True)
def exit_handler(signal, frame): print "Exiting..." stop_camera() change_dc({"x": 7.5, "y": 7}) GPIO.cleanup() print "Bye!" sys.exit(0)
def F_AlarmOnOff(AlarmActive, Alarm_Number): """ AlarmActive function: Function to enable and disable alarm when button is pressed as well as display status on screen Args: AlarmActive Return: AlarmActive """ try: if AlarmActive: AlarmActive = False lcd.set_backlight(1) lcd.clear() lcd.message('Alarm ' + str(Alarm_Number) + ' Disabled') sleep(2) lcd.clear() lcd.set_backlight(0) return AlarmActive else: AlarmActive = True lcd.set_backlight(1) lcd.clear() lcd.message('Alarm ' + str(Alarm_Number) + ' Enabled') sleep(2) lcd.clear() lcd.set_backlight(0) return AlarmActive except KeyboardInterrupt: print ('KeyboardInterrupt in Function F_AlarmOnOff') GPIO.cleanup() quit()
def main(): logger.setupLogger() logger.info("Starting application") db = database.Database() db.createConnection() try: initGpio() while True: tagId = nfc.readNfc() employeeId = db.getEmployeeIdFromTagId(tagId) if (employeeId != None): logger.info("Employee authorized") db.addNewTimestampOfEmployeeId(employeeId) blinkLed(GREEN_LED) time.sleep(SYS_PAUSE_TIME) else: logger.info("Employee NOT authorized") blinkLed(RED_LED) time.sleep(SYS_PAUSE_TIME) except KeyboardInterrupt: logger.info("Closing application") GPIO.cleanup() db.closeConnection()
def doorLockInput(): #키패드 입력값 확인 함수 #print "doorLock Input" global rows global cols matrix=[[1,2,3], #어떤 버튼인지 확인하기 위한 매트릭스 [4,5,6], [7,8,9], ['*',0,'#']] try: for j in xrange(0,3,1): gpio.output(cols[j],False) for i in xrange(0,4,1): if gpio.input(rows[i])==0: print matrix[i][j] while gpio.input(rows[i])==0: pass return matrix[i][j] #키패드값 리턴 gpio.output(cols[j],True) return None except KeyboardInterrupt: gpio.cleanup() exit()
def setupGPIO(): GPIO.setwarnings(False) GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(lights, GPIO.OUT) GPIO.output(lights, GPIO.LOW)
def run(): while True: try: main() except: IO.cleanup() sys.exit()
def run(self): GPIO.setmode(GPIO.BOARD) GPIO.setup(self.pins["trig"], GPIO.OUT) GPIO.setup(self.pins["echo"], GPIO.IN) time.sleep(0.01) while not self.interrupt.isSet(): GPIO.output(self.pins["trig"], True) time.sleep(0.00001) GPIO.output(self.pins["trig"], False) while GPIO.input(self.pins["echo"]) == 0: pulse_start = time.time() while GPIO.input(self.pins["echo"]) == 1: pulse_end = time.time() if (not 'pulse_start' in locals()) or (not 'pulse_end' in locals()): distance = 1000 else: pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 with self.status_lock, self.config_lock: if distance > config.bin_height: Status.level = 0 else: Status.level = round((config.bin_height - distance) / config.bin_height * 100) time.sleep(1) GPIO.cleanup()
def main(): GPIO_INIT() #Sets up the GPIO Pins print "system on" try: while True: if (GPIO.input(23)==False): #WHILE the door is closed the progran will check the temperature if GPIO.input(14): print "ir sensor tripped" check_temp_state() ir_sensor_callback() sleep(1) else: print "sensor not tripped" #function call to check temperature sleep(3) else: print "door open" sleep(10) except KeyboardInterrupt: print "" print "Goodbye, have a nice day" finally: GPIO.cleanup()
# Save values for next iteration left_start = left_encoder right_start = right_encoder data_time_init = data_time2 gyro_init = omega # Reset sums for next iteration accel_sum = np.zeros(3) # Vector of sum of accelerometer values mag_sum = np.zeros(3) # Vector of sum of magnetometer values omega_sum = np.zeros(3) # Vector of sum of gyroscope values #temp_sum = 0 # Sum of temperature values imu_counter = 0 # Number of summed values else: # If Roomba data hasn't come in # Read acceleration, magnetometer, gyroscope data [accel_sum, mag_sum, omega_sum, imu_counter] = ReadIMU(imu, accel_sum, mag_sum, omega_sum, imu_counter) # Remove to use only one measurement per data iteration # End if Roomba.Available() # End while time.time() - start_time <=t: # End for i in range(len(move_dict.keys())): Roomba.Move(0,0) # Stop Roomba Roomba.PauseQueryStream() # Pause data stream if Roomba.Available() > 0: # If anything is in the Roomba receive buffer z = Roomba.DirectRead(Roomba.Available()) # Clear out excess Roomba data #print(z) # Include for debugging imu_file.close() # Close data file Roomba.PlaySMB() # For fun :) ## -- Ending Code Starts Here -- ## # Make sure this code runs to end the program cleanly Roomba.ShutDown() # Shutdown Roomba serial connection GPIO.cleanup() # Reset GPIO pins for next program
def destroy(): # Stop all pwm channel led_val.stop() # Release resource GPIO.cleanup()
#Write to database #If new var is created this statment must be updated. cursor.execute("INSERT INTO sensordata(sensestamp, rainfall, temperature, humidity) VALUES (%s,%s,%s,%s)", (date,rain,temp,humid)) #Commit new changes to database. db.commit() #Close database db.close() #Infinite loop for checking rain status every 10 seconds. try: while True: humid, temp = Adafruit_DHT.read_retry(sensor, pin) #Check humid and temp from sensor print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temp, humid) #Print both as floating point to console rainstate = GPIO.input(23) #Check reading from rain drop sensor at pin 23. if (rainstate == 0): rain = "Raining!" print rain else: rain = "None" print rain WriteToDB(rain,temp,humid) time.sleep(30) #Wait 30 seconds, then repeat. except KeyboardInterrupt: print "Quit by CTRL+C" GPIO.cleanup()
def cleanup(): stop() stopServos() GPIO.cleanup()
def destroy(): GPIO.output(LedPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource
start = time.time() while GPIO.input(32)==1: s1 = time.time() total_time = s1 - start distance = total_time*170 distance_in_cm = distance*100 if distance_in_cm>40: GPIO.output(3,1) time.sleep(0.1) GPIO.output(3,0) else: GPIO.output(35,1) time.sleep(0.1) GPIO.output(35,0) print("Distance of the Object is:" , distance_in_cm) except: print("Error") finally: GPIO.cleanup((31,32))
def _clean_up(self): GPIO.cleanup()
def finalizoGPIO(): GPIO.cleanup() ## Hago una limpieza de los GPIO
def gpio_cleanup(self): """The top-level method to provide clean the GPIO pin that is reserved the button. """ GPIO.cleanup(self.gpio_pin)
def destroy(): # Turn off all LEDs GPIO.output(LedPins, GPIO.HIGH) # Release resource GPIO.cleanup()
def destroy(): GPIO.cleanup()
def destroy(): GPIO.output(BeepPin, GPIO.LOW) # beep off GPIO.cleanup() # Release resource
def releaseGPIO(pinNr): log("d", "releaseGPIO({})".format(pinNr)) GPIO.output(pinNr, GPIO.LOW) GPIO.cleanup()
def gpio_cleanup(self): """Method to provide clean the GPIO pin that is reserved the fan. """ GPIO.cleanup(self.gpio_pin)
def stop_read(MIFAREReader): global continue_reading MIFAREReader.MFRC522_StopCrypto1() continue_reading = False GPIO.cleanup()
xposservo = (int(u * 10) / 1) #not finding any contour except Exception as excerr: print(excerr) if ("name 'notfound' is not defined" == str(excerr)): print("nothing found") dt2 = dt2 + 1 if (dt2 >= 11): dt2 = 2 dt1 = dt1 + 0.5 if (dt1 >= 6): dt1 = 2 pwm1.ChangeDutyCycle((int(dt1 * 10) / 10)) pwm2.ChangeDutyCycle((int(dt2 * 10) / 10)) elif ("float division by zero" == str(excerr)): print("servostop") #servo must pause here #show stuff cv.imshow('frame', frame) print((int(dt1 * 10) / 10), (int(dt2 * 10) / 10)) #close stuff ikey = cv.waitKey(5) if (ikey == ord("q")): cv.destroyAllWindows() pwm1.stop() pwm2.stop() rp.cleanup() vs.stop() break
def finish(self): gpio.cleanup()
def destory(self): GPIO.cleanup()
def destroy(): GPIO.output(REDPIN,GPIO.LOW) GPIO.output(YELLOWPIN,GPIO.LOW) GPIO.output(GREENPIN,GPIO.LOW) GPIO.cleanup()
def end_read(signal,frame): global continue_reading print ("Ctrl+C captured, ending read.") continue_reading = False GPIO.cleanup()
# read file vid_rec_num, make into int() set rec_num equal to it vrn = open(vid_rec_num_fp, 'r') rec_num = int(vrn.readline()) print "rec_num is %d" % rec_num vrn.close() # if file doesn't exist, create it to avoid issues later else: rec_num = 0 write_rec_num() except: print("Problem listing /home/pi") flash(0.1,10) GPIO.cleanup() sys.exit() try: while True: # this will run until button attached to 24 is pressed, then # if pressed long, shut program, if pressed very long shutdown Pi # stop recording and shutdown gracefully print "Waiting for button press" # rising edge on port 24" GPIO.wait_for_edge(24, GPIO.RISING) print "Stop button pressed" stop_recording() # poll GPIO 24 button at 20 Hz continuously for 3 seconds # if at the end of that time button is still pressed, shut down # if it's released at all, break
def main(): try: #setup GPIO-Pins GPIO.setmode(GPIO.BCM) GPIO.setup(BUTTON1, GPIO.IN) GPIO.setup(BUTTON2, GPIO.IN) GPIO.setup(LED, GPIO.OUT, initial=False) print("IOTA Kontostand wird abgefragt") balance = check_balance() print("%s IOTA befinden sich in der Wallet" % (balance)) print("----------------------------------------") print("Daten der Tankstelle werden abgerufen...") stationData = get_station_info() print("ENERGY-SB %s" % (stationData["ENERGY-SB"])) #print("ENERGY-SB: %s IOTA/%s" %("2", "kwH")) print("----------------------------------------") print("Führen Sie den Zapfhahn ein...") wait_for_button_click( BUTTON1) #manuell muss der Zapfhahn in das Auto gesteckt werden pumpData = get_pump_info() print("Tanksäule %s wurde in den Tank geführt!" " Sprittyp %s ausgewählt" % (pumpData["ZapfId"], pumpData["FuelType"])) print("Tanksäule wird initialisiert...") carId = initialize_fueling(pumpData["ZapfId"], pumpData["FuelType"]) print("Tankvorgang kann nun gestartet werden!") GPIO.output(LED, True) fueling = False startTime = time.time() ## #menge = 0 ## while not GPIO.input(BUTTON1): if GPIO.input(BUTTON2) and not fueling: fueling = True GPIO.output(LED, False) call_api("startFueling", carId) if not GPIO.input(BUTTON2) and fueling: fueling = False GPIO.output(LED, True) call_api("pauseFueling", carId) if fueling: currentTime = time.time() if currentTime - startTime > 0.1: startTime = currentTime fuelingData = call_api("getFueling", carId) print("Fueling... %s: %s, IOTAs: %s" % (fuelingData["unit"], fuelingData["amount"], fuelingData["cost"])) #menge = menge + 1.016 endFuelingData = call_api("endFueling", carId) amount = endFuelingData["amount"] cost = endFuelingData["cost"] unit = endFuelingData["unit"].encode('utf-8') address = endFuelingData["address"].encode('utf-8') print( "Sie haben %s %s getankt, die Rechnung beläuft sich auf %s IOTAs" % (amount, unit, cost)) print("Empfängeradresse: %s" % (address)) print("Button1 drücken um zu zahlen...") wait_for_button_click(BUTTON1) #warte auf knopfdruck um zu zahlen print("Die Rechnung wird beglichen...") bundle = pay(amount, address, "Smart-Refuling Rechnung") print("----------------------------------------") print("Bundlehash: %s" % (bundle["bundle"].hash)) print("Die Rechnung ist gültig, schöne Weiterfahrt!") finally: GPIO.cleanup()
def init_dht(): # initialize GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.cleanup()
def main(): #program start directory = '/media/pi/BILLYUSB1/' LOG_FILENAME = '/tmp/bplay_%s.log' % time.strftime( '%Y-%m-%d %H:%M:%S', time.localtime(time.time())).replace( " ", "_").replace(":", "") logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG) #logging.basicConfig(level=logging.DEBUG) reader = SimpleMFRC522() logging.info( "\n\n\n***** %s Begin Player****\n\n\n" % time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) current_movie_id = 111111222222 playerOB = "" try: while True: isPlay = isplaying() logging.debug( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " Movie Playing: %s" % isPlay) if not isPlay: current_movie_id = 555555555555 start_time = time.time() logging.debug('start_time0: %s' % start_time) logging.debug( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " Waiting for ID to be scanned") temp_time = time.time() logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " #READER BEFORE %s" % temp_time) idd, movie_name = reader.read() temp_time = time.time() - temp_time logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " #READER AFTER - ELAPSED TIME %s" % temp_time) logging.debug( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " + ID: %s" % idd) logging.debug( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " + Movie Name: %s" % movie_name) movie_name = movie_name.rstrip() if current_movie_id != idd: logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + ' New Movie') logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " - ID: %s" % idd) logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " - Name: %s" % movie_name) #this is a check in place to prevent omxplayer from restarting video if ID is left over the reader. #better to use id than movie_name as there can be a problem reading movie_name occasionally if movie_name.endswith(('.mp4', '.avi', '.m4v', '.mkv')): current_movie_id = idd #we set this here instead of above bc it may mess up on first read logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " playing: omxplayer %s" % movie_name) playerOB = playmovie(movie_name, directory, playerOB) elif 'folder' in movie_name: current_movie_id = idd movie_directory = movie_name.replace('folder', "") try: movie_name = random.choice( glob.glob( os.path.join(directory + movie_directory, '*'))) movie_name = movie_name.replace(directory, "") direc = directory except IndexError: movie_name = 'videonotfound.mp4' direc = 'home/pi/Videos/' logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " randomly selected: omxplayer %s" % movie_name) playerOB = playmovie(movie_name, direc, playerOB) else: end_time = time.time() elapsed_time = end_time - start_time logging.debug('end_time: %s' % end_time) logging.debug('start_time1: %s' % start_time) isPlay = isplaying() if isPlay: if elapsed_time > 0.6 and elapsed_time < 8: #pause, unpause movie logging.info( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + " PLAY/PAUSE %s" % elapsed_time) playerOB.play_pause() except KeyboardInterrupt: GPIO.cleanup() print("\nAll Done")
def cleanup(): p.stop() GPIO.cleanup()
def cleanAndExit(): GPIO.cleanup() sys.exit()
def cleanup_gpio(event): """ Stuff to do before stop home assistant. """ # pylint: disable=no-member GPIO.cleanup()
def __del__(self): GPIO.cleanup()
def cleanup_gpio(event): """Stuff to do before stopping.""" GPIO.cleanup()
def destroy(): # When program ending, the function is executed. GPIO.cleanup()