コード例 #1
0
ファイル: ledstrip.py プロジェクト: Jrois/PiHome
    def __init__(self, r, g, b, ww, cw):
        # set up pwm pins
        factory = PiGPIOFactory()
        self.red = PWMLED(r, pin_factory=factory)
        self.green = PWMLED(g, pin_factory=factory)
        self.blue = PWMLED(b, pin_factory=factory)
        self.warm = PWMLED(ww, pin_factory=factory)
        self.cool = PWMLED(cw, pin_factory=factory)

        # initialize state vector
        self.i = 5
        self.states = [0, 0, 0, 0, 0, 0]
        self.states[self.i] = 1

        self.on = False

        # pwm value
        self.val = 0.5
def ledWithVaryingBrightness(gpio="GPIO26"):\
    # PWM (pulse-width-modulation)
	led = PWMLED(gpio)
	led.value = 0.5  # half brightness
	sleep(1)
	led.value = 1  # full brightness
	sleep(1)
	led.value = 0  # off
	sleep(1)
コード例 #3
0
def initialize_mfc():

    mfc_pin1 = 5
    mfc_pin2 = 6
    mfc_pin3 = 13

    # Although these are not LEDs,
    # PWMLED is the easiest pwm implementation
    # in gpiozero and will be used for mfcs
    mfc1 = PWMLED(mfc_pin1)
    mfc2 = PWMLED(mfc_pin2)
    mfc3 = PWMLED(mfc_pin3)

    mfc1.value = 0.0
    mfc2.value = 0.0
    mfc3.value = 0.0

    return mfc1, mfc2, mfc3
コード例 #4
0
    def __init__(self):
        """
        instantiate objects
        this process will establish communication links
        if fail then raise an exception that will terminate the program
        """

        # dictionary of flight parameters
        self.parameters = {"descent_vel": 0.25, "logging_interval": 0.1}

        # Pulse the green LED constantly while script is running
        self.green_led = PWMLED(22)
        self.green_led.pulse(fade_in_time=0.5, fade_out_time=0.5)

        # Flash the red LED if an error occurs
        self.red_led = LED(17)

        # If the button is held for 3 seconds then end the script
        self.button = Button(26)
        self.button.hold_time = 3
        self.button.when_held = self.__prepare_exit

        self.gcs = GroundControlStation()
        if self.gcs.initSuccessful:
            self.report("Link to GCS established")
        else:
            # if fail to open link to GCS no means of reporting so enter specific sequence
            self.alert_initialisation_failure()
            raise ValueError(
                "Failed to communicate with Ground Control Station")

        self.fc = FlightController()
        if self.fc.initSuccessful:
            self.report("Link to FC established")
        else:
            self.report("Link to FC failed")
            raise ValueError("Failed to communicate with Flight Controller")

        self.uC = MicroController()
        if self.uC.initSuccessful:
            self.report("Link to uC established")
        else:
            self.report("Link to uC failed")
            raise ValueError("Failed to communicate with Micro Controller")

        self.logger = DataLogging()
        self.vision = LandingVision()
        self.scheduler = RecurringTimer(self.parameters["logging_interval"],
                                        self.__monitor_flight)

        # Setting up class attributes
        self.abortFlag = None
        self.emergency_land = False
        self.state = "Initial"
        self.received_mission = None
        self.mission_title = "Default mission name"
        self.reporting_count = 0
コード例 #5
0
def button_3():
    while True:
        if BUTTON3.value == 1 and LED1.value == 0:
            turn_led_on()
            PWMLED(12, True, 0.50, 100)     # De functie heb ik nog niet werkende gekregen spijtig genoeg.
            time.sleep(0.25)
        if BUTTON3.value == 1 and LED1.value == 1:
            turn_led_off()
            time.sleep(0.25)
コード例 #6
0
class CustomSliderWidget(BoxLayout):
    Value_Slider_One = '0'
    Value_Slider_Two = '0'
    Value_Slider_Three = '0'
    slider_min = NumericProperty(0)
    slider_max = NumericProperty(1)
    fontsize = NumericProperty(50)
    sliderheight = StringProperty('40dp')

    try:
        led_red = PWMLED(17)  #17
        led_green = PWMLED(22)  #22
        led_blue = PWMLED(27)  #27
        print("successfully declared PWM LEDs")

    except NameError:
        pass

    def setvalue_one(self, *args):
        self.textboxone.text = str(float(format(args[1], '.5f')))

        value_output = float(args[1])
        try:
            self.led_red.value = value_output
            print('Changed the value of the Red LED')
        except AttributeError:
            print('Value change not succesful ', value_output)

    def setvalue_two(self, *args):
        self.textboxtwo.text = str(float(format(args[1], '.5f')))
        try:
            self.led_green.value = float(args[1])
            print('Changed the value of the Green LED')
        except AttributeError:
            pass

    def setvalue_three(self, *args):
        self.textboxthree.text = str(float(format(args[1], '.5f')))
        try:
            self.led_blue.value = float(args[1])
            print('Changed the value of the Blue LED')
        except AttributeError:
            pass
コード例 #7
0
 def __init__(self, gpio_pin, state=None):
     print("LED_INIT")
     self._led = PWMLED(pin=gpio_pin, frequency=100)
     self._led.value = 0
     self._brightness_queue = Queue(0)
     self._brightness_thread = None
     self._max_brightness = 0.7
     self._doc = None
     if (state):
         self.set_state(state)
コード例 #8
0
def main():
    fan = PWMLED(18)
    while True:
        vcgm = Vcgencmd()
        temp = vcgm.measure_temp()
        if temp >= 40:
            fan.on()
        elif temp <= 35:
            fan.off()
        time.sleep(1)
コード例 #9
0
ファイル: indicators.py プロジェクト: drano02/callattendant
 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
コード例 #10
0
ファイル: lib.py プロジェクト: Hackthings/LTD_SmartHome
def getLEDs(pins):
    leds = {}

    for pin in pins:
        try:
            leds[pin] = PWMLED(pin)
        except:
            pass

    return leds
コード例 #11
0
 def pwm(self, pin_number: int, value: float) -> bool:
     if (
         pin_number in self.pins and
         self.pins[pin_number]['mode'] in [None, self.MODE_OUT]
     ):
         self.pins[pin_number]['mode'] = self.MODE_OUT
         if self.pins[pin_number]['obj'] is None:
             self.pins[pin_number]['obj'] = PWMLED(pin_number, pin_factory=self.remote_gpio)
         self.pins[pin_number]['obj'].value = value
         return True
     return False
コード例 #12
0
    def _setupBtnLedPins(self):
        """Sets up the board's lcd & led based on my breadboard's pin configuration"""
        #------------------------------------------ Buttons & LED ------------------------------------------#
        self.__leds = {
            "red": PWMLED(6),
            "yellow": PWMLED(13),
            "green": PWMLED(19),
            "blue": PWMLED(26)
        }
        self.__btns = {
            "red": Button(12),
            "yellow": Button(16),
            "green": Button(20),
            "blue": Button(21)
        }

        #------------------------------------------ Btn-LED Pairs ------------------------------------------#
        createPairs = lambda name: (
            name, ButtonLedPair(self.getLedObj(name), self.getBtnObj(name)))
        self.btnLedPairs = dict(map(createPairs, list(self.getLedNames())))
コード例 #13
0
 def init_fan(self, pin, frequency, speed):
     try:
         self.deinit_fan()
         self.fan = PWMLED(pin=pin,
                           initial_value=speed,
                           frequency=frequency,
                           pin_factory=self.pin_factory)
         self._logger.info("PWM pin initialized with pin factory: " +
                           str(self.fan.pin_factory))
     except:
         self._logger.error("Error occurred while initializing PWM pin")
コード例 #14
0
ファイル: IntegraLED.py プロジェクト: nemanjamil/smartWall
 def __init__(self, channel, levels=1000, linear=False):
     self.factory = PiGPIOFactory()
     self.led = PWMLED(channel, pin_factory=self.factory)
     self.led.off()
     self.led.frequency = 150
     self.state = self.LEDState.off
     self.levels = levels
     self.interval = 1.0 / levels
     self.level = 0.0
     self.lock = Lock()
     self.linear = linear
コード例 #15
0
ファイル: zisc_proj.py プロジェクト: yaron-sys/zisc_proj
def ledPWMStart(pinNum, sleepTimeSec):
    """
	ledpwm.value = 0  # off
	ledpwm.value = 0.5  # half brightness
	ledpwm.value = 1  # full brightness 
	"""
    ledpwm = PWMLED(pinNum)
    pwmVal = [x * 0.1 for x in range(0, 10)]
    while True:
        for val in pwmVal:
            ledpwm.value = val
            sleep(sleepTimeSec / 2)
コード例 #16
0
    def __init__(self, pin_gpio, name="GPIO"):
        """
        Constructor del objeto LED

        Args:
            pin_gpio (int): pin GPIO donde va a estar conectado el dispositivo.
            name (str, optional): Nombre con el que se mostrará el dispositivo en los diferentes servicios implementados. Defaults to "GPIO".
        """
        self.GPIO = PWMLED(pin_gpio)
        self.name = name if name != "GPIO" else "GPIO " + str(pin_gpio)
        self.set_blink = False
        self.sensors = []
コード例 #17
0
def main():
	# Set r, g and b as global variables and define them
	# I had to define them here because of a weird quirk in the Daemonize library, this was a headache
	global r
	global g
	global b
	r = PWMLED(os.getenv('GPIO_RED'))
	g = PWMLED(os.getenv('GPIO_GREEN'))
	b = PWMLED(os.getenv('GPIO_BLUE'))
	
	# Define UDP socket and bind to it
	sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	sock.bind((address, port))

	# Create variable which is checked by threads to see if they should stop
	global stopthread

	# Continue listening for input
	while True:
		data, addr = sock.recvfrom(1024)
		instructions = data.decode('ascii').split(",")
		print(instructions)

		if 'cthread' in locals():
			stopthread = True
			cthread.join()
		if instructions[0] == 'single':
			set(instructions[-1])
		if instructions[0] == 'strobe':
			stopthread = False
			cthread = Thread(target=strobe, args=(instructions,))
			cthread.start()
		if instructions[0] == 'fade':
			stopthread = False
			cthread = Thread(target=fade, args=(instructions,))
			cthread.start()
		if instructions[0] == 'breathe':
			stopthread = False
			cthread = Thread(target=breathe, args=(instructions,))
			cthread.start()
コード例 #18
0
def main():
    
    # now just write the code you would use in a real Raspberry Pi
    
    from Adafruit_CharLCD import Adafruit_CharLCD
    from gpiozero import Buzzer, LED, PWMLED, Button, DistanceSensor, LightSensor, MotionSensor
    from lirc import init, nextcode
    from py_irsend.irsend import send_once
    from time import sleep
    
    def show_sensor_values():
        lcd.clear()
        lcd.message(
            "Distance: %.2fm\nLight: %d%%" % (distance_sensor.distance, light_sensor.value * 100)
        )
        
    def send_infrared():
        send_once("TV", ["KEY_4", "KEY_2", "KEY_OK"])
    
    lcd = Adafruit_CharLCD(2, 3, 4, 5, 6, 7, 16, 2)
    buzzer = Buzzer(16)
    led1 = LED(21)
    led2 = LED(22)
    led3 = LED(23)
    led4 = LED(24)
    led5 = PWMLED(25)
    led5.pulse()
    button1 = Button(11)
    button2 = Button(12)
    button3 = Button(13)
    button4 = Button(14)
    button1.when_pressed = led1.toggle
    button2.when_pressed = buzzer.on
    button2.when_released = buzzer.off
    button3.when_pressed = show_sensor_values
    button4.when_pressed = send_infrared
    distance_sensor = DistanceSensor(trigger=17, echo=18)
    light_sensor = LightSensor(8)
    motion_sensor = MotionSensor(27)
    motion_sensor.when_motion = led2.on
    motion_sensor.when_no_motion = led2.off
    
    init("default")
    
    while True:
        code = nextcode()
        if code != []:
            key = code[0]
            lcd.clear()
            lcd.message(key + "\nwas pressed!")
            
        sleep(0.2)
コード例 #19
0
def ledWithVaryingBrightness(gpio=""):
    from gpiozero import PWMLED
    from time import sleep
    led = PWMLED(gpio)

    time = 5
    while time > 0:
        led.value = 0  # off
        sleep(1)
        led.value = 0.5  # half brightness
        sleep(1)
        led.value = 1  # full brightness
        sleep(1)
コード例 #20
0
ファイル: train.py プロジェクト: MrBunsy/WiFiPiTrain
    def __init__(self, config):
        '''

        :param motorPin0:
        :param motorPin1:
        :param real:
        :param deadZone: speeds too low to attempt to move motor
        :param frontWhite:
        :param frontRed:
        :param rearRed:
        :param readWhite:
        '''
        self.motor = None
        self.frontWhiteLight = None
        self.frontRedLight = None
        self.rearWhiteLight = None
        self.rearRedLight = None
        self.redBrightness = config["redBrightness"]
        self.whiteBrightness = config["whiteBrightness"]
        # really on a pi with a motor?
        self.real = config["real"]
        self.deadZone = config["deadZone"]
        # user-facing controls
        self.requestedSpeed = 0
        self.headlights = False
        self.reverse = False

        self.config = config

        if config["real"]:
            self.motor = Motor(config["motorPin0"], config["motorPin1"])
            if config["frontWhitePin"] is not None:
                self.frontWhiteLight = PWMLED(config["frontWhitePin"])
            if config["frontRedPin"] is not None:
                self.frontRedLight = PWMLED(config["frontRedPin"])
            if config["rearWhitePin"] is not None:
                self.rearWhiteLight = PWMLED(config["rearWhitePin"])
            if config["rearRedPin"] is not None:
                self.rearRedLight = PWMLED(config["rearRedPin"])
コード例 #21
0
 def __init__(self,
              green_leds=[6, 13, 19, 26],
              red_leds=[12, 16, 20, 21],
              indicator=22):
     # Init leds
     # self.green_leds = LEDBarGraph(6, 13, 19, 26, pwm=True)
     self.green_leds = LEDBarGraph(*green_leds, pwm=True)
     # self.red_leds = LEDBarGraph(12, 16, 20, 21, pwm=True)
     self.red_leds = LEDBarGraph(*red_leds, pwm=True)
     self.indicator = PWMLED(indicator)
     self.vote_getter = VoteGetter()
     self.curr_votes = Votes(100, 1)
     self.leds_from_votes(self.curr_votes)
コード例 #22
0
def getLEDs(pins):
	leds = {}
	
	for pin in pins:
		try:
			leds[pin] = {
				'LED': PWMLED(pin),
				'Overwrite': False
			}
		except:
			pass
		
	return leds
コード例 #23
0
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()
コード例 #24
0
	def __init__(self, pin_rs=7, pin_e=8, pins_db=[25, 24, 23, 18]):
		self.pin_rs=pin_rs
		self.pin_e=pin_e
		self.pins_db=pins_db
		self.contrast = PWMLED(15,frequency=25)
		self.contrast.on()
		self.contrast.value=.55
		self.Contrastbutton = Button(14)
		self.Contrastbutton.when_pressed = self.ContrastPressed
		
		self.brightness = PWMLED(20,frequency=60)
		self.brightness.on()
		self.brightness.value=.95
		self.Brightnessbutton = Button(21)	
		self.Brightnessbutton.when_pressed = self.BrightnessPressed

		GPIO.setmode(GPIO.BCM)
		GPIO.setup(self.pin_e, GPIO.OUT)
		GPIO.setup(self.pin_rs, GPIO.OUT)
		for pin in self.pins_db:
			GPIO.setup(pin, GPIO.OUT)
		self.clear()
コード例 #25
0
 def __init__(self, baseClock):
   self.baseClock = baseClock
   self.r = LedThread(PWMLED("GPIO5"), baseClock)
   self.g = LedThread(PWMLED("GPIO12"), baseClock)
   self.b = LedThread(PWMLED("GPIO16"), baseClock)
   self.r2 = LedThread(PWMLED("GPIO20", False), baseClock)
   self.g2 = LedThread(PWMLED("GPIO18", False), baseClock)
   self.b2 = LedThread(PWMLED("GPIO22", False), baseClock)
コード例 #26
0
ファイル: hal.py プロジェクト: jpunkt/pizzabox-mc
    def __init__(self):
        self.btn_forward = Button(gpio_pins.BTN_FORWARD_GPIO)
        self.btn_back = Button(gpio_pins.BTN_BACK_GPIO)

        self.led_btn_fwd = PWMLED(gpio_pins.LED_FWD_BTN)
        self.led_btn_back = PWMLED(gpio_pins.LED_BACK_BTN)

        # self.lid_sensor = Button(gpio_pins.LID_SWITCH)

        self.ud_sensor = ScrollSensor(*gpio_pins.SCROLL_UPDOWN_SENSORS,
                                      gpio_pins.SCROLL_UPDOWN_ENDSTOP)
        self.lr_sensor = ScrollSensor(*gpio_pins.SCROLL_LR_SENSORS,
                                      gpio_pins.SCROLL_LR_ENDSTOP)

        self.motor_lr = Motor(*gpio_pins.MOTOR_CTRL_LR)
        self.motor_ud = Motor(*gpio_pins.MOTOR_CTRL_UPDOWN)
        self.led_layer = PWMOutputDevice(gpio_pins.LED_LAYER)
        self.led_backlight = PWMOutputDevice(gpio_pins.LED_BACKLIGHT)

        self.camera = None
        self.soundcache = {}

        self.blocked = False
コード例 #27
0
ファイル: handle_gpio.py プロジェクト: Diftraku/cortana2
def main():
    # setup
    # See https://www.raspberrypi.org/documentation/usage/gpio/
    # Pins are on the edge of the connector, right next to each-other
    # Indicator should connect the positive side (anode, yellow wire) to GPIO pin 23
    # and negative side (cathode, orange wire) to ground
    # Button should connect 3V3 (blue wire) to GPIO pin 24 (green wire)
    away_indicator = PWMLED(pin=18, active_high=False, initial_value=False)
    home_indicator = LED(pin=23, active_high=False, initial_value=False)
    button = Button(pin=17, pull_up=False)
    button.when_held = handle_button
    button.hold_time = 0.5

    # Setup logging
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(handler)

    # This is used to communicate the state relatively "thread-safely"
    # to the Sopel bot
    presence_file = Path(PRESENCE_FILE)

    # Prime the state from file, defaults to False if file does not exist
    last_state = state = read_state(presence_file)

    logger.info('Starting main loop')

    while True:
        # Update the state from file
        state = read_state(presence_file)

        # Check if state changed
        if state != last_state:
            # Set LED based on the state
            if state:
                home_indicator.on()
                away_indicator.off()
            else:
                home_indicator.off()
                away_indicator.pulse(fade_in_time=1, fade_out_time=3)
            logger.info('Toggling LED state: %s', 'on' if state else 'off')
            last_state = state

        # Sleep before next round
        sleep(0.5)
コード例 #28
0
class Air:
    relays = PiGPIOFactory(host='192.168.1.20')  #RELAY PINS
    air_pin = PWMLED(18, pin_factory=relays)

    def __init__(self):
        self.data = []

    def blow(self, time):
        relays = self.relays
        air_pin = self.air_pin
        air_pin.value = 1
        print("blow")
        print(time)
        sleep(time)
        air_pin.value = 0
コード例 #29
0
 def _rebuild_pwmled(self):
     old_value = 0.
     if self._pwmled is not None:
         if not self._active or self._bcm_pin is None:
             _log.info('Disabling PWM led.')
         else:
             old_value = self._pwmled.value
         self._pwmled.off()
         self._pwmled = None
     if self._bcm_pin is not None and self._active:
         _log.info('Rebuilding PWM led on pin %d with frequency %d.',
                   self._bcm_pin, self._frequency)
         self._pwmled = PWMLED(self.bcm_pin,
                               frequency=self.frequency,
                               initial_value=old_value)
コード例 #30
0
def main():
    try:  
        led = PWMLED(14)
        log.info("Reading from GPIO pin: %s" % (led.pin))
        while True:
            brighten(led)
            dim(led)
    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