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
from gpiozero import LED from gpiozero.pins.pigpio import PiGPIOFactory from signal import pause factory = PiGPIOFactory(host='raspberrypi.local') led = LED(17, pin_factory=factory) led.blink() pause()
class StatefulHWButton(StatefulButton): """Cycling mode button with an LED and button Args: StatefulHWButton ([type]): [description] """ def __init__(self, path, states, led_pin=None, button_pin=None, fallback=None): super().__init__(path, states, fallback) self.button = None self.led = None self.lit_for = None self.last_pressed = dt.min self.button = None self.led = None try: # only works on raspi if button_pin: self.button = Button(button_pin) self.button.when_pressed = self.push if led_pin: self.led = LED(led_pin) except Exception as e: LOGGER.warning(f"Exception but continuing:{e}") LOGGER.debug(f"Exception but continuing:{e}", exc_info=True) def __str__(self): return f"StatefulHWButton: {vars(self)}" def __repr__(self): return f"StatefulHWButton: {vars(self)}" def illuminate(self): """ Don't change, just illuminate """ self.last_pressed = dt.now() self.set_LED() def push(self): """ Resets the dormancy counter. """ #LOGGER.debug("button pushed!") moment = dt.now() if self.lit_for is None or moment < self.last_pressed + self.lit_for: # active: change state next(self) self.set_LED() self.last_pressed = dt.now() def set_LED(self): if not self.led: return current = self.value try: led_on_time = current.on_time led_off_time = current.off_time one_n = led_on_time + led_off_time # LOGGER.debug(f"set_LED; {vars(self)}") if self.lit_for is None: self.led.blink(on_time=led_on_time, off_time=led_off_time) else: led_n = int(self.lit_for.total_seconds() / one_n) self.led.blink(on_time=led_on_time, off_time=led_off_time, n=led_n) except KeyError as exc: raise ButtonError("check set_LED") from exc def configd(self, config_dict): if 'button' in config_dict: c = config_dict['button'] else: c = config_dict LOGGER.debug(f"button config: {c}") self.path = Path(c['file']) self.button = Button(c['button']) self.button.when_pressed = self.push self.led = LED['led'] LOGGER.debug(f"button configd: {self.path}, button: {self.button}, led: {self.led}") # self.value() # update from new file self.set_LED()
file = open("/home/pi/retropicam/auths/ACCESS_KEY.txt","r") ACCESS_KEY = file.read() file = open("/home/pi/retropicam/auths/ACCESS_SECRET.txt","r") ACCESS_SECRET = file.read() api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET) #setup ins and outs btn = Button(23) led = LED(17) bz = Buzzer(2) #Setect button while True: if btn.is_pressed: #User feedback led.blink(0.05,0.05) bz.beep(on_time=0.1,off_time=0.1) print("Button pressed, taking photos...") #Take photos filename = "/home/pi/retropicam/photos/photo" #Take gif photos for num in range (length): date = time.strftime("%d-%m-%Y-%H-%M%S") takephoto = "fswebcam -r "+resolution+" --no-banner"+" "+filename+"-"+date+".jpg" os.system(takephoto) #User feedback print("Photos Taken") led.off() bz.off()
if x == 10: break print "Checking pin no.", x, ": GPIO", lvlPinNoArray[x] lvlPin = Button(lvlPinNoArray[x], pull_up=False) if lvlPin.is_pressed: break result = (10.0 - x) / 10.0 print "Detected tank level is ", result * 100, "%" seedVoltage.off() return result print "Starting..." pump = LED(pumpPinNo) statusLed = LED(statusLedPin) while True: level = readTankLevel() print "Level =", level * 100, "%" # TODO: Store level in Log # Check level and turn off pump if necessary if level * 100 < threshold: pump.off() else: pump.on() statusLed.blink() sleep(sleep_time) print "Done."
while seeking == True: # Get players position playerPos = mc.player.getPos() # Has the player moved if lastPlayerPos != playerPos: distanceFromBlock = distanceBetweenPoints(randomBlockPos, playerPos) if distanceFromBlock < 2: # found it! seeking = False else: if distanceFromBlock < 5 and position != 4: led.on() position = 4 if 4 < distanceFromBlock < 11 and position != 3: led.blink(0.3, 0.3) position = 3 if 10 < distanceFromBlock < 26 and position != 2: led.blink(0.6, 0.5) position = 2 if 25 < distanceFromBlock < 41 and position != 1: led.blink(1, 0.5) position = 1 if distanceFromBlock > 40 and distanceFromBlock < lastDistanceFromBlock: led.blink() if distanceFromBlock > 40 and distanceFromBlock > lastDistanceFromBlock: led.off() lastDistanceFromBlock = distanceFromBlock sleep(2)
import sys import piglow #initialize led indicator red = LED(16) red.off() piglow.all(0) piglow.show() #function to gradually change the volume def rampvol(speed = 0.25, start = 0, stop = 100, step = 1): vol = start while vol != stop: vol = vol + step system("amixer -q sset PCM,0 " + str(vol) + "%") sleep(speed) #blink all the indicators red.blink(0.25,0.25,5,1) red.off() i = 0 while i <= 5: piglow.red(1) piglow.show() i += 1 sleep(0.5) piglow.red(0) piglow.show() sleep(0.5) day = int(time.strftime("%j")) #get the day of the year [0,366] playlist = ( int(day) + offset ) % 2 if playlist == 0: if day > 330: #kiss me baby, it's christmas time maxvol = 80
from gpiozero import LED led = LED(18) led.blink(0.5, 0.5, background=True) print("here") input() print("there") led.off() input()
photoButton.when_held = snapShot #GPIO button assignment for send location locationButton = Button(26, hold_time=0.5) locationButton.when_held = sendLocation #Sensehat joystick assignments sense.stick.direction_up = powerOff sense.stick.direction_down = powerOff sense.stick.direction_left = powerOff sense.stick.direction_right = powerOff #Main function, will run until colission detected or user powers off device while True: sense.clear() greenLed.blink() sense.show_message("ON", text_colour=green) time.sleep(2) sense.clear() #Counter variable controls while counter < 21: curTime = time.gmtime() curMin = curTime.tm_min curSec = curTime.tm_sec #print("Cursec",curSec) #Resets video number to zero if video count >2 # Only video 0,1,2 are maintained on the device if vidNum > 2: vidNum = 0 print("Reset vidNum") #If the device is recorsing and the current secont modulo 20 = 0
class MP2_A2: def __init__(self): # Preparing self.audiodir = path.expanduser('~/Git/MP2_A2_audiofiles/AudioFiles') self.fire = Fire("Arduino") self.first_button = Button(pin_fig.first_button) self.second_button = Button(pin_fig.second_button) self.main_status_led = LED(pin_fig.status_led_2) self.recovery_staus_led = LED(pin_fig.status_led_1) self.get_option() def get_option(self): argparser = ArgumentParser() argparser.add_argument('-t', '--finishtime', action='store_true', help='Measure finish time') # default is False argparser.add_argument('-e', '--waitforenter', action='store_true', help=('Wait for ENTER key ' 'instead of button press')) # default is False argparser.add_argument('-nl', '--no-loop', action='store_true', help='Loop this script') # default is False self.option = argparser.parse_args() def move_robot(self): # Preparing self.fc = FireAndConveyor(audiofiles_dir=self.audiodir) self.ee = ExplodeAndEscape(audiofiles_dir=self.audiodir) # Move Robot self.main_status_led.on() if self.option.waitforenter: input("Waiting for ENTER key instead of BUTTON1 (first section): ") else: print("Waiting for BUTTON1 press (first section)") self.first_button.wait_for_press() print("move_robot start") self.main_status_led.blink(on_time=1, off_time=2) init_time = time() self.fire.on() self.fc.main(init_time) self.main_status_led.blink(on_time=0.5, off_time=0.5) if self.option.waitforenter: input("Waiting for ENTER key instead of BUTTON2 (second section): ") else: print("Waiting for BUTTON2 press (second section)") self.second_button.wait_for_press() self.main_status_led.blink(on_time=1, off_time=2) self.ee.main(init_time) sleep(1) self.fire.off() print("move_robot end") if self.option.finishtime: input("Press ENTER key to measure finish time: ") print("{:.3f} sec: ".format(time() - init_time), end="") self.main_status_led.off() def recovery_robot(self): # Preparing self.recovery = Recovery() # Recovery Robot sleep_time = 0.1 self.recovery_staus_led.on() print("Waiting for BUTTON1 press (recovery section)") self.first_button.wait_for_press() press_button_time = 0 while self.first_button.is_pressed: press_button_time += 1 if press_button_time >= 2.0 / sleep_time: self.recovery_staus_led.off() sleep(sleep_time) if press_button_time < 2 / sleep_time: print("recovery_robot start") self.recovery_staus_led.blink(on_time=1, off_time=2) self.recovery.main() print("recovery_robot end") self.recovery_staus_led.off() else: print("recovery was skipped") def main(self): self.move_robot() self.recovery_robot() # Start main() again for loop if not self.option.no_loop: self.main()
class FootController(object): def __init__(self): self.power_led = LED(6) self.green_led = LED(17) self.blue_led = LED(27) self.yellow_led = LED(22) self.red_led = LED(24) self.white_led = LED(25) self.moller = { 'led': self.green_led, # value 100 is off 'value': 100, 'sig': 0x52, } self.ts = { 'led': self.blue_led, # value 100 is off 'value': 100, 'sig': 0x50, } self.delay = { 'led': self.yellow_led, # value 100 is off 'value': 100, 'sig': 0x51, } self.mute = { # value 100 is off 'value': 100, 'sig': 0x54, } self.bunk = { 'value': 0, } self.amp = { 'value': 'jcm900', 'jcm900': { 'led': self.red_led, 'sig': 0x00 }, 'twin reverb': { 'led': self.white_led, 'sig': 0x01 } } self.amp['jcm900']['led'].on() self.right_button = Button(13) self.right_button.when_pressed = self.right_button_push self.center_button = Button(19) self.center_button.when_pressed = self.center_button_push self.left_button = Button(26) self.left_button.when_pressed = self.left_button_push self.other_button = Button(23) self.other_button.when_pressed = self.mute_change self.power_led.on() def ts_change(self, on_off=''): if on_off == '' and self.ts['value'] == 100: self.ts['led'].on() self.ts['value'] = 0 print('TS ON') elif on_off == '' and self.ts['value'] == 0: self.ts['led'].off() self.ts['value'] = 100 print('TS OFF') elif on_off == 'on': self.ts['led'].on() self.ts['value'] = 0 print('TS ON') else: self.ts['led'].off() self.ts['value'] = 100 print('TS OFF') controller_change = [ CONTROLLER_CHANGE, self.ts['sig'], self.ts['value'] ] midiout.send_message(controller_change) def delay_change(self, on_off=''): if on_off == '' and self.delay['value'] == 100: self.delay['led'].on() self.delay['value'] = 0 print('Delay ON') elif on_off == '' and self.delay['value'] == 0: self.delay['led'].off() self.delay['value'] = 100 print('Delay OFF') elif on_off == 'on': self.delay['led'].on() self.delay['value'] = 0 print('Delay ON') else: self.delay['led'].off() self.delay['value'] = 100 print('Delay OFF') controller_change = [ CONTROLLER_CHANGE, self.delay['sig'], self.delay['value'] ] midiout.send_message(controller_change) def moller_change(self, on_off=''): if on_off != 'off' and self.moller['value'] == 100: self.moller['led'].on() self.moller['value'] = 0 print('Moller ON') else: self.moller['led'].off() self.moller['value'] = 100 print('Moller OFF') controller_change = [ CONTROLLER_CHANGE, self.moller['sig'], self.moller['value'] ] midiout.send_message(controller_change) def mute_change(self): if self.mute['value'] == 100: self.mute['value'] = 0 self.red_led.blink() self.moller_change('off') self.ts_change('off') self.delay_change('off') print('Mute ON') self.bunk_status() else: self.mute['value'] = 100 print('Mute OFF') if self.bunk['value'] in [0, 1]: self.moller_change('off') self.ts_change('off') self.delay_change('off') # jcm900 ON self.red_led.on() if self.amp['value'] != 'jcm900': self.amp['value'] = 'jcm900' controller_change = [ CONTROLLER_CHANGE, self.amp['jcm900']['sig'], 100 ] midiout.send_message(controller_change) controller_change = [ CONTROLLER_CHANGE, self.mute['sig'], self.mute['value'] ] midiout.send_message(controller_change) def right_button_push(self): if self.mute['value'] == 0: return if self.bunk['value'] == 0: self.moller_change() elif self.bunk['value'] == 1: self.ts_change('off') self.delay_change('off') def center_button_push(self): if self.mute['value'] == 0: self.decrement_bunk() return if self.bunk['value'] == 0: self.ts_change() elif self.bunk['value'] == 1: self.ts_change('on') self.delay_change('off') def left_button_push(self): if self.mute['value'] == 0: self.increment_bunk() return if self.bunk['value'] == 0: self.delay_change() elif self.bunk['value'] == 1: self.ts_change('on') self.delay_change('on') def increment_bunk(self): if self.bunk['value'] == 7: self.bunk['value'] = 0 else: self.bunk['value'] += 1 print('Bunk Change: Number {}'.format(self.bunk['value'])) self.bunk_status() def decrement_bunk(self): if self.bunk['value'] == 0: self.bunk['value'] = 7 else: self.bunk['value'] -= 1 print('Bunk Change: Number {}'.format(self.bunk['value'])) self.bunk_status() def bunk_status(self): if self.bunk['value'] == 0: self.green_led.off() self.blue_led.off() self.yellow_led.off() elif self.bunk['value'] == 1: self.green_led.on() self.blue_led.off() self.yellow_led.off() elif self.bunk['value'] == 2: self.green_led.off() self.blue_led.on() self.yellow_led.off() elif self.bunk['value'] == 3: self.green_led.on() self.blue_led.on() self.yellow_led.off() elif self.bunk['value'] == 4: self.green_led.off() self.blue_led.off() self.yellow_led.on() elif self.bunk['value'] == 5: self.green_led.on() self.blue_led.off() self.yellow_led.on() elif self.bunk['value'] == 6: self.green_led.off() self.blue_led.on() self.yellow_led.on() elif self.bunk['value'] == 7: self.green_led.on() self.blue_led.on() self.yellow_led.on()
from gpiozero import LED, LightSensor, Button, DistanceSensor, PWMOutputDevice, AngularServo from signal import pause from gpiozero import PWMLED import Adafruit_DHT import RPi.GPIO as GPIO from time import sleep import random blue = LED(6) blue.blink() pause()
from gpiozero import LED import time import random nose = LED(25) left = LED(23) right = LED(24) leds = [LED(7), LED(8), LED(9), LED(22), LED(18), LED(17)] left.off() right.off() time.sleep(1) nose.blink() left.on() right.on() def sparkle(): for i in range(25): result = random.choice(leds) result.on() time.sleep(0.2) result.off() while True: sparkle() time.sleep(0.2)
from gpiozero import LED import time # GPIO 24 ... LED ... 470 ohm resistor ... GND led = LED(24) try: led.blink() time.sleep(20) except KeyboardInterrupt: led.off() print "done"
modra.on() # Zhasni zelenou LED a rozsvit vyckavaci modrou LED # Zacatek hlavniho proudu programu if __name__ == "__main__": cervena = LED(22) # Cervena LED na pinu 22 zelena = LED(23) # Zelena LED na pinu 23 modra = LED(27) # Modra LED na pinu 27 smycka = True # Pokud dorazi signal preruseni/ukonceni programu, zpracuj funkci uklid_pri_vypnuti signal.signal(signal.SIGINT, uklid_pri_vypnuti) signal.signal(signal.SIGTERM, uklid_pri_vypnuti) modra.blink(.1, .1, None, True) # Rozblikej modrou LED v separatnim vlakne # Cekej, dokud neoverim, ze jsem pripojeny k Wi-Fi (dostal jsem od DHCP serveru IP adresu) ip = None while ip is None: ip = ziskej_ip("wlan0") if ip == None: print("Cekam na Wi-Fi...") time.sleep(1) else: print("Jsem pripojeny k Wi-Fi a mam IP adresu") modra.on() # Ukonci blikani a rozsvit vyckavaci modrou LED zarizeni = "/sys/bus/w1/devices/" # Adresar pripojenych 1-Wire zarizeni soubor = open("/boot/teplomer_konfigurace.txt") # Precti konfguraci programu jako JSON
class treeWater: def __init__(self): self.GPIO_led_R1 = 14 self.GPIO_led_Y1 = 15 self.GPIO_led_G1 = 4 self.GPIO_led_B1 = 17 self.GPIO_btn_B1 = 18 self.MTR_pump1 = 1 self.GPIO_wtr_tgd = 21 self.GPIO_wtr_t01 = 20 self.GPIO_wtr_t02 = 19 self.GPIO_wtr_t03 = 16 self.GPIO_wtr_t04 = 13 self.GPIO_wtr_t05 = 12 self.GPIO_wtr_t06 = 6 self.GPIO_wtr_t07 = 5 self.GPIO_wtr_t08 = 7 self.GPIO_wtr_t09 = 8 self.GPIO_wtr_t10 = 11 self.GPIO_wtr_t11 = 9 self.GPIO_wtr_t12 = 10 self.GPIO_wtr_t13 = 25 self.GPIO_wtr_pgd = 22 self.GPIO_wtr_p01 = 23 # Setup the water level indicator # self.wtrLevel = LEDBarGraph(self.GPIO_led_R1, self.GPIO_led_Y1, self.GPIO_led_G1, pwm=True) # Setup the Pump Water Level Sensor # _pumpWtrLevelGnd should remain ON the entire time self._pumpWtrLevelGnd = DigitalOutputDevice(self.GPIO_wtr_pgd, True, True) self.pumpWtrLevel = DigitalInputDevice(self.GPIO_wtr_p01) # Setup the tree water level indicator # _treeWtrLevelGnd should remain ON the entire time self._treeWtrLevelGnd = DigitalOutputDevice(self.GPIO_wtr_tgd, True, True) self.treeWtrLevel01 = DigitalInputDevice(self.GPIO_wtr_t01) self.treeWtrLevel02 = DigitalInputDevice(self.GPIO_wtr_t02) self.treeWtrLevel03 = DigitalInputDevice(self.GPIO_wtr_t03) self.treeWtrLevel04 = DigitalInputDevice(self.GPIO_wtr_t04) self.treeWtrLevel05 = DigitalInputDevice(self.GPIO_wtr_t05) self.treeWtrLevel06 = DigitalInputDevice(self.GPIO_wtr_t06) self.treeWtrLevel07 = DigitalInputDevice(self.GPIO_wtr_t07) self.treeWtrLevel08 = DigitalInputDevice(self.GPIO_wtr_t08) self.treeWtrLevel09 = DigitalInputDevice(self.GPIO_wtr_t09) self.treeWtrLevel10 = DigitalInputDevice(self.GPIO_wtr_t10) self.treeWtrLevel11 = DigitalInputDevice(self.GPIO_wtr_t11) self.treeWtrLevel12 = DigitalInputDevice(self.GPIO_wtr_t12) self.treeWtrLevel13 = DigitalInputDevice(self.GPIO_wtr_t13) # Setup the pump status indicator and manual override button self.pumpStsLED = LED(self.GPIO_led_B1) self.pumpBtn = Button(self.GPIO_btn_B1, True) # create a default object, no changes to I2C address or frequency self.mtrHat = Adafruit_MotorHAT(addr=0x60) self.pump = self.mtrHat.getMotor(self.MTR_pump1) # We should always run at max speed self.pump.setSpeed(255) self.pumpSts = False # recommended for auto-disabling motors on shutdown! def Shutdown(self): self.mtrHat.getMotor(1).run(Adafruit_MotorHAT.RELEASE) self.mtrHat.getMotor(2).run(Adafruit_MotorHAT.RELEASE) self.mtrHat.getMotor(3).run(Adafruit_MotorHAT.RELEASE) self.mtrHat.getMotor(4).run(Adafruit_MotorHAT.RELEASE) def pumpRun(self): if self.pumpSts == False: # Pump is off; Turn it on self.log("Turning Pump On","INFO") self.pump.run(Adafruit_MotorHAT.FORWARD) self.pumpSts = True self.pumpStsLED.on() #else: # Pump is already running; Do nothing def pumpStop(self): if self.pumpSts == True: # Pump is on; Turn it off self.log("Turning Pump Off","INFO") self.pump.run(Adafruit_MotorHAT.RELEASE) self.pumpSts = False self.pumpStsLED.off() #else: # Pump is already off; Do nothing def log(self, msg, level = "INFO"): # Probably prefix MSG with timestamp? # Add logging facilities later ts = time.gmtime() ts = time.strftime("%Y-%m-%d %H:%M:%S", ts) print(ts," - ",level,": ",msg) def manualRun(self): self.log("Manual override process running...") while True: if self.pumpBtn.value: self.pumpRun() else: self.pumpStop() # Cool this down a little sleep(0.5) def autoFill(self): self.log("Automatic filler process running...") while True: if self.WtrLevel.value <= 0.5 and self.pumpWtrLevel.value: self.pumpRun() else: self.pumpStop() # Cool this down a little sleep(0.5) def monitorWtrPump(self): self.log("Pump water level checker running...") lastState = not self.pumpWtrLevel.value stateCheck = True while True: state = self.pumpWtrLevel.value if lastState != state: lastState = state if state: self.log("Pump water present","INFO") if self.pumpSts: self.pumpStsLED.on() else: self.pumpStsLED.off() else: self.log("Low pump water level","WARNING") self.pumpStsLED.blink(0.5,0.5,None,True) # Cool this down a little sleep(0.5) def monitorTreeWtr(self): self.log("Tree water level monitor running...") self.wtrLevel = LEDBarGraph(self.GPIO_led_R1, self.GPIO_led_Y1, self.GPIO_led_G1, pwm=True) level = 0 lastLevel = -1 while True: # This is terrible, horrible, very bad code! if self.treeWtrLevel13.value: level = 13 elif self.treeWtrLevel12.value: level = 12 elif self.treeWtrLevel11.value: level = 11 elif self.treeWtrLevel10.value: level = 10 elif self.treeWtrLevel09.value: level = 9 elif self.treeWtrLevel08.value: level = 8 elif self.treeWtrLevel07.value: level = 7 elif self.treeWtrLevel06.value: level = 6 elif self.treeWtrLevel05.value: level = 5 elif self.treeWtrLevel04.value: level = 4 elif self.treeWtrLevel03.value: level = 3 elif self.treeWtrLevel02.value: level = 2 elif self.treeWtrLevel01.value: level = 1 else: level = 0 if lastLevel != level: self.log("Tree water level now at level " + str(level), "INFO") lastLevel = level level = level / 13 self.wtrLevel.value = level sleep(1)
def main(): now = datetime.now() my_path = os.path.abspath(os.path.dirname(__file__)) log_file_path_abs = os.path.join( my_path, "{}/{}_{}.log".format(log_file_path, log_file_name, now.strftime("%Y-%m-%d_%H-%M-%S"))) csv_file_path_abs = os.path.join( my_path, "{}/{}_{}.csv".format(log_file_path, csv_file_name, now.strftime("%Y-%m-%d_%H-%M-%S"))) print_and_log("Starting...", log_file_path_abs) csv_file = open(csv_file_path_abs, "w+") csv_file.write("Time;Level;Pump\n") csv_file.close() pump = LED(PUMP_PIN_NO, active_high=False) #pump_off(pump, log_file) status_led = LED(STATUS_LED_PIN_NO) # CFG stuff - TODO: quick and dirty for testing, needs to be replaced cfg_file_threshold_path_abs = os.path.join(my_path, "threshold.cfg") # TODO: Read Thingspeak URL and Key from config file # Main Loop while True: try: level = read_tank_level(log_file_path_abs) threshold = read_threshold_from_file(cfg_file_threshold_path_abs, log_file_path_abs) print_and_log("Using threshold value of: {}".format(threshold), log_file_path_abs) # Turn off pump if necessary pumpState = 0 if level * 100 < threshold: #pump_off(pump, log_file) pump.off() pumpState = 0 else: #pump_on(pump, log_file) pump.on() pumpState = 1 print_and_log( "Current state: Level: {}% | Pump: {}".format( level * 100, pump_state_textual(pumpState)), log_file_path_abs) csv_file = open(csv_file_path_abs, "a") csv_file.write("{};{};{}\n".format( get_timestamp(), level, pumpState)) # TODO: Store level in Log csv_file.close() print_and_log("Sending data to Thingspeak...", log_file_path_abs) send_data_to_thingspeak(THINGSPEAKURL, THINGSPEAKKEY, level, pumpState, log_file_path_abs) sys.stdout.flush() status_led.blink( ) # Heartbeat TODO: check if this works as intended sleep(sleep_time) # Wait # except IOError as e: # print_and_log("File write error occurred: {}".format(e), log_file) except Exception as err: print_and_log("Error occurred! Exiting...", log_file_path_abs) raise err # Terminate Program print_and_log("Terminating...", log_file_path_abs) try: csv_file.close() log_file.close() except: print("Unable to close file stream.") finally: print("Done.")
from gpiozero import LED from TwitterAPI import TwitterAPI from oauth import * import time # set up 2 pins for LEDs yLed = LED(20) rLed = LED(21) #### specify hashtags to follow # can be separated by comma: '#jesus,#pizza,#selfie' TRACK_TERM = '#jesus' # set up the TwitterAPI object api = TwitterAPI(CONSUMER_KEY,CONSUMER_SECRET, ACCESS_TOKEN_KEY,ACCESS_TOKEN_SECRET) # print a welcome message print "Connected to Twitter. Searching for: %s"%TRACK_TERM # this is the responseobject from twitter. # it gets updated everytime a new tweet comes in with the TRACK_TERMs response = api.request('statuses/filter', {'track': TRACK_TERM}) # this goes through the tweets availalble in the response object for tweet in response: # prints out their text and blinks the lights print(tweet['text'] if 'text' in tweet else '') rLed.blink(on_time=1, n=1) yLed.blink(on_time=1, n=1)
def _forward(self): self.motorLeft.forward() self.motorRight.forward() def _backward(self): self.motorLeft.backward() self.motorRight.backward() def _left(self): self.motorLeft.backward() self.motorRight.forward() def _right(self): self.motorLeft.forward() self.motorRight.backward() def _stop(self): self.motorLeft.stop() self.motorRight.stop() motionController = MotionController(motorLeft, motorRight) communicator = Communicator(motionController) while True: statusLed.blink(0.5, 0.5) communicator.connect() statusLed.on() communicator.listen() communicator.cleanup()
from gpiozero import LED red = LED(22) amber = LED(27) green = LED(17) red.blink(0.5,0.1) amber.blink(0.25,0.1) green.blink(0.125,0.1)
led_white = LED(17) led_blue = LED(5) led_white.on() led_blue.on() switch_to_robot_network() try: response = dweepy.get_latest_dweet_for('misty') old_status = str(response[0]["created"]) print("START:", old_status) except: dweepy.dweet_for('misty', {'status': 'script_start'}) time.sleep(2) led_blue.blink(0.1) led_white.blink(0.1) while True: try: time.sleep(1.5) response = dweepy.get_latest_dweet_for('misty') new_status = str(response[0]["created"]) print("NOW: ", new_status) if new_status != old_status: old_status = new_status print("Trigger Alarm") print("Preparing Image") prepare_image() print("Connecting to printer network") x = switch_to_printer_network()
from gpiozero import LED led = LED(17) led.blink(n=1)
# Seteo de los pines ok_led = LED(ok_led_pin) warn_led = LED(warn_led_pin) error_led = LED(error_led_pin) monitor_led = LED(monitor_led_pin) # Configuramos la antena Xbee # Comando para escanear puertos {dmesg | grep tty} # se accede a traves de RS232 masterport xbee = ZigBeeDevice("/dev/ttyAMA0", 9600) remote_xbee = RemoteZigBeeDevice( xbee, XBee64BitAddress.from_hex_string("0013A20041513615")) print("Empezamos") for x in range(5): ok_led.blink(1, 1, 5) warn_led.blink(1, 1, 5) error_led.blink(1, 1, 5) monitor_led.blink(1, 1, 5) print(servo.value) servo.min() print(servo.value) sleep(5) servo.mid() sleep(5) servo.max() sleep(5) print(x) print("e voila")
f.write("\n") line = "" while True: data = self.gp.bb_i2c_zip(27,[4,0x42,2,6,1,3,0])[1][0] char = chr(data) if data ==255: pass elif char == "$": self.processline(line) line = "$" else: line += char sleep(0.1) if __name__ == '__main__': gps = GPS() ok = LED(26) while True: sleep(30) print(gps.gpsData) if gps.sat > 4: print("fix") ok.blink() else: print("no fix") ok.off()
os.system("/bin/bash /opt/RetroFlag/killes.sh") os.system("omxplayer -o hdmi /opt/RetroFlag/tone.mp3") print("Shutting down...") os.system("shutdown -h now") break else: led.on() #Take control of LED instead of relying on TX pin #RESET Button pressed #When Reset button is presed restart current game if rebootBtn.is_pressed: retroPiCmd("RESET") #RESET Button held #When Reset button is held for more then 3 sec quit current game if rebootBtn.is_held: led.blink(.2, .2) retroPiCmd("QUIT") #Fan control #Adjust MIN and MAX TEMP as needed to keep the FAN from kicking #on and off with only a one second loop cpuTemp = int(float(getCPUtemp())) fanOnTemp = 55 #Turn on fan when exceeded fanOffTemp = 40 #Turn off fan when under if cpuTemp >= fanOnTemp: fan.on() if cpuTemp < fanOffTemp: fan.off() time.sleep(1.00)
i7 = Button(io.I7, pull_up=False) i8 = Button(io.I8, pull_up=False) i9 = Button(io.I9, pull_up=False) i10 = Button(io.I10, pull_up=False) i11 = Button(io.I11, pull_up=False) i12 = Button(io.I12, pull_up=False) col = PiIO_col() motor_timer = PiIO_TON(0, 2) # 2s timer run_timer = PiIO_timer() # run timer enable = LED(io.OE) run = LED(io.RUN) count = 0 servo_setp = 0 motor_enable = False run.blink(.100, .900) # run LED # mqt message handler # def on_mqt_message(client, userdata, message): global servo_setp, motor_enable if 'motor' in message.topic: motor_enable = (message.payload.decode('utf-8').lower() == 'true') if motor_enable: run_timer.reset() print("on") if 'servo' in message.topic: servo_setp = float(message.payload.decode('utf-8'))
class PiShutdownButton: """PiShutdownButton.""" def __init__(self, gpio_btn, gpio_led, btn_hold_time=1, reset_time=2, shutdown_mode_time=4): """Initialize a PiShutdownButton object.""" self.btn = Button(gpio_btn, hold_time=btn_hold_time, hold_repeat=True) self.btn.when_held = self.btn_hold self.btn.when_pressed = self.btn_press self.btn.when_released = self.btn_release self.led = LED(gpio_led) self.led.on() self.shutdown_mode_time = shutdown_mode_time self.shutdown_mode = False # Shutdown mode is active self.shutdown_timer = False # Shutdown timer is active self.shutdown_triggered = False # Shutdown is in progress self.reset_time = reset_time self.reset_timer = None def reset(self): """Reset application state.""" logging.debug('Resetting application state.') self.shutdown_mode = False self.shutdown_timer = False self.shutdown_triggered = False self.led.on() def btn_hold(self, button): """Handle button hold.""" logging.debug('Button is being held.') if not self.shutdown_mode: pressed_time = int(button.pressed_time) # 4 second threshold - 1 second hold delay if (pressed_time > self.shutdown_mode_time - 1) and not self.shutdown_mode: logging.debug("Entering shutdown mode.") self.led.blink(on_time=0.1, off_time=0.1) self.shutdown_mode = True def btn_press(self): """Handle button press.""" logging.debug('Button is pressed.') if not self.shutdown_mode: self.led.blink(on_time=0.5, off_time=0.5) def btn_release(self): """Handle button release.""" logging.debug('Button is released.') if not self.shutdown_mode: logging.debug('Turning LED on.') # Not in the shutdown mode, turn the LED on self.led.on() elif not self.shutdown_timer: # Shutdown mode is active, start the reset timer logging.debug('Starting shutdown timer.') self.shutdown_timer = True self.reset_timer = Timer(self.reset_time, self.reset) self.reset_timer.start() elif not self.shutdown_triggered: # Shutdown timer is active, initiate shutdown logging.debug('Shutting down system.') self.shutdown_triggered = True self.reset_timer.cancel() self.led.off() os.system('sudo poweroff')
#!/usr/bin/env python #Reaction game recipe from gpiozero import Button, LED from time import sleep import random led1 = LED(27) led2 = LED(23) player_1 = Button(22) player_2 = Button(24) led2.blink(on_time=1, off_time=1, n=10, background=True) time = random.uniform(5, 10) sleep(time) led1.on() while True: if player_1.is_pressed: print("Player 1 wins!") break if player_2.is_pressed: print("Player 2 wins!") break led1.off()
from gpiozero import LED from time import sleep from controller import robot_controller import os robot = robot_controller(os.path.dirname(os.path.realpath(__file__))) for pin in robot.get_config()['Robot']: re = LED(pin) echo = LED(robot.get_config()['distance_sensor']['echo']) echo.off() trigger = LED(robot.get_config()['distance_sensor']['trigger']) trigger.off() signal_led = LED(robot.get_config()['distance_sensor']['signal_led']) signal_led.blink() sleep(1)
def main(): now = datetime.now() my_path = os.path.abspath(os.path.dirname(__file__)) log_file_path_abs = os.path.join( my_path, "{}/{}{}.log".format(log_file_path, log_file_name, now.strftime("%Y-%m-%d_%H-%M-%S"))) csv_file_path_abs = os.path.join( my_path, "{}/{}{}.csv".format(log_file_path, csv_file_name, now.strftime("%Y-%m-%d_%H-%M-%S"))) print_and_log("Starting...", log_file_path_abs) write_to_csv("Time;Level;Pump", csv_file_path_abs, log_file_path_abs) try: # Set stack size limit to maximum possible resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY)) print_and_log("Successfully increased stack size to maximum.", log_file_path_abs) except Exception as e: print_and_log( "Unable to increase stack size. Reason: {}. Continuing...".format( e), log_file_path_abs) # Create devices using GPIOZERO library try: pump = LED(PUMP_PIN_NO, active_high=False) #pump_off(pump, log_file) status_led = LED(STATUS_LED_PIN_NO) seed_voltage = LED(SEED_VOLTAGE_PIN_NO) lvl_pin_cnt = len(list(LVL_PIN_NO_ARRAY)) lvl_pin_array = [LED] * lvl_pin_cnt for x in range(lvl_pin_cnt): #print_and_log("Checking pin no. {}: GPIO {}".format(x, lvlPinNoArray[x]), log_file_path_abs) lvl_pin_array[x] = Button(LVL_PIN_NO_ARRAY[x], pull_up=False) print_and_log( "Done initializing GPIO devices. Using {} level pins.".format( lvl_pin_cnt), log_file_path_abs) except Exception as e: print_and_log("Unable to create devices: {}. Exiting...".format(e), log_file_path_abs) return 1 # CFG stuff - TODO: quick and dirty for testing, needs to be replaced cfg_file_threshold_path_abs = os.path.join(my_path, "threshold.cfg") # Manual pump ctl through file TODO: Replace manctl_filepath = os.path.join(my_path, "manual_pump_control.cfg") # Initialize pump state variable - pump is always off if not actively pulled LOW by program pump_running = False # TODO: Read Thingspeak URL and Key from config file # Heartbeat TODO: check if this works as intended (when program crashes...) status_led.blink() # Switch to manual mode for testing TODO: Remove switch_mode(ControlMode.MANUAL) # Main Loop while True: try: # Read Level level = read_tank_level(lvl_pin_array, seed_voltage, log_file_path_abs) # Read Threshold from File threshold = read_threshold_from_file(cfg_file_threshold_path_abs, log_file_path_abs) print_and_log("Using threshold value of: {}".format(threshold), log_file_path_abs) # Control pump pump_allowed = is_pump_allowed(level, pump_running, threshold) pump_desired = is_pump_desired(manctl_filepath, log_file_path_abs) if pump_allowed & pump_desired: pump_running = pump_turn_on(pump, log_file_path_abs) else: pump_running = pump_turn_off(pump, log_file_path_abs) # Log Data print_and_log( "Current state: Level: {}% | Pump: [ALLOWED: {}, DESIRED: {}, RUNNING: {}]" .format(level * 100, pump_allowed, pump_desired, pump_state_textual(pump_running)), log_file_path_abs) write_to_csv( "{};{};{}\n".format(get_timestamp(), level, int(pump_running)), csv_file_path_abs, log_file_path_abs) # Send Data to Thingspeak print_and_log("Sending data to Thingspeak...", log_file_path_abs) send_data_to_thingspeak(THINGSPEAKURL, THINGSPEAKKEY, level * 100, int(pump_running), log_file_path_abs) sys.stdout.flush() # Wait until next check is due print_and_log( "Waiting {} seconds until next check...".format(sleep_time), log_file_path_abs) sleep(sleep_time) except Exception as err: print_and_log("An unknown error occurred! Exiting...", log_file_path_abs) print_and_log(traceback.format_exc(), log_file_path_abs) raise err # Terminate Program print_and_log("Terminating...", log_file_path_abs) print("Done.") return 0
# Ejecutar como root con sudo from gpiozero import Button, LED from subprocess import check_call from signal import pause # Boton de apagado; debe mantenerse pulsado 3 segundos shutdown_btn = Button(3, hold_time=3) # LED opcional para saber que todo va bien led = LED(21) # Funcion que se ejecuta cuando pulsamos el boton def shutdown(): # Parpadear el LED mas rapido mientras se esta apagando led.blink(on_time=0.1, off_time=0.1) check_call(['sudo', 'poweroff']) # Parpadear el LED opcional para saber que # todo esta funcionando bien led.blink(on_time=0.5, off_time=0.5) # Asignar la funcion shutdown al mantener el boton pulsado shutdown_btn.when_held = shutdown # Mantener el programa pausado pause()
if tempdiff >= highdiff: red = True reason = 0 elif tempdiff <= lowdiff: red = False #LED and notification controls filewrite(updated.month, updated.day, updated.hour, updated.minute, inside, outside, attic, window, outsidehigh, red, reason) if red == True: greenled.off() if window == 1: if notified == False: notify(reason) notified = True redled.blink(0.75, 0.75) elif window == 2: if (reason == 0) or (reason == 3): if notified == False: notify(reason) notified = True redled.blink(0.75, 0.75) else: redled.on() else: redled.on() else: redled.off() greenled.on() notified = False
if config.post_online: show_image(real_path + "/finished.png") else: show_image(real_path + "/finished2.png") time.sleep(restart_delay) show_image(real_path + "/intro.png"); led_pin.on() #turn on the LED #################### ### Main Program ### #################### ## clear the previously stored pics based on config settings if config.clear_on_startup: clear_pics(1) print("Photo booth app running...") led_pin.blink() show_image(real_path + "/intro.png"); led_pin.on(); #turn on the light showing users they can push the button input(pygame.event.get()) # press escape to exit pygame. Then press ctrl-c to exit python. #GPIO.wait_for_edge(btn_pin, GPIO.FALLING) time.sleep(config.debounce) #debounce btn_pin.when_pressed = start_photobooth pause()
from gpiozero import LED from signal import pause myLed = LED(17) myLed.blink(.5) pause()
ledRed = LED(17) ledGreen = LED(27) # NFS Server Check print('Checking for NFS Server...') pingResponse = os.system("ping -c 1 " + nfsServer) ledRed.on() if pingResponse == 0: print('{} {}'.format(nfsServer, 'is up!')) mntCmd = 'mount {}:{} {}'.format(nfsServer, nfsDrive, nfsMnt) mntResponse = os.system(mntCmd) if mntResponse == 0: print('{} {}'.format(nfsServer, 'has been mounted!')) print('Transferring backups to external storage...') ledRed.blink() copy_tree(tmpDir, nfsMnt, verbose=1) if os.getenv('CLEANUP') == 'true': rmCmd = 'rm -rf {}/*'.format(tmpDir) os.system(rmCmd) print('done') else: print('{} {}'.format('Cannot mount', nfsServer)) ledGreen.blink() ledRed.blink() time.sleep(10) else: print('{} {}'.format(nfsServer, 'is not available!')) ledGreen.blink() ledRed.blink() time.sleep(5)
from gpiozero import LED from signal import pause red = LED(17) red.blink() pause()
#!/usr/bin/python from gpiozero import LED from signal import pause import time yellow = LED(26) yellow.blink() pause()
#!/home/pi/Documents/python/blink.py from gpiozero import LED from signal import pause red = LED(25) red.blink(0.2) pause()
while True: config = yaml.load( file('/home/pi/Desktop/python3/smartfridge/config.yml', 'r')) frequencySecs = int(config["frequencysecs"]) fridgeThreshold = getFridgeTempThreshold() tempFridge = getTemperature(temp_fridge_sensor) tempExternal = getTemperature(temp_external_sensor) led.on() print("Threshold: " + str(fridgeThreshold)) print("Fridge temp: " + str(tempFridge)) print("External temp: " + str(tempExternal)) if tempFridge == ERROR_TEMP: led.blink(0.1, 0.5) relay.off() #off for a NC relay = on print("error with fridge temp sensor fridge on") logData(fridgeThreshold, str(tempFridge), str(tempExternal), "error with fridge temp sensor fridge on") elif tempFridge > fridgeThreshold: relay.off() #off for a NC relay = on print("fridge on") logData(fridgeThreshold, str(tempFridge), str(tempExternal), "on") else: relay.on() #on for a NC relay = off print("fridge off") logData(fridgeThreshold, str(tempFridge), str(tempExternal), "off") sleep(frequencySecs)
# This is an alternative for blinking an LED # Instead of calling ON/OFF with a delay, # this program generated the blinking on/off cycle # with just a single function call # Blinking interval is hard-coded to 1 second # in the library. That is 1 sec on, 1 sec off from gpiozero import LED from signal import pause green=LED(17) green.blink() pause()
from gpiozero import LED from signal import pause power = LED(35) # /sys/class/leds/led1 activity = LED(47) # /sys/class/leds/led0 activity.blink() power.blink() pause()
#!/usr/bin/python3 # testzero.py # # Example using GPIOZero with GPIO.BOARD numbering # PiStop in Location C (BOARD pins 8,10,12) # # Note: 1. gpiopins.py must be located in python path or same directory. # 2. /usr/lib/python3/dist-packages/gpiozero/devices.py should be updated as shown in devices.py file. import gpiopins as GPIO GPIO.setmode(GPIO.BOARD) from gpiozero import LED from time import sleep green=LED(8) yellow=LED(10) red=LED(12) green.blink() sleep(0.1) yellow.blink() sleep(0.1) red.blink()