def triggerGate(self, command): try: if command == "pedestrian_access": led = LED(2, active_high=False) led.on() sleep(0.2) led.off() led.close() self.send(text_data=json.dumps({'result': 'gate_triggered'})) MailSender.sendMail("Pedestrian access triggered") return elif command == "vehicle_access": led = LED(3, active_high=False) led.on() sleep(0.2) led.off() led.close() self.send(text_data=json.dumps({'result': 'gate_triggered'})) MailSender.sendMail("Vehicle access triggered") return self.send(text_data=json.dumps({'result': 'bad_command'})) MailSender.sendMail("Gate trigger failed with bad command") except Exception as e: self.send(text_data=json.dumps({'result': 'internal_server_error'})) MailSender.sendMail(f"Gate trigger failed with exception: {e}")
class StatusLed: def __init__(self): self._led = LED(PIN) self._led.off() _logger.debug('{} initialized'.format(self.__class__.__name__)) def set(self, status): self._led.off() blinking_time_s = _blinking_time_s.get(status) if blinking_time_s is None: raise ValueError('Unknown status: {}'.format(status)) if blinking_time_s < 0: # Constant on. self._led.on() else: self._led.blink(on_time=blinking_time_s, off_time=blinking_time_s) def close(self): self._led.off() self._led.close() _logger.debug('{} stopped'.format(self.__class__.__name__))
def test_construction(self): """ 生成テスト """ # 接続ピン PIN_LD = 23 PIN_PR = 10 # 周辺設定 led = LED(PIN_LD) # 期待値 valueLDExpctd = False # black # ターゲット生成 photoref = Button(PIN_PR,active_state=True,pull_up=None) # 接続 led.source = photoref # 実際値 valueLDActual = led.value # 評価 try: self.assertEqual(valueLDActual,valueLDExpctd) sleep(0.1) finally: led.close() photoref.close()
class HardwareController(object): def __init__(self): self.button = Button(pin=BUTTON_PIN, hold_time=1, hold_repeat=True) self.status_led = LED(STATUS_LED_PIN) self.button_led = LED(BUTTON_LED_PIN) self.button.when_pressed = self.button_pressed self.button.when_released = self.button_released self.button.when_held = self.button_held self.hold_time = 0 self.status_led.blink(on_time=0.1, off_time=0.1, n=5, background=False) self.status_led.on() return def close(self): self.button.close() self.button_led.close() self.status_led.close() return def button_held(self): logger.debug("button held") self.hold_time = self.button.active_time self.button_led.blink(on_time=0.25, off_time=0.1, n=1) return def button_pressed(self): logger.debug("button pressed") self.hold_time = 0 return def button_released(self): increments = int(self.hold_time / BUTTON_HOLD_INCREMENTS) logger.debug("button released. Held for {0} increments".format(increments)) if increments > 0: time.sleep(2) self.button_led.blink(on_time=0.5, off_time=0.5, n=increments, background=False) time.sleep(1) if increments == 1: logger.info("Shutdown called via button press") check_call(['sudo', 'poweroff']) elif increments == 2: logger.info("Reboot called via button press") check_call(['sudo', 'reboot']) return
class LEDplus(): def __init__(self, pinnumber): self.led = LED(pinnumber) self.__loop = True self.operation = 'off' self.__threading = threading.Thread(target=self.__blink) def on(self, ): self.operation = 'on' self.__loop = False self.maybejoin() self.led.on() def off(self, ): self.operation = 'off' self.__loop = False self.maybejoin() self.led.off() def close(self, ): self.operation = 'off' self.__loop = False self.maybejoin() self.led.off() self.led.close() def close(self, ): self.operation = 'off' self.__loop = False self.maybejoin() self.led.off() self.led.close() def maybejoin(self, ): if self.__threading.isAlive(): self.__threading.join() def blink(self, pitch): if self.operation != 'blink-%s' % pitch: self.__loop = False if self.operation != 'on' and self.operation != 'off': last_pitch = self.operation.split('-')[1] time.sleep(float(last_pitch) + 0.1) self.operation = 'blink-%s' % pitch self.__loop = False self.maybejoin() self.__threading = threading.Thread(target=self.__blink, args=(pitch, )) self.__threading.start() def __blink(self, pitch=2): self.__loop = True while self.__loop: self.led.toggle() time.sleep(pitch) self.led.off()
class Led: def __init__(self, pin: Union[int, str], active_high=True, initial_value=False) -> None: try: self._led = LED(pin, active_high=active_high, initial_value=initial_value) except BadPinFactory: logger.warning("no gpio found") self._led = None @property def pin(self) -> Any: if self._led: return self._led.pin @property def is_lit(self) -> bool: if self._led: return self._led.is_lit return False @property def value(self) -> int: if self._led: return self._led.value return 0 @value.setter def value(self, value) -> None: if self._led: self._led.value = value def close(self) -> None: if self._led: self._led.close() def on(self) -> None: if self._led: self._led.on() def off(self) -> None: if self._led: self._led.off() def toggle(self) -> None: if self._led: self._led.toggle() def blink(self) -> None: if self._led: self._led.blink()
class Me(tornado.web.RequestHandler): def prepare(self): logging.log(logging.INFO, "Preparing LED 26 ...") self.relay = LED(26) def get(self): self.relay.on() sleep(1) self.relay.off() self.relay.close() self.write("{\"time\": " + str(time.time()) + "}")
class GoogleAIYVoicehat(MycroftSkill): def __init__(self): MycroftSkill.__init__(self) def initialize(self): self.time_held = 100 self.short_press = 2 self.button = Button(23, hold_time = 7) self.led = LED(25) self.schedule_repeating_event(self.handle_button, None, 0.01, 'buttonpress') def handle_button(self): self.button.when_pressed = self.start_timer self.button.when_held = self.graceful_exit self.button.when_released = self.stop_timer self.add_event('recognizer_loop:record_begin', self.handle_listener_started) self.add_event('recognizer_loop:record_end', self.handle_listener_ended) def start_timer(self): self.time_held = time.time() def stop_timer(self): self.time_held = time.time() - self.time_held if self.time_held < self.short_press: self.bus.emit(Message('mycroft.mic.listen')) elif self.time_held < self.button.hold_time: self.bus.emit(Message('mycroft.stop')) def handle_listener_started(self): self.led.on() def handle_listener_ended(self): self.led.off() # In truth, this is a not-so-graceful power down. # Emitting message 'system.shutdown' doesn't work on Picroft. def graceful_exit(self): self.blink() self.log.info('Forcing a linux shutdown ...') subprocess.call(['sudo', 'shutdown', '-h', 'now']) def blink(self): for i in range(6): self.led.toggle() time.sleep(0.5) def shutdown(self): self.cancel_scheduled_event('buttonpress') self.button.close() self.led.close()
def blink(): led = LED(PIN_NO_LED) led.off() sleep(SLEEP_TIME) led.on() sleep(SLEEP_TIME) led.off() sleep(SLEEP_TIME) led.close() # Use brute force method because gpiozero turns off output on exit os.system('echo "' + str(PIN_NO_LED) + '" | tee /sys/class/gpio/export >/dev/null') os.system('echo "out" | tee /sys/class/gpio/gpio' + str(PIN_NO_LED) + '/direction >/dev/null') os.system('echo "1" | tee /sys/class/gpio/gpio' + str(PIN_NO_LED) + '/value >/dev/null')
class Explode: def __init__(self, audiofiles_dir): self.led_explode = LED(pin_fig.explode_led) self.mixer_explode = mixer self.audiofiles_dir = audiofiles_dir def on(self): siren_mp3_path = path.join(self.audiofiles_dir, "bomb1.mp3") self.mixer_explode.init() self.mixer_explode.music.load(siren_mp3_path) self.mixer_explode.music.play(1) self.led_explode.blink(on_time=0.05, off_time=0.05) print("explode on") def off(self): self.mixer_explode.music.stop() self.led_explode.off() self.led_explode.close() print("explode off")
class Nozzle(Device): @property def obit(self): return self.__obit @threaded def init(self): self.__obit = LED(int(self.pins[0])) print("Init Finished:" + self.name) @threaded def run(self): self.__obit.on() @threaded def stop(self): self.__obit.off() print("Stop Finished:" + self.name) @threaded def exit(self): self.__obit.close() print("Exit Finished:" + self.name)
def tcpCallback(): while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) print("TCP socket awaiting connection...") (conn, addr) = s.accept() conn.send(("OKENDOFMSG").encode()) print("Socket connected") while True: string_recv = (conn.recv(1024)).decode() print("Recv: " + string_recv) if string_recv == "PINGENDOFMSG": conn.send(("PONGENDOFMSG").encode()) elif string_recv == "NEXTENDOFMSG": printer = LED(26) printer.on() printer.close() elif string_recv == "SCANENDOFMSG": print_paper() with open('/home/pi/Desktop/Checker/image_in.jpg', 'rb') as file: data = file.read() message = data + ("ENDOFMSG").encode() print('Sending data to:', addr) conn.sendall(message) elif string_recv == "EXENDOFMSG": conn.close() break elif string_recv == "SHUTENDOFMSG": conn.close() quit() print("Done") except Exception as e: print(e) sleep(2)
class Siren: def __init__(self, audiofiles_dir): self.led_siren = LED(pin_fig.siren_led) self.mixer_siren = mixer self.audiofiles_dir = audiofiles_dir def on(self): siren_mp3_path = path.join(self.audiofiles_dir, "ambulance-siren2.mp3") self.mixer_siren.init() self.mixer_siren.music.load(siren_mp3_path) # 12sec self.mixer_siren.music.play(-1) self.mixer_siren.music.set_volume(0.7) self.led_siren.blink(on_time=1, off_time=1) print("siren on") def off(self): self.mixer_siren.music.stop() self.led_siren.off() self.led_siren.close() print("siren off")
def test_callback(self): """ コールバックテスト """ # 接続ピン PIN_LD = 23 PIN_PR = 10 # 周辺設定 led = LED(PIN_LD) # 期待値 highLDExpctd = True # white lowLDExpctd = False # black # ターゲット生成 photoref = Button(PIN_PR,active_state=True,pull_up=None) photoref_pin = Device.pin_factory.pin(PIN_PR) # コールバック関数設定 photoref.when_pressed = led.on photoref.when_released = led.off # Highでフォトリフレクタを駆動(白) photoref_pin.drive_high() sleep(0.1) highLDActual = led.value # Low でフォトリフレクタを駆動(黒) photoref_pin.drive_low() sleep(0.1) lowLDActual = led.value # 評価 try: self.assertEqual(highLDActual,highLDExpctd) self.assertEqual(lowLDActual,lowLDExpctd) sleep(0.1) finally: led.close() photoref.close()
class Blender(object): def __init__(self, timeout): # https://gpiozero.readthedocs.io/en/stable/recipes.html#pin-numbering # Connect the GPIO-18 pin and a ground pin (Ground 6 for example) self.pin = LED(18) self.timeout = timeout self.timeout_thread = None self.state = 0 self.off() def handle_timeout(self): print("Timeout") self.off() def ensure_blender_turns_off(self): self.timeout_thread = threading.Timer(self.timeout, self.handle_timeout, []) self.timeout_thread.start() def on(self): print('Setting blender to ON') self.pin.on() self.ensure_blender_turns_off() self.state = ON def off(self): print('Setting blender to OFF') self.pin.off() self.state = OFF def toggle(self): if self.state == ON: self.off() else: self.on() def cleanup(self): self.pin.close()
def main(): global led_state, led_pin try: led = LED(led_pin) led.on() while True: txt = input("Type [Enter]: ") led_state = not led_state if led_state: led.on() else: led.off() log.info("LED state: %s" % led_state) except KeyboardInterrupt: log.info("...^C pressed...") except: log.error(str(sys.exc_info()[1])) log.error(traceback.format_tb(sys.exc_info()[2])) finally: log.info("Cleaning up/closing.") led.close() # this ensures a clean exit
GPIO_PIN = 14 LED = LED(GPIO_PIN) class WakewordGadget(AlexaGadget): """ An Alexa Gadget that turns an LED on and off in sync with the detection of the wake word """ def __init__(self): super().__init__() def on_alexa_gadget_statelistener_stateupdate(self, directive): for state in directive.payload.states: if state.name == 'wakeword': if state.value == 'active': logger.info('Wake word active - turn on LED') LED.on() elif state.value == 'cleared': logger.info('Wake word cleared - turn off LED') LED.off() if __name__ == '__main__': try: WakewordGadget().main() finally: logger.debug('Cleaning up GPIO') LED.close()
def main(): parser = argparse.ArgumentParser() parser.add_argument("-rpc", help="Start rpc server", action="store_true", default=False) parser.add_argument("-v", "--verbose", help="Log verbosity", action="store_true", default=False) parser.add_argument("-stop", help="Cleanup on stop service", action="store_true", default=False) parser.add_argument( "-off_first", help="Check OFF condition first, then ON condition", action="store_true", default=False) parser.add_argument("--lcd", help="Use I2C LCD 16x2 to show status", choices=[ "sainsmart_charlcd_led", "adafruit_charlcd_rgb", "adafruit_charlcd_mono"], default=None) parser.add_argument("--pin", help="GPIO Pin", type=int, action='append', default=[]) parser.add_argument( "--off", help="Pin Off condition, format: <temp|hum>:<eq|lt|lte|gt|gte>:<value>:[or|and|xor|nand|nor|xnor]", action="append", default=[]) parser.add_argument( "--on", help="Pin On condition, format: <temp|hum>:<eq|lt|lte|gt|gte>:<value>:[or|and|xor|nand|nor|xnor]", action="append", default=[]) parser.add_argument( "--rpc_listen", help="Listen address, default all 0.0.0.0", type=str, default="0.0.0.0") parser.add_argument( "--rpc_port", help="Listen port, default 15555", type=int, default=15555) args = parser.parse_args() logging.basicConfig( level=logging.DEBUG if args.verbose else logging.INFO, format="%(asctime)s %(levelname)-8s %(name)-30s %(message)s" ) logger = logging.getLogger("rpioalert.main") if args.stop is True: logger.info("Reset LED") for pin in args.pin: led = LED(pin) led.off() led.close() sys.exit() try: leds = [LED(pin) for pin in args.pin] except: logger.info("Unable to connect to GPIO Pin {}".format(args.pin)) logger.debug(sys.exc_info()) loop = asyncio.get_event_loop() executor = ThreadPoolExecutor(max_workers=1) lcd = Lcd(lcd_type=args.lcd) stats = Status(lcd=lcd) lock = asyncio.Lock() tasks = [ asyncio.ensure_future(rpio_alert(**{ "leds": leds, "off_condition": args.off, "on_condition": args.on, "off_first": args.off_first, "stats": stats, "lock": lock, "executor": executor, "loop": loop })) ] if args.rpc: tasks.append( asyncio.ensure_future(rpc_server(**{ "leds": leds, "listen": args.rpc_listen, "port": args.rpc_port, "off_condition": args.off, "on_condition": args.on, "off_first": args.off_first, "stats": stats, "lock": lock, "executor": executor, "loop": loop })) ) try: logger.info("Start rpioalert") loop.run_forever() except asyncio.CancelledError: pass except KeyboardInterrupt: pass except: logger.debug(sys.exc_info()) logger.info("Stop rpioalert") loop.run_until_complete(asyncio.wait([shutdown(t) for t in tasks])) executor.shutdown(wait=True) loop.close() lcd.clear_lcd() for led in leds: if not led.closed: led.off() led.close()
'--shutdown_after_seconds', required=False, default=5 * 60, help= "In seconds, how long to wait after no motion is detected to shut down the LED. (default: 5 * 60)" ) parser.add_argument( '--rescan_after_seconds', required=False, default=1, help="In seconds, how long to wait between motion checks. (default: 1)" ) args = parser.parse_args() sensor = MotionSensor(args.sensor_pin) led = LED(args.led_pin) detection_led = LED(args.detection_led_pin) while True: try: turn_on_and_wait( sensor=sensor, led=led, detection_led=detection_led, shutdown_after_seconds=int(args.shutdown_after_seconds), rescan_after_seconds=int(args.rescan_after_seconds)) except KeyboardInterrupt: print("Ending the program.") sensor.close() led.close() detection_led.close() break
def main(): altunitraw = os.getenv('ALTUNIT', 'False') altunit = ast.literal_eval(altunitraw) reverse_pin = int(os.getenv('REV_GPIO', 17)) servo_gpio = int(os.getenv('SERVO_GPIO', 27)) backup_in = int(os.getenv('BACKUP_GPIO', 22)) obd_port = os.getenv('OBD_PORT', '/dev/elm_obd') arduino_port = os.getenv('ARDUINO_PORT', None) logging.warning('Reverse activate pin {0}'.format(reverse_pin)) logging.warning('Video Switch Servio pin {0}'.format(servo_gpio)) logging.warning('Backup activate pin {0}'.format(backup_in)) logging.warning('ELM327 OBD Serial port {0}'.format(obd_port)) logging.warning('Arduino (Physical Interface Unit) Serial port {0}'.format( arduino_port)) logging.warning('Use Alt Units - (Imperial) {0}'.format(altunit)) if arduino_port: arduino = Arduino(arduino_port) arduino.start() lock = Lock() #Set screen on pin screen_reverse_pin = LED(reverse_pin) screen_reverse_pin.blink(on_time=10, off_time=1, background=True) #Could not make this work in a function.. Or a thread.. if servo_gpio and backup_in: logging.warning( 'Setting up 2 way video switch on GPIO {0} triggered by {1}.'. format(servo_gpio, backup_in)) backup = Button(backup_in) init_servo = 1 if backup.value else -1 servo = Servo(servo_gpio, initial_value=init_servo) backup.when_pressed = servo.max backup.when_released = servo.min mirror = Carmirror(gps=True, obd_port=obd_port, altunit=altunit) mirror.infoscreen("starting OBD", "Please wait") mirror.configobd() mirror.infoscreen("starting GPS", "Please wait") mirror.configgps() if mirror.connection: mirror.codes() currentscreen = 1 buttonpressed = False totalscreens = 4 + len(gauges) try: while True: currentscreen = currentscreen % totalscreens keypress = None if currentscreen == 0: if arduino_port: lock.acquire() ax = arduino.get_value('AY') / 9.81 ay = arduino.get_value('AX') / 9.81 maxx = arduino.get_value('MAY') / 9.81 maxy = arduino.get_value('MAX') / 9.81 lock.release() keypress = mirror.accelerometer(ax, ay, maxx, maxy) else: currentscreen = currentscreen + 1 if currentscreen == 1: keypress = mirror.gpsscreen() if currentscreen == 2: keypress = mirror.obd_main() if currentscreen == 3: keypress = mirror.obd_airfuel() if currentscreen > 3: keypress = mirror.obd_gauge(**gauges[currentscreen - 4]) #handle user inputs. if arduino_port: buttons = arduino.get_value('BTNS') if buttons and not buttonpressed: buttonpressed = True if int(buttons) == 1: currentscreen += 1 elif int(buttons) == 2: currentscreen -= 1 elif int(buttons) == 3: # Set fav for now.. currentscreen = 4 elif not buttons: buttonpressed = False if keypress == 'K_LEFT': currentscreen -= 1 if keypress == 'K_RIGHT': currentscreen += 1 except KeyboardInterrupt: logging.warning('interrupted!') screen_reverse_pin.close()
# using random to generate blinking interval from gpiozero import LED import random from time import sleep led = LED(17) try: while True: interval = random.uniform(0.1, 3) print("interval is " + str(interval)) print("on!") led.on() sleep(interval) print("off!") print() led.off() sleep(interval) except KeyboardInterrupt: print('interrupted!') led.close() # cleans up pin
#!/usr/bin/python3 from gpiozero import LED from time import sleep red = LED(21) sleep_speed = 0.5 print("Press Crtl-C to stop the program.") while True: try: red.on() sleep(sleep_speed) red.off() sleep(sleep_speed) except KeyboardInterrupt: print("Stopping program.\n") red.close() exit()
def smart(bot): global led1 global led2 global led3 global update_id back = 20 # led status if led1.closed: led1 = LED(12) if led2.closed: led2 = LED(21) if led3.closed: led3 = LED(16) for update in bot.get_updates(offset=update_id, timeout=10): update_id = update.update_id + 1 action_list = [["روشن", "بازگشت"], [""]] sleep(1) update.message.reply_text( "لطفا یکی از گزینههای زیر را انتخاب نمائید : ", reply_markup=telegram.ReplyKeyboardMarkup(action_list, one_time_keyboard=True)) led1.off() led2.off() led3.off() if update.message: if update.message.text == "روشن": while back: lightLevel = readLight() update.message.reply_text( "شدت نور برابر است با : {}".format(lightLevel)) if 100 < lightLevel < 150: led1.on() led2.off() led3.off() update.message.reply_text("چراغ یک روشن") elif 50 < lightLevel < 100: led1.on() led2.on() led3.off() update.message.reply_text("چراغ یک و دو روشن") elif lightLevel < 50: led1.on() led2.on() led3.on() update.message.reply_text("همه چراغها روشن شوند") else: led1.off() led2.off() led3.off() update.message.reply_text( "نیازی به چراغ روشن وجود ندارد.") sleep(2.5) back -= True if not back: update.message.reply_text("تست به پایان رسید!") elif update.message.text == "بازگشت": import run led1.close() led2.close() led3.close() run.main() sleep(1)
def greenLED(): greenled = LED(24) greenled.on() sleep(1) greenled.off() greenled.close()
import argparse from logs import get_logger from gpiozero import LED if __name__ == "__main__": logger = get_logger() logger.info("Beginning garage door app.") parser = argparse.ArgumentParser("Open/close the garage door.") parser.add_argument('--pin', default=os.getenv('GARAGE_DOOR_PIN', 14), required=False, type=int, help="The GPIO pin for the garage door on the Pi.") args = parser.parse_args() logger.info( "Connecting garage door opener to pin ({pin})".format(pin=args.pin)) try: garage_door = LED(args.pin) logger.info("Triggering garage door.") garage_door.toggle() sleep(0.5) garage_door.toggle() logger.info("Garage door has changed its state.") finally: # This closes the pin connection to the program so that the pin can be # readily used again by the next caller even if the above fails for # whatever reason. garage_door.close() logger.info("Ending garage door app.")
# print sensor data for log try: sensor = BME280(mode=BME280_OSAMPLE_8) degrees = sensor.read_temperature() pascals = sensor.read_pressure() hectopascals = pascals / 100 humidity = sensor.read_humidity() print strftime("%Y.%m.%d %H:%M:%S") + ' {0:0.3f} , {1:0.3f} deg C , {2:0.2f} hPa , {3:0.2f} %'.format(sensor.t_fine, degrees, hectopascals, humidity) #print 'Timestamp = {0:0.3f}'.format(sensor.t_fine) #print 'Temp = {0:0.3f} deg C'.format(degrees) #print 'Pressure = {0:0.2f} hPa'.format(hectopascals) #print 'Humidity = {0:0.2f} %'.format(humidity) #print ' ' except (RuntimeError, TypeError, NameError): counter = 0 while counter < 50: led.on() sleep(0.3) led.off() sleep(0.3) counter += 1 led.close() #led2.close()
print('led3 on') elif event == 'led4': led4.on() print('led4 on') elif event == 'led5': led5.on() print('led5 on') elif event == 'led6': led6.on() print('led6 on') elif event == 'led7': led7.on() print('led7 on') elif event == 'led8': print('led8 on') led8.on() elif event is None: break led1.close() led2.close() led3.close() led4.close() led5.close() led6.close() led7.close() led8.close() window.Close() print('done')
#!/usr/bin/env python3 from gpiozero import Button from gpiozero import LED from time import sleep btn = Button(22) btn2 = Button(24) led = LED(16) print(""" From left-to-right, press button 1 for led 4, button 2 to exit. """) while True: if btn.is_pressed: led.on() sleep(0.1) led.off() elif btn2.is_pressed: btn.close() led.close() print("done") exit(0)
# blink_gpiozero.py # BlinkPython # # Description: # Python program to blink an LED on a Raspberry Pi with the GPIO Zero library. # # Created by John Woolsey on 06/07/2018. # Copyright c 2018 Woolsey Workshop. All rights reserved. # Imports from gpiozero import LED from time import sleep # Pin Definitions redLED = LED(21) # BCM pin 21, physical pin 40 # Blink LED print "Press CTRL-C to exit." try: while True: # runs forever redLED.on() # turn on LED sleep(0.5) # wait half a second redLED.off() # turn off LED sleep(0.5) # wait half a second # Cleanup finally: # exit cleanly when CTRL+C is pressed redLED.close() # release redLED resource print "\nCompleted cleanup of GPIO resources."
# print sensor data for log try: sensor = BME280(mode=BME280_OSAMPLE_8) degrees = sensor.read_temperature() pascals = sensor.read_pressure() hectopascals = pascals / 100 humidity = sensor.read_humidity() print strftime("%Y.%m.%d %H:%M:%S") + ' {0:0.3f} , {1:0.3f} deg C , {2:0.2f} hPa , {3:0.2f} %'.format(sensor.t_fine, degrees, hectopascals, humidity) #print 'Timestamp = {0:0.3f}'.format(sensor.t_fine) #print 'Temp = {0:0.3f} deg C'.format(degrees) #print 'Pressure = {0:0.2f} hPa'.format(hectopascals) #print 'Humidity = {0:0.2f} %'.format(humidity) #print ' ' except: counter = 0 while counter < 50: led.on() sleep(0.3) led.off() sleep(0.3) counter += 1 led.close() led2.close()
class Zoltar(object): def __init__(self, comm_client): print('Finally, a Zoltar!') self.is_moving = False self.left_eye = LED(LED1_GPIO) self.right_eye = LED(LED2_GPIO) self.button = Button(BUTTON_GPIO) self.button.when_pressed = self.stop_moving self.communications = comm_client def begin_moving(self): self.left_eye.on() self.right_eye.on() self.servo = AngularServo(SERVO_GPIO, min_angle=SERVO_MIN_ANGLE, max_angle=SERVO_MAX_ANGLE, initial_angle=SERVO_INITIAL_ANGLE) while self.is_moving: if self.communications.available(): (origin, message) = self.communications.recv() if message == 'COIN': break for x in reversed(range(0, 179)): self.servo.angle = x sleep(0.01) for x in range(0, 179): self.servo.angle = x if self.servo.angle == 0: sleep(0.5) else: sleep(0.01) self.finale() def eyes_off(self): self.right_eye.off() self.left_eye.off() def eyes_on(self): self.left_eye.on() self.right_eye.on() def finale(self): self.flashing_eyes() self.print_fortune() self.cleanup_gpio() def print_fortune(self): zoltar_dir = os.getenv('ZOLTAR_DIR') subprocess.Popen(['python', 'zoltar_print_fortune.py'], cwd=zoltar_dir) def flashing_eyes(self): self.eyes_off() sleep(1) self.eyes_on() sleep(1) self.eyes_off() sleep(1) self.eyes_on() sleep(1) self.eyes_off() def stop_moving(self): print('Button detected') self.is_moving = False def cleanup_gpio(self): self.left_eye.close() self.right_eye.close() self.servo.close() self.button.close()
lcd.text('Passcode', 1) lcd.text('Correct!', 2) buzz.on() greenled.on() sleep(2) greenled.off() buzz.off() lcd.text('Initializing', 1) lcd.text('Face Scan...', 2) break else: lcd.text('Passcode', 1) lcd.text('Incorrect!', 2) buzz.on() redled.on() sleep(2) redled.off() buzz.off() userpass = [] elif len(userpass) > len(password): lcd.clear() lcd.text('Please Try Again', 1) sleep(1) userpass = [] redled.close() greenled.close() buzz.close() btn1.close() btn2.close() import faceunlock
#!/usr/bin/env python # requires to install python3-gpiozero # flashes A few leds print("Loading gpiozero..") from gpiozero import LED from time import sleep led1 = LED(4) led2 = LED(18) x = 1 print("Flashing two leds like an alarm..") while (x < 5): print(x, "/ 4", "flashing..") led1.on() sleep(0.5) led1.off() led2.on() sleep(0.5) led2.off() x = x + 1 print("Exiting..") led1.close() led2.close() exit()