def main(): firstRun = True lastRunTimestamp = time.time() players = [] numOnline = 0 redLed = PWMLED(redPin) while True: if (lastRunTimestamp + 300) < time.time() or firstRun == True: firstRun = False lastRunTimestamp = time.time() try: f = open(confFile, 'r') serverInfo = json.loads(f.read()) f.close() #print("checking server status. " + str(time.time())) r = requests.get("https://api.mcsrvstat.us/2/" + serverInfo['ipAddress'], timeout=10).json() numOnline = r['players']['online'] if numOnline > 0: players = r['players']['list'] redLed.pulse() #print(players) else: players = [] redLed.off() #print("didn't find any players") except Exception as e: redLed.blink(0.5,0.5,0,0,15,True) scrollText("Something went wrong") if numOnline > 0: scrollText(listToString(players)) else: scrollText("no one online")
class PWMLEDIndicator(object): """ A pulse-width modulated LED. """ def __init__(self, gpio_pin, brightness=100): """ Constructor of a PWM LED. :param gpio_pin: GPIO pin assignment (not the header pin number) :param brightness: Brightness percentage. Defaults to 100%. """ self.led = PWMLED(gpio_pin) self.brightness = brightness / 100.0 # brightness value is from 0 to 1.0 def turn_on(self): # ~ self.led.on() self.led.value = self.brightness def turn_off(self): # ~ self.led.off() self.led.value = 0 def blink(self, max_times=10): # blink in a separate thread self.led.blink(0.5, 0.2, n=max_times) def pulse(self, max_times=10): # pulse in a separate thread self.led.pulse(n=max_times) def close(self): self.led.close()
def main(): led = PWMLED(conf.LED_PIN) led.blink() # each item in conf.BTNS[] is an individual button setting for this in conf.BTNS: this['button'] = Button(this['PIN']) this['button']when_released = put_curry(this['LABEL']) print("ready!") led.pulse() pause()
row1 = [19] row2 = [11, 27, 17, 25, 16] row3 = [8, 26, 5, 4, 9, 13] row4 = [6, 18, 15, 12, 22, 24, 20] row5 = [7, 21, 14, 10, 23] rows = [row1, row2, row3, row4, row5] lights = [] #while True: for item in rows: for lednum in item: light = PWMLED(lednum) light.blink(on_time=0.1, off_time=1, fade_in_time=0.1, fade_out_time=0.1) lights.append(light) sleep(0.1) # sleep(0.1) # for light in lights: # light.close() # lights = [] # # for item in reversed(rows): # for lednum in item: # light = PWMLED(lednum) # light.blink(on_time=0.1,off_time=1,fade_in_time=0.1,fade_out_time=0.1) # lights.append(light)
#!/usr/bin/python3 from gpiozero import PWMLED from signal import pause red = PWMLED(pin=21, active_high=True, initial_value=0, frequency=100) print("Press Crtl-C to stop the program.") while True: try: red.blink(on_time=1, off_time=1, fade_in_time=0, fade_out_time=0, n=None, background=True) pause() except KeyboardInterrupt: print("Stopping program.\n") red.close() exit()
time.sleep(1) rgbLED.off() # turn on LED singleLED.value = .01 # dim time.sleep(1) singleLED.value = 1 # bright time.sleep(1) singleLED.off() # test the Rangefinder for thisloop in range(0, 5): print(thisloop, ' - Distance to nearest object is', rangefind.distance, 'm') time.sleep(1) # control the LEDs with the rangefinder while True: rangefindDistance = rangefind.distance DIST = rangefindDistance if rangefindDistance <= 1 else 1 invDIST = .1 / rangefindDistance if .1 / rangefindDistance <= 1 else 1 print(DIST, "-", invDIST) if DIST < 1: singleLED.blink(on_time=DIST, off_time=invDIST) else: singleLED.off() rgbLED.color = (invDIST, DIST, 0) time.sleep(.1) # note that I don't gracefully handle program termination.
import json url = conf.URL + endpt opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(url) request.add_header('Content-Type', 'application/json') request.get_method = lambda: 'PUT' try: url = opener.open(request) except urllib.error.URLError as e: print("PUT %s URLError, reason: %s" % (url, e.reason)) except urllib.error.HTTPError as e: print("HTTPError PUT %s == %s" % (url, e.code)) return curry if __name__ == "__main__": led = PWMLED(conf.LED_PIN) led.blink() # each item in conf.BTNS[] is an individual button setting for this in conf.BTNS: this.button = Button(this['PIN']) this.button.when_released = put_curry(this['LABEL']) print("ready!") led.pulse() pause()
from gpiozero import PWMLED my_led = PWMLED('GPIO26') # blink 5 times print('blink') my_led.blink(on_time=1, off_time=1, fade_in_time=0.75, fade_out_time=0.75, n=5)
from gpiozero import MotionSensor from gpiozero import PWMLED from time import sleep pir = MotionSensor('GPIO26') my_led1 = PWMLED('GPIO6') my_led2 = PWMLED('GPIO13') while True: print("waiting") pir.wait_for_motion() print("Motion detected!") my_led1.blink(on_time=1, off_time=1, fade_in_time=0.75, fade_out_time=0.75, n=5, background=True) sleep(1) my_led2.blink(on_time=1, off_time=1, fade_in_time=0.75, fade_out_time=0.75, n=5, background=False)
# check the buttons thread for new input while len(record) > 0: item = record.popleft() if item == 0 and idle: idle = False recording = True custom_chars.load_level() rec = AudioIO.Recorder(channels=input_channels, rate=input_rate, device=input_device) rec_stream = rec.open(fname=basepath + '/recordings/' + datetime.now().strftime( '%Y%m%d_%H%M%S') + '.wav') rec_stream.start_recording() record_led.blink() dsphlp.dspwrite(lcd, clear=1) rec_screen = dsphlp.display_screen(lcd) if item == 1 and recording: idle = True recording = False rec_stream.stop_recording() rec_stream.close() reclist = get_recordingsList(basepath + '/recordings/') MainMenu.replaceLevelItemList('0.', reclist[0]) record_led.off() standard_screen() while len(play) > 0: item = play.popleft() if item == 0 and menu and MainMenu.CurrentItem.startswith('0.') and not playing: selectedrecording = int(MainMenu.CurrentItem.split('.')[MainMenu.CurrentLevel])
from gpiozero import MCP3008, PWMLED pot1 = MCP3008(0) pot2 = MCP3008(1) led = PWMLED(21) while True: print(pot1.value, pot2.value) led.blink(on_time=pot1.value, off_time=pot2.value, n=1, background=False)
# Import libraries import RPi.GPIO as GPIO from gpiozero import PWMLED from time import sleep from signal import pause # Write all codes inside try statement try: led = PWMLED(17) led.blink(2,2) pause() # except statement to handle user's keyboard interrupt except KeyboardInterrupt: print("Stopping python script...") print("Cleaning up GPIO...") # finally statement will run before exiting try statement finally: GPIO.cleanup() print("Cleaning completed!") print("Exit program")
led1_fadein = 3 led1_fadeout = 1.5 hold_time = 3.0 #----- functions ------ def shut_down(): led1.pulse(led1_fadein, led1_fadeout) system("sudo shutdown -h now") sleep(40) # should take no more than 40 secs to shutdown #----- start of main logic------ while True: led1.on() btn1.wait_for_press() led1.blink(0.2, 0.2) start_time = time() while btn1.value == True: sleep(0.1) duration = time() - start_time if duration > hold_time: shut_down() #----- end of main logic -----
from gpiozero import PWMLED from time import sleep pwmled = PWMLED(24) pwmled.blink(1, 1, 0, 0, 3, False) sleep(3) pwmled.pulse(3, 3, 3, False)
#!/usr/bin/python3 # Beispieldatei gpiozero-led-pwm.py from gpiozero import PWMLED import sys, time myled = PWMLED(7, frequency=1000) # BCM-Nummer 7 = Pin 26 des J8-Header # Frequenz: 1000 Hz print("LED wird langsam heller") myled.value = 0 myled.on() for brightness in range(1, 11): myled.value = brightness / 10.0 time.sleep(0.5) print("LED blinkt zehn Mal") myled.blink(on_time=0.5, off_time=0.25, n=10, background=False) print("Kurze Pause") time.sleep(1) print("LED blinkt dreimal langsam, halbe Helligkeit") myled.value = 0.1 myled.blink(on_time=1, off_time=1, n=3, background=False) print("LED aus und Programmende") myled.off()
class PomodoroTimer(object): def __init__(self): self.timer = None self.led = PWMLED(LIGHT_PIN) self.buzzer = TonalBuzzer(BUZZER_PIN) def times_up(self): print("Time's up") self.fin() def start_pomodoro(self, channel): print("Start Pomodoro") self.led.blink(on_time=0.3, off_time=0.3, n=5, background=True) if (self.timer != None): print("Pomodoro was re-started") self.timer.cancel() self.timer = Timer(5, self.times_up) self.timer.start() def play_note(self, note, duration=0.04): self.buzzer.play(Tone.from_note(note)) sleep(duration) self.buzzer.stop() def ending_music(self): # Available Range # A3, B3, C4, D4, E4, F4, G4, A4, B4 arpeggio = [ "A#3", "C#4", "E#4", "A#3", "C#4", "E#4", "A#3", "C#4", "E#4", "A#3", "C#4", "E#4", "A3", "C4", "E4", "A3", "C4", "E4", "A3", "C4", "E4", "A3", "C4", "E4", "C4", "E4", "G4", "C4", "E4", "G4", "C4", "E4", "G4", "C4", "E4", "G4", "Cb4", "Eb4", "Gb4", "Cb4", "Eb4", "Gb4", "Cb4", "Eb4", "Gb4", "Cb4", "Eb4", "Gb4", "A#3", "C#4", "E#4", "A#3", "C#4", "E#4", "A#3", "C#4", "E#4", "A#3", "C#4", "E#4", "A3", "C4", "E4", "A3", "C4", "E4", "A3", "C4", "E4", "A3", "C4", "E4", ] for note in arpeggio: self.play_note(note) self.play_note("A3", duration=0.2) def fin(self): self.led.pulse() self.ending_music() self.led.off() def run(self): self.button = Button(BUTTON_PIN, pull_up=False) self.button.when_pressed = self.start_pomodoro pause()
#!/usr/bin/python3 from gpiozero import PWMLED from signal import pause red = PWMLED(pin=21, active_high=True, initial_value=0, frequency=100) print("Press Crtl-C to stop the program.") while True: try: red.blink(on_time=0.5, off_time=0.5, fade_in_time = 2, fade_out_time = 2, n=None, background=True) pause() except KeyboardInterrupt: print("Stopping program.\n") red.close() exit()
from gpiozero import PWMLED status_led = PWMLED(24) type = int(input("Enter type: ")) if type == 0: status_led.on() elif type == 1: status_led.blink(0.5, 0.5) while True: a = 1
class Element(Function): def __init__(self, id, config, inputData, return_queue, cmd_queue): super().__init__(id, config, inputData, return_queue, cmd_queue) def execute(self): ##################################### # # # REFERENCE IMPLEMENTATION # # # ##################################### specificConfig = self.config.get('SpecificConfig') if not specificConfig: self.return_queue.put( Record(None, message='Trigger: {:04d}'.format( self.config['Identifier']))) return gpioName = None mainMode = None subModeLED = None subModePWMLED = None gpioWorker = None cmd = None self.gpio = None self.initFlag = False for attrs in specificConfig: if attrs['Name'] == 'GPIO': gpioName = attrs['Data'] if attrs['Name'] == 'MainMode': mainMode = attrs['Data'] elif attrs['Name'] == 'SubModeLED': subModeLED = attrs['Data'] elif attrs['Name'] == 'SubModePWMLED': subModePWMLED = attrs['Data'] if mainMode == 'LED': self.gpio = LED(gpioName, initial_value=False) if subModeLED == 'Toggle on input': gpioWorker = self.ledWorkerToggle self.gpio.toggle() self.logLEDstate() elif subModeLED == 'Control on Input': gpioWorker = self.ledWorkerCtrl # set initial state if self.inputData is not None: if self.inputData: self.gpio.on() else: self.gpio.off() self.logLEDstate() elif subModeLED == 'Blink': def a(cmd=None): pass gpioWorker = a # assign an empty function self.gpio.blink() self.return_queue.put( Record( None, 'Start LED Blink Mode on GPIO{}'.format( self.gpio.pin.number))) elif mainMode == 'PWMLED': self.gpio = PWMLED(gpioName, initial_value=False) if subModePWMLED == 'Control on Input': gpioWorker = self.pwmLedWorkerCtrl if self.inputData is not None: self.gpio.value = self.inputData self.return_queue.put( Record( None, 'PWMLED: Set brightness on GPIO{} to {:.2f}'. format(self.gpio.pin.number, self.inputData))) elif subModePWMLED == 'Pulse': def a(cmd=None): pass gpioWorker = a # assign an empty function self.gpio.pulse() self.return_queue.put( Record( None, 'Start PWMLED Pulse Mode on GPIO{}'.format( self.gpio.pin.number))) ##################################### # # # Start of the infinite loop # # # ##################################### while (True): # Example code: Do something try: # Block for 1 second and wait for incoming commands cmd = None cmd = self.cmd_queue.get(block=True, timeout=1) except queue.Empty: pass if isinstance(cmd, ProcCMD): if cmd.bStop: # Stop command received, exit self.return_queue.put( Record(None, 'GPIO{} closed'.format(self.gpio.pin.number))) self.gpio.close() return gpioWorker(cmd) def logLEDstate(self): self.return_queue.put( Record( None, 'Switch LED on GPIO{} to {}'.format(self.gpio.pin.number, self.gpio.is_active))) def ledWorkerToggle(self, cmd=None): if cmd is None: return self.gpio.toggle() self.logLEDstate() def ledWorkerCtrl(self, cmd=None): if cmd is None: return if cmd.data: self.gpio.on() else: self.gpio.off() self.logLEDstate() def pwmLedWorkerCtrl(self, cmd=None): if cmd is None: return try: self.gpio.value = cmd.data except Exception: self.gpio.close() raise self.return_queue.put( Record( None, 'PWMLED: Set brightness on GPIO{} to {:.2f}'.format( self.gpio.pin.number, cmd.data)))
message_arr = message.split(" ") station = message_arr[0] command = message_arr[1] message if command == "fire": insert_fire_event( conn, station, "fire outbreak", datetime.now().strftime("%Y-%m-%d %H:%M:%S"), ) SERIAL and sendCommand(message) if station == STATION_NAME: status_led and status_led.on() else: status_led and status_led.blink(0.5, 0.5) elif command == "reset": SERIAL and sendCommand(message) status_led and status_led.off() except IndexError: print("Error processing message") if time.time() - postTime > POST_INTERVAL: postTime = time.time() print("sending values to cloud") send_values_cloud(conn) time.sleep(0.1) # while True:
#!/usr/bin/env python3 from gpiozero import Button, PWMLED import os from signal import pause from time import sleep masterled = PWMLED( 14, initial_value=1 ) #define led as pulse-width modultaion, use pin 14 as the positive power pin, and intial_value=1 means start at full power #comment out below line if you want to keep the led on solid rather than "pulse" masterled.blink( on_time=10, off_time=1, fade_in_time=5, fade_out_time=5, background=True ) #make led "pulse" 10 sec solid on, 5 sec to fade out, 1 sec solid off, 5 sec to reach max brightness indefinitely, allow script to continue with background=True #power = PWMLED(4) #not used for single power/reset button #power.on() #not used for single power/reset button masterBtn = Button( 3, hold_time=2 ) #define button, use pin 3 as the positive pin, hold_time is how many seconds button must be "held" to trigger shutdown, must be equal to or less than sleep time in while loop below #rebootBtn = Button(2) #not used for single power/reset button #functions that handle button events def shutdown(): masterled.blink( on_time=.5, off_time=.5, fade_in_time=0, fade_out_time=0, n=4, background=False
from time import sleep from gpiozero import PWMLED pwm_led = PWMLED('GPIO13') # Blink the easy way print('I\'m blinking!') pwm_led.blink(0.5, 0.25, n=25, background=False) # Change the brightnes with PWM while True: print('I\'m glowing!') for v in range(0, 11): pwm_led.value = v / 10 sleep(0.25) for v in range(10, -1, -1): pwm_led.value = v / 10 sleep(0.25)
ecodes.KEY_9, ecodes.KEY_0, ) evdev_device = 0 try: evdev_device = int(sys.argv[1]) except IndexError: pass except ValueError: pass print("Almost there, pulse the eyes to let the user know") eyes = PWMLED(21) eyes.blink(0.5, 0.25, 0.25, 0.25, 3, False) eyes.on() print("Initialised, now handling events") try: # Only run the motors at 50% initially power = 0.5 # Process the (lirc-spawned) events device = InputDevice("/dev/input/event" + str(evdev_device)) for event in device.read_loop(): if event.type == ecodes.EV_KEY: if event.value == 1: # key down if event.code in robot_movement: robot_movement[event.code](power) elif event.code in robot_power: