class SoundButton:

       def __init__(self, id, button_pin, led_pin, sound_file):
               self.id = id
               self.button_pin = button_pin
               self.led_pin = led_pin
               self.sound_file = sound_file
               self.sound = Sound(sound_file)

               self.button = Button(button_pin)
               self.led = LED(led_pin)
               self.led.off()

               print(self.button_pin)
               
               self.button.when_pressed = self.pressed

       def pressed(self):
               print("pressed")
               pygame.mixer.music.load(self.sound_file)
               pygame.mixer.music.play()
	       soundButtons [current_sound_button_object].turn_off_led()
               self.led.on()
	       current_sound_button_object = self.id
	       
       def turn_off_led(self):
               self.led.off()
コード例 #2
0
ファイル: paddle.py プロジェクト: rbtdev/pi-game
class Paddle:
	def __init__(self, paddleId, buttonPressCb):
		self.id = paddleId
		self.button = Button(pins[paddleId]['buttonPin'])
		self.led = LED(pins[paddleId]['ledPin'])
		self.led.off()
		self.pressedAt = None
		self.buttonPressCb = buttonPressCb

	def enable(self):
		self.button.when_pressed = self.handleButtonPress
		print ("Paddle enabled")
	
	def disable(self):
		self.button.when_pressed = None
		print ("Paddle disabled")
	
	def handleButtonPress(self):
		self.pressedAt = datetime.now()
		self.buttonPressCb(self)

	def on(self):
		self.led.on()

	def off(self):
		self.led.off()

	def pressed(self):
		return self.button.is_pressed
コード例 #3
0
def blink_led():
	led = LED(4)
	print "LED IS ON !!"
	led.on()
	sleep(5)
	print "LED IS OFF !!"
	led.off()
class LED_CONTROL:
    def __init__(self, parent="none", label="LED", gpio_pin = 23):
        self.led = LED(gpio_pin)
        self.label=label
        self.ledLabel = tk.Label(master=parent,text = self.label)
        self.ledLabel.pack()#grid(row = 0, column = 0)
##        self.ser=
                        
        self.ledOnButt = tk.Button(master=parent,text = "ON", fg = "green", command = self.ledOn)
        self.ledOnButt.pack(fill="x")
        
        self.ledOffButt = tk.Button(master=parent,text = "OFF", fg = "RED", command = self.ledOff)
        self.ledOffButt.pack(fill="x")        
##
##        self.ledZapTime = tk.Entry(master=parent,width=10)
##        self.ledZapTime.insert(0,"zap in ms")
##        self.ledZapTime.pack(fill="x")
##        
##        self.ledZapButt = tk.Button(master=parent,text = "ZAP!", command = self.ledZap)
##        self.ledZapButt.pack(fill="x")        
 
    #callbacks for LED
    def ledOn(self):
        self.led.on()
        
    def ledOff(self):
        self.led.off()
コード例 #5
0
class stepperMotor:
	
	def __init__(self,enable, direction, step):
		self.enablePin = LED(enable)
		self.directionPin = LED(direction)
		self.stepPin = LED(step)
		self.stepLocation = 0

		self.enablePin.on() #Logic high disables motor
		self.directionPin.on() #Default direction is forward
		self.stepPin.off()

	def rotate(self, steps, pause):
		with open('motorStepLocation','r') as motorLocation:
			for line in motorLocation:
				self.stepLocation = int(line.split(None, 1)[0])
		motorLocation.close()

		print self.stepLocation
		self.stepPin.off()
		self.enablePin.off() #Logic low enables motor
		if (steps > 0):
			self.directionPin.on() #Choose forward direction
			tmpForward = 1
		else:
			self.directionPin.off() #Choose reverse direction
			tmpForward = -1

		for iStep in range (0, abs(steps)):
			self.stepPin.on()
			sleep(pause)
			self.stepPin.off()
			sleep(pause)
			self.stepLocation = self.stepLocation + tmpForward

		self.enablePin.on() #Logic high disables motor
		print self.stepLocation
		subprocess.check_output("mv motorStepLocation motorStepLocation.old", shell = True)
		subprocess.check_output("echo %i >> motorStepLocation" %self.stepLocation, shell = True)
	
	def gotToOrigin(self):
		with open('motorStepLocation','r') as motorLocation:
                        for line in motorLocation:
                                self.stepLocation = int(line.split(None, 1)[0])
                motorLocation.close()

		self.rotate(-self.stepLocation, 0.01)

	def getPosition(self):
                with open('motorStepLocation','r') as motorLocation:
                        for line in motorLocation:
                                self.stepLocation = int(line.split(None, 1)[0])
                motorLocation.close()

                print self.stepLocation
		return self.stepLocation
コード例 #6
0
ファイル: light_switch.py プロジェクト: ukBaz/python-bluezero
class board:
    def __init__(self, ble):
        self.led = LED(22)
        self.button = Button(25)
        self.ble = ble

    def switch_led(self, *args, **kwargs):
        print(self.led.is_lit, args, kwargs)
        if self.led.is_lit:
            self.led.off()
            self.ble.light.Set(constants.GATT_CHRC_IFACE, "Value", [0x00])
        else:
            self.led.on()
            self.ble.light.Set(constants.GATT_CHRC_IFACE, "Value", [0x01])
コード例 #7
0
ファイル: RelayControl.py プロジェクト: jeremydorr/Safe3D
class RelayCtl:
   'Class to control the relay'
   
   def __init__(self, pin, defaultmode):
      self.pin = pin
      self.relay=LED(pin)
      if(defaultmode == "on"):
         self.relay.on()
      if (defaultmode == "off"):
         self.relay.off()
   def relayOn(self):
      self.relay.on()
   def relayOff(self):
      self.relay.off()
コード例 #8
0
ファイル: loadmanager.py プロジェクト: CiSC87/equanimous
 def initialize(self):
     self.log=LoggerFactory.get_file_logger(config.log_filename,"LoadManagerThread",config.log_level)
     self.log.info("Initializing")
     load1=LED(config.load_1_pin)
     load2=LED(config.load_2_pin)
     load1.on()
     load2.on()
     time.sleep(1)
     load1.off()
     load2.off()
     time.sleep(1)
     load1.on()
     load2.on()
     self.log.info("Successfully initialized")
コード例 #9
0
class SoundButton:

       def __init__(self, id, button_pin, led_pin, sound_file):
               self.id = id
               self.button_pin = button_pin
               self.led_pin = led_pin
               self.sound_file = sound_file
               self.sound = Sound(sound_file)

               self.button = Button(button_pin)
               self.led = LED(led_pin)
               self.led.off()

               print(self.button_pin)
               
               self.button.when_pressed = self.pressed

       def pressed(self):
               #print("pressed")
               self.led.on()
               time.sleep(5)
               pygame.mixer.music.load(self.sound_file)
               pygame.mixer.music.play()
               self.led.off()
	       
       def turn_off_led(self):
               self.led.off()
コード例 #10
0
ファイル: pi.py プロジェクト: denniskline/garage-door
class Light:

    def __init__(self):
        self._ledGreen = LED(22)
        self._ledYellow = LED(27)
        self._ledRed = LED(17)
        pass

    def green_light_on(self):
        logging.debug("green light on")
        try:
            self._ledGreen.on()
        except:
            logging.warn("Unable to turn on green light", exc_info=True)

    def yellow_light_on(self):
        logging.debug("yellow light on")
        try:
            self._ledYellow.on()
        except:
            logging.warn("Unable to turn on yellow light", exc_info=True)

    def red_light_on(self):
        logging.debug("red light on")
        try:
            self._ledRed.on()
        except:
            logging.warn("Unable to turn on red light", exc_info=True)

    def green_light_off(self):
        logging.debug("Turning green light off")
        try:
            self._ledGreen.off()
        except:
            logging.warn("Unable to turn off green light", exc_info=True)

    def yellow_light_off(self):
        logging.debug("Turning yellow light off")
        try:
            self._ledYellow.off()
        except:
            logging.warn("Unable to turn off yellow light", exc_info=True)

    def red_light_off(self):
        logging.debug("Turning red light off")
        try:
            self._ledRed.off()
        except:
            logging.warn("Unable to turn off red light", exc_info=True)

    def is_green_light_on(self):
        return self._ledGreen.is_lit()
        
    def is_yellow_light_on(self):
        return self._ledYellow.is_lit()
        
    def is_red_light_on(self):
        return self._ledRed.is_lit()
コード例 #11
0
ファイル: trafficscene.py プロジェクト: Yakindu/examples
class TrafficLightCar:

	def __init__(self):
		self.led_r = LED(15)
		self.led_y = LED(18)
		self.led_g = LED(24)

	def set_red(self, bool):
		if bool:
			self.led_r.on()
		else:
			self.led_r.off()

	def set_yellow(self, bool):
		if bool:
			self.led_y.on()
		else:
			self.led_y.off()

	def set_green(self, bool):
		if bool:
			self.led_g.on()
		else:
			self.led_g.off()
コード例 #12
0
ファイル: trafficscene.py プロジェクト: Yakindu/examples
class TrafficLightPed:

	def __init__(self):
		self.led_r = LED(12)
		self.led_g = LED(21)
		self.led_req = LED(16)
		self.btn_req = Button(19)
		self.btn_req.when_pressed = self.req_btn_pressed
		self.pressed = False

	def set_red(self, bool):
		if bool:
			self.led_r.on()
		else:
			self.led_r.off()

	def set_green(self, bool):
		if bool:
			self.led_g.on()
		else:
			self.led_g.off()

	def set_request(self, bool):
		if bool:
			self.led_req.on()
		else:
			self.led_req.off()

	def req_btn_pressed(self):
		self.pressed = True

	def is_req_btn_pressed(self):
		return self.pressed

	def clear_events(self):
		self.pressed = False
コード例 #13
0
from gpiozero import LightSensor, LED
from time import sleep

light = LightSensor(4, charge_time_limit=0.001)
buzzer = LED(26)

buzzer.off()
sleep(1)

light.wait_for_dark()
buzzer.on()
コード例 #14
0
ファイル: pyTOTIS.py プロジェクト: zmp26/pyTOTIS
        tl[len(tl)-1].set_date(str(datetime.datetime.today()).split()[0])
<<<<<<< HEAD
        logging.info("List was changed on: " + str(datetime.datetime.today()))
=======
>>>>>>> 00dd912383c0cc5a2f0b93f7b03bf31b7a6f62de
        sleep(2)

    #update toners.txt below
    pyTOTIS_update_toners("toners.txt", tl, str(datetime.datetime.today()).split(".")[0])


    pyTOTIS_main_menu()


#main program control
pyTOTIS_startup()
while True:
    blue_led.on()

    if deliver_btn.is_pressed: #begin toner input process
        #next two lines for debugging purposes -> uncomment/comment as necessary
        #print("deliver button pressed")
        blue_led.off()
        pyTOTIS_toner_deliver(tonerlist)

    if deploy_btn.is_pressed: #begin toner deploy process
        #next two lines for debugging purposes -> uncomment/comment as necessary
        #print("deploy button pressed")
        blue_led.off()
        pyTOTIS_toner_deploy(tonerlist)
コード例 #15
0
ファイル: warholizer.py プロジェクト: mhoole71/warholizer
effects = ['negative', 'solarize', 'sketch', 'emboss', 'oilpaint', 'hatch', 'pastel','watercolor', 'film', 'cartoon']


while True:
     if btn.is_pressed:
          os.chdir("/home/pi/warholizer")
          image_directory = "warhol" + str(dir_num)
          os.mkdir(image_directory)
          os.chdir(image_directory)
          camera.start_preview(alpha = 192)
          for i in range(5):
               red_led.on()
               green_led.on()
               buzzer.on()
               sleep(0.5)
               red_led.off()
               green_led.off()
               buzzer.off()
               sleep(0.5)
          for j in range (4):
               camera.image_effect = effects[randint(0,len(effects)-1)]
               
               camera.capture('image%d.jpg' %j)
               print("Picture captured number", j)
               sleep(1)
          camera.stop_preview()
          image_args = ["gm", "montage",  "-geometry", "512x384+2+2", "-bordercolor", "red", "+tile", "image0.jpg", "image1.jpg", "image2.jpg", "image3.jpg", "warhol.jpg"]

          subprocess.check_call(image_args)
          
          print ("Warhol image created")
コード例 #16
0
from gpiozero import LED
from time import sleep
import signal
import sys

# print('halo')

pinEnable = LED(13)
pinDir = LED(19)
pinPulse = LED(21)

pinEnable.off()
pinDir.on()

def signal_handler(sig, frame):
    print('You pressed Ctrl+C!')
    pinEnable.on()
    pinDir.off()
    sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)

for x in range(6*x)::
    pinPulse.on()
    print('hehe')
    sleep(1/1000)
    pinPulse.off()
    print('haha')
    sleep(1/1000)
コード例 #17
0
def end_race(lane,seconds):
    logging.info(lane + " Won!")
    logging.info(seconds/100.0)
    LED.off()
    return False
コード例 #18
0
class HardwareInterface:
    def __init__(self):
        self.mqtt_client = None
        self.maps_leds_pulse = None

        self.btn_run = Button(10, bounce_time=0.1)
        self.btn_map1 = Button(17, bounce_time=0.1, hold_time=5)
        self.btn_map2 = Button(27, bounce_time=0.1, hold_time=5)
        self.btn_map3 = Button(22, bounce_time=0.1, hold_time=5)
        self.input_ipad = Button(25, bounce_time=2)
        self.output_pause = LED(18)
        self.output_powerswitch = LED(23)

        self.led_go = LED(4)

        self.map_leds = [LED(5), LED(9), LED(11)]

        self.direction_states = [
            (Button(19), Button(26)),
            (Button(6), Button(13)),
            (Button(20), Button(21)),
            (Button(12), Button(16)),
        ]

        self.directions = ["N", "E", "S", "W"]
        self.sleeping = True
        self.map_choice = False
        self.pause_input = True
        self.device_switch = False

        self.mqtt_pub_topic_direction = "directions"
        self.mqtt_pub_topic_map = "map"

    def add_client(self, client):
        self.client = client

    def set_map(self, chosen_map):
        self.map_choice = int(chosen_map)
        # self.maps_leds_pulse = False
        # sleep(2)

        self.send_msg(self.mqtt_pub_topic_map, chosen_map, qos=1)
        # Turn on hw-controller
        self.output_powerswitch.on()
        print("map chosen")

    def pause(self):
        self.pause_input = True
        self.output_pause.on()
        self.led_go.off()
        sleep(0.1)
        print("pause hardware input")

    def resume(self):
        self.pause_input = False
        self.output_pause.off()
        self.led_go.on()
        sleep(0.1)
        print("resume hardware input")

    def sleep(self):
        self.send_msg(self.mqtt_pub_topic_map, "-1", qos=1)
        self.sleeping = True
        for led in self.map_leds:
            led.off()
        self.output_powerswitch.off()
        self.pause()
        # self.maps_leds_pulse = False
        # self.map_leds[self.map_choice-1].off()
        sleep(0.1)
        print("put to sleep")

    async def rotateMapLed(self):
        while not self.map_choice and not self.sleeping:
            for led in self.map_leds:
                led.toggle()
            await asyncio.sleep(1)

        for led in self.map_leds:
            led.off()
        if not self.sleeping:
            self.map_leds[self.map_choice - 1].on()

    def wake(self):
        self.sleeping = False
        self.map_choice = False
        # self.maps_leds_pulse = True
        asyncio.ensure_future(self.rotateMapLed())
        # for led in self.map_leds:
        #     led.on()
        #     sleep(0.5)
        #     led.off()
        #     sleep(0.5)
        # Wait for hardware boot
        sleep(0.1)
        # Send wake to gui
        self.send_msg(self.mqtt_pub_topic_map, "0", qos=1)
        print("waking")

    def send_directions(self):
        self.pause()
        data_out = []
        for direction in self.direction_states:
            try:
                if direction[0].is_active and direction[1].is_active:
                    data_out.append(self.directions[0])
                elif direction[0].is_active and not direction[1].is_active:
                    data_out.append(self.directions[1])
                elif not direction[0].is_active and not direction[1].is_active:
                    data_out.append(self.directions[2])
                elif not direction[0].is_active and direction[1].is_active:
                    data_out.append(self.directions[3])
            except Exception as e:
                data_out = False
                print(e)

        if data_out:
            data_out = ','.join(data_out)
            # data_out = json.dumps(data_out)
        else:
            data_out = 'error'

        print(self.mqtt_pub_topic_direction + ': ' + data_out)
        self.send_msg(self.mqtt_pub_topic_direction, data_out, qos=1)

    def send_msg(self, topic, msg, qos=1):
        try:
            self.client.publish(topic, msg, qos=qos)
        except Exception as e:
            print(e)

    def on_message_status(self, client, userdata, msg):
        msg.payload = msg.payload.decode()
        try:
            status = int(msg.payload)
        except Exception:
            print("not valid status message")
            status = None

        if status == 0:
            # Resume
            hardwareInterface.resume()
        elif status == 1:
            # Pause
            hardwareInterface.pause()
        elif status == 2:
            # Sleep / reset
            hardwareInterface.pause()

        print("Topic: ", msg.topic + "\nMessage: " + msg.payload)
コード例 #19
0
ファイル: lights2.py プロジェクト: amos1969/geocraft
from gpiozero import LED
from mcpi.minecraft import Minecraft
from mcpi import block
red = LED(17)
amber = LED(27)
green = LED(9)
mc = Minecraft.create()

while True:
    pos = mc.player.getPos()
    blockType = mc.getBlockWithData(pos.x, pos.y-1, pos.z)
    if blockType.data == 14:
        red.on()
    else:
        red.off()
コード例 #20
0
ファイル: inproved game.py プロジェクト: nniuq1/dmastanford
from gpiozero import Button, LED
from time import sleep
import random
lb1 = LED(17)
lb1 = LED(22)
b1 = Button(4)
b2 = Button(21)

time = 0
for i in range(8):
    choise = random.randint(0, 6)
    if choise == 1:
        lb1.on()
        while b1.button.off():
            sleep(0.1)
            time += 0.1
        lb2()
    elif choise == 2:
        lb2.on()
        while b2.button.off():
            sleep(0.1)
            time += 0.1
        lb1.off()
    else:
        sleep(0.25)
    sleep(1)
コード例 #21
0
class IRReceiver():
    """
    IR Receiver

    Contains helpful functions for decoding IR signals from a physical IR
    Receiver.

    IR Receivers signal 1 by default when no IR signal is detected, and 0
    otherwise. So a HIGH pulse is 0, while a LOW pulse is 1.

    More information on the NEC Infrared Transmission Protocol can be found at:
    https://techdocs.altium.com/display/FPGA/NEC+Infrared+Transmission+Protocol
    """

    # minimum pulse length that counts as a read - arbitrary
    MIN_PULSE_READ = 50 * 0.000001  # sec

    # maximum pulse length that counts as a read - arbitrary
    MAX_PULSE_READ = 65000 * 0.000001  # sec

    def __init__(self):
        self.sensor = InputDevice(16)
        self.led = LED(26)

    def read_loop(self):
        """
        Continuously reads IR pulses and decodes them into NEC compliant
        messages.
        """
        log.info("Reading IR inputs")

        pulses: List[Pulse] = []

        def track_pulse(pulse):
            nonlocal pulses
            if pulse and \
               self.MIN_PULSE_READ < pulse.length < self.MAX_PULSE_READ:
                log.debug(pulse)
                pulses.append(pulse)
            elif len(pulses) > 0:
                message = None
                try:
                    message = self._pulses_to_binary_message(pulses)
                except ValueError as e:
                    log.error(e, exc_info=True)
                finally:
                    if message:
                        log.info(hex(message))
                pulses = []

        while 1:
            # empty space (registers as 1 on IR Receiver)
            space_pulse = self._sense_pulse(True)
            track_pulse(space_pulse)
            # burst pulse (registers as 0 on IR Receiver)
            burst_pulse = self._sense_pulse(False)
            track_pulse(burst_pulse)

    def _sense_pulse(self, is_space):
        """Listens for a pulse space or burst."""
        start = datetime.now()
        while self.sensor.is_active is is_space:
            # timed out, return nothing
            if (datetime.now() - start).total_seconds() >= self.MAX_PULSE_READ:
                return None
            self.led.off() if is_space else self.led.on()
        return Pulse((datetime.now() - start).total_seconds(), is_space)

    def _sanitize_pulses(self, pulses):
        """
        Confirms pulses received match expected pattern and removes preceding
        pulses not relevant to the message, i.e. [<arbitrary space>,
        9ms leading pulse burst, 4.5ms space], as well as trailing burst.
        """
        if pulses[0].is_space is not True:
            raise ValueError("Pulse patterns must begin with a space")
        if len(pulses) != 68:
            raise ValueError(f"Pulse patterns must be 68 pulses long (1 space "
                             f"+ 1 9ms burst + 1 4.5ms space + 64 message "
                             f"pulses + 1 trailing burst). Received: "
                             f"{len(pulses)}")
        for idx in range(0, len(pulses), 2):
            if not (pulses[idx].is_space is True
                    and pulses[idx + 1].is_space is False):
                raise ValueError(f"Pulse pattern does not alternate between "
                                 f"spaces and bursts beginning at index {idx}")

        # remove all pulses not relevant to encoded message
        pulses = pulses[3:-1]

        for idx in range(0, len(pulses), 2):  # bursts
            if not pulses[idx].is_small_gap():
                raise ValueError(f"Burst at index {idx} does not match NEC"
                                 f"specifications ({pulses[idx]})")
        for idx in range(1, len(pulses), 2):  # spaces
            if not (pulses[idx].is_small_gap() or pulses[idx].is_large_gap()):
                raise ValueError(f"Space at index {idx} does not match NEC "
                                 f"specifications ({pulses[idx]})")

        return pulses

    def _pulses_to_binary_message(self, pulses):
        """Converts sequence of pulses into NEC compliant binary message."""
        try:
            pulses = self._sanitize_pulses(pulses)
        except ValueError as e:
            log.error(e)
            return None

        msg_str = ""
        # use size of spaces to determine encoded message values
        for idx in range(1, len(pulses), 2):
            if pulses[idx].is_small_gap():
                msg_str += "0"
            elif pulses[idx].is_large_gap():
                msg_str += "1"
            else:
                raise ValueError(f"Pulse pattern malformed")

        msg_bin = int(msg_str, 2)

        # validate address and command
        address = msg_bin & 0xFF000000 >> (6 * 4)
        address_inverse = msg_bin & 0x00FF0000 >> (4 * 4)
        command = msg_bin & 0x0000FF00 >> (2 * 4)
        command_inverse = msg_bin & 0x000000FF
        if command == ~command_inverse:
            raise ValueError(f"Address does not match inverse ({hex(address)} "
                             f"{hex(address_inverse)})")
        if command == ~command_inverse:
            raise ValueError(f"Command does not match inverse ({hex(command)} "
                             f"{hex(command_inverse)})")

        return msg_bin
コード例 #22
0
ファイル: led_remote_5.py プロジェクト: VHSVictor/GPIOZERO
from gpiozero import LED
from gpiozero.pins.pigpio import PiGPIOFactory
from time import sleep

factory3 = PiGPIOFactory(host='192.168.1.3')
factory4 = PiGPIOFactory(host='192.168.1.4')

led_1 = LED(17)  # local pin
led_2 = LED(17, pin_factory=factory3)  # remote pin on one pi
led_3 = LED(17, pin_factory=factory4)  # remote pin on another pi

while True:
    led_1.on()
    led_2.off()
    led_3.on()
    sleep(1)
    led_1.off()
    led_2.on()
    led_3.off()
    sleep(1)
コード例 #23
0
class CollectorPositioner:

    def __init__(self, pca9865_address=0x40, en_pin=None, tilt_servo_ch=None, rotation_servo_ch=None):
        if en_pin is not None:
            self.en_led = LED(en_pin)
            self.en_led.off()
        else:
            self.en_led = None

        try:
            self.expander = PCA9685(address=pca9865_address)
            self.expander.set_pwm_freq(60)
            if tilt_servo_ch is not None:
                self.tilt_servo = ServoController(
                    expander=self.expander,
                    channel=tilt_servo_ch,
                    min_angle=0,
                    max_angle=90,
                    min_pulse=140,
                    max_pulse=340
                )
                self.tilt_servo.set_angle(0)
            else:
                self.tilt_servo = None

            if rotation_servo_ch is not None:
                self.rotation_servo = ServoController(
                    expander=self.expander,
                    channel=rotation_servo_ch,
                    min_angle=0,
                    max_angle=180,
                    min_pulse=180,
                    max_pulse=660
                )
                self.rotation_servo.set_angle(0)
            else:
                self.rotation_servo = None
        except:
            self.expander = None
            self.tilt_servo = None
            self.rotation_servo = None
            print("Collector positioner could not initiated")

    def set_tilt_angle(self, angle):
        if self.tilt_servo is None:
            return False, 0
        else:
            return self.tilt_servo.set_angle(angle)

    def get_tilt_angle(self):
        if self.tilt_servo is None:
            return False, 0
        else:
            return True, self.tilt_servo.get_angle()

    def set_rotation_angle(self, angle):
        if self.rotation_servo is None:
            return False, 0
        else:
            return self.rotation_servo.set_angle(angle)

    def get_rotation_angle(self):
        if self.rotation_servo is None:
            return False, 0
        else:
            return True, self.rotation_servo.get_angle()

    def finish(self):
        if self.tilt_servo is not None:
            self.tilt_servo.set_angle(0)
        if self.rotation_servo is not None:
            self.rotation_servo.set_angle(0)
        if self.en_led is not None:
            self.en_led.on()
コード例 #24
0
        running = 1
        child = pexpect.spawn('./Printrun/pronsole.py')
        child.logfile = sys.stdout.buffer
        child.expect('offline>')
        child.sendline('help connect')
        child.expect('Available ports: ')
        child.expect('\r\n')
        printers = child.before.split()
        printerString = bytesToStrings(printers)

        for x in printerString:
            child.expect('offline>')
            printerTitle = x.split('/')[-0]
            child.sendline('connect ' + x)
            i = child.expect(
                ['Printer is now online\r\n', 'Could not connect'])
            if i == 0:
                levelBed(printerTitle, child)
            else:
                print('Could not connect to printer')

        child.sendline('exit')
        running = 0
        red.off()


button.when_pressed = autoLevel
red.off()
green.on()

pause()
コード例 #25
0
ファイル: Plant.py プロジェクト: steveb93/Pi_Water-Irrigation
            temperature, humidity))
        print(DHT_Read)

        dictionary = {
            "eon": {
                "Temperature": temperature,
                "Humidity": humidity
            }
        }
        pubnub.publish().channel('ch2').message([DHT_Read
                                                 ]). async (publish_callback)
        pubnub.publish().channel("eon-chart").message(dictionary). async (
            publish_callback)

        wet = get_status()

        if wet == True:
            print("turning on")
            pump.off()
            sleep(5)
            print("pump turning off")
            pump.on()
            sleep(1)
        else:
            pump.on()

        sleep(1)
    elif flag == 0:
        pump.on()
        sleep(3)
コード例 #26
0
class Thermostat:
  
    def __init__(self, gtkWindow):
	self.TemperatureSetPoint = 20
	self.ActualTemperature = 25
	self.Power = False
	self.ManualPower = gtkWindow.wg.ThermostatManualPower_checkbutton.get_active()
	self.StatusCode = 0
	self.WaterIsLow = False
	self.StatusMessage = 'System OK'
	self.RefillPump = LED(20)
	self.RefillPumpTimeON = 5
	self.RefillPumpPumping = False
	
	#Make sure refill pump is OFF on startup
	self.RefillPumpOFF()
	
	#Create timer to update system
	GObject.timeout_add_seconds(10, self.ThermostatUpdate)
	
	#Create serial port communication
	self.SerialPort = serial.Serial(port='/dev/ttyUSB0', baudrate = 19200, timeout = 2)
	self.SerialPort.isOpen()
	self.ThermostatUpdate()
	
    def __del__(self):
	self.SerialPort.close()
	print 'Serial port closed'
	
    def SetTemperature(self, newSetPoint):
	self.SerialPort.write('SS ' + str(newSetPoint) + '\r')
	time.sleep(0.1)
	print self.SerialPort.readline()
	self.ThermostatUpdate()
	
    def PowerON(self):
	if (self.Power):
	    self.SerialPort.write('SO 1\r')
	else:
	    self.SerialPort.write('SO 0\r')
	    
	self.SerialPort.readline()
	
    def RefillPumpON(self):
	#Pin signal is inverted in external circuit
	self.RefillPump.off()
	self.RefillPumpPumping = True
	
    def RefillPumpOFF(self):
	self.RefillPump.on()
	self.RefillPumpPumping = False
	
    def ThermostatClearFault(self):
	self.SerialPort.write('SUFS\r')
	time.sleep(0.1)
	tmpRes = self.SerialPort.readline()
	
    def ThermostatUpdate(self):
	#Get Unit On status
	self.SerialPort.write('RO\r')
	time.sleep(0.04)
	tmpRes = self.SerialPort.read(2)
	self.Power = bool(tmpRes == '1\r')
	
	#Get actual temperature
	self.SerialPort.write('RT\r')
	time.sleep(0.04)
	self.ActualTemperature = self.SerialPort.readline()
	
	#Get set point from thermostat
	self.SerialPort.write('RS\r')
	time.sleep(0.04)
	self.TemperatureSetPoint = self.SerialPort.readline()

	#Get fault status
	self.SerialPort.write('RUFS\r')
	time.sleep(0.04)
	self.StatusCode = self.SerialPort.readline()
	self.FaultStatusMessageUpdate()
	return True
      
    def FaultStatusMessageUpdate(self):
	tmpCodes = [int(i) for i in self.StatusCode.split()]
	tmpBinaryV3 = list(bin(tmpCodes[2]))
	tmpBinaryV3 = [0] * (8-len(tmpBinaryV3)+2) + map(int,tmpBinaryV3[2:])
	if (self.WaterIsLow):
	    print("Water is low")
	if (tmpBinaryV3[7]):
	    self.StatusMessage = 'Code ' + ''.join(str(e) for e in tmpBinaryV3) + ' - Low Level Warning'
	    self.WaterIsLow = True
	   
	if (tmpBinaryV3[4]):
	    self.StatusMessage = 'Code ' + ''.join(str(e) for e in tmpBinaryV3) + ' - Low Level Fault'
	    self.WaterIsLow = True
	    
	if (not(tmpBinaryV3[7]) and not(tmpBinaryV3[4])):
	    self.StatusMessage = 'Code ' + ''.join(str(e) for e in tmpBinaryV3) + ' - OK'
	    if (self.WaterIsLow):
		print("Thermostat cleared fault")
from gpiozero import LED
from time import sleep
red = LED(25)
amber = LED(8)
green = LED(7)
green.on()
amber.off()
red.off()

while True:
    sleep(10)
    green.off()
    amber.on()
    sleep(1)
    amber.off()
    red.on()
    sleep(10)
    amber.on()
    sleep(1)
    green.on()
    amber.off()
    red.off()
コード例 #28
0
import socket
import json
import time
from gpiozero import RGBLED, LED

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.bind(("", 37020))
led = RGBLED(16, 20, 21, active_high=True, pwm=True)

BOI_PIN = LED(14)

print("Client started")
prev_data = None
while True:
    data, addr = client.recvfrom(1024)
    data = json.loads(data.decode('utf-8'))
    # led.color = (1,1,0)
    if prev_data is None or prev_data != data:
        led.color = (data['red']/255, data['green']/255, data['blue']/255)
        if data["boi"] == str(True):
            BOI_PIN.on()
        else:
            BOI_PIN.off()
        # print(data)
        prev_data = data
    #server_time = float(data['time'])
    #print("Latency:", time.time() - server_time)
コード例 #29
0
#setup robot, blue dot, LED, and the two button variables
devastator_bluedot = BlueDot()
devastator_robot = CamJamKitRobot()
devastator_eye = LED(25)
record_button = Button(13)
stop_button = Button(21)

#Setup the camera Variables
devastator_camera = PiCamera()
devastator_camera.resolution = (1280, 720)
devastator_camera.framerate = 25
moment = datetime.now()

#Blink the LED 4 times to ensure the code runs correctly
for x in range(1, 5):
    devastator_eye.off()
    sleep(0.5)
    devastator_eye.on()
    sleep(0.5)

#Define the move function and the individual commands
def move(pos):
    if pos.top:
        devastator_robot.forward()
    elif pos.bottom:
        devastator_robot.backward()
    elif pos.left:
        devastator_robot.left()
    elif pos.right:
        devastator_robot.right()
    elif pos.middle:
コード例 #30
0
        led10.off()
    return

led1 = LED(4)
led2 = LED(5)
led3 = LED(6)
led4 = LED(12)
led5 = LED(13)
led6 = LED(16)
led7 = LED(17)
led8 = LED(18)
led9 = LED(19)
led10 = LED(20)
buzzer = LED(27)

buzzer.off()
allLights("off")
sleep(1)
buzzer.on()
allLights("on")
sleep(1)
buzzer.off()
allLights("off")
sleep(1)
buzzer.on()
allLights("on")
sleep(1)
buzzer.off()
allLights("off")
sleep(2)
コード例 #31
0
ØVred.on()
sleep(1)
ØVgreen.on()
sleep(1)
ØVyel.on()
sleep(1)
NSred.on()
sleep(1)
NSgreen.on()
sleep(1)
NSyel.on()
sleep(1)
ØVred.off()
ØVgreen.off()
ØVyel.off()
NSred.off()
NSgreen.off()
NSyel.off()


def RedRed(x):  #Begge er røde
    global tid
    if x == "NS":
        x = "ØV"
        print("Red! NS")
        print("Red! ØV")
        NSred.on()
        ØVred.on()
        sleep(5)
        return NS(x)
    elif x == "ØV":
コード例 #32
0
class lettore_codice_a_barre(oggetto):
    def __init__(self, file_configurazione, coda_ipc_entrata, lock_ipc_entrata,
                 coda_ipc_uscita, lock_ipc_uscita):
        super().__init__(coda_ipc_entrata, lock_ipc_entrata, coda_ipc_uscita,
                         lock_ipc_uscita)
        logging.info(type(self).__name__ + " inizializzazione")
        configurazione = []
        lista_configurazione = []
        impostazioni = []

        self.attiva_terminatore = False
        self.attiva_limite_caratteri = False

        with open(file_configurazione) as f:
            configurazione = f.readlines()
        lista_configurazione[:] = [x.strip() for x in configurazione]
        # La lista delle impostazioni è una lista di liste, così da permettere
        # indici non unici
        for impostazione in lista_configurazione:
            nome, valore = impostazione.split(" ")
            impostazioni.append([nome, valore])

        with open(file_configurazione) as file_configurazione:
            for linea in file_configurazione:
                linea = linea.strip()
                opzione, valore = linea.split(" ")
                if opzione == "device":
                    self.device = evdev.InputDevice(valore)
                    self.device.grab()
                elif opzione == "pin_lettura":
                    self.leggi = LED(int(valore))
                    self.leggi.off()
                elif opzione == "terminatore":
                    self.attiva_terminatore = True
                    self.terminatore = valore
                elif opzione == "limite_caratteri":
                    self.attiva_limite_caratteri = True
                    self.limite_caratteri = int(valore)
                elif opzione == "richiesta_comando":
                    self.richiesta_comando = Button(int(valore))
        logging.info(type(self).__name__ + " inizializzato")

    def avvia(self):
        logging.info(type(self).__name__ + " avviato")
        with self.lock_segnali_uscita:
            if not self.coda_segnali_uscita.full():
                self.coda_segnali_uscita.put_nowait(["avviato", ""])
        ##### Variabili d'appoggio #####
        # Segnale così com'è scritto nella coda segnali
        pacchetto_segnale_entrata = []
        # Segnale come deve essere scritto nella coda segnale
        pacchetto_segnale_uscita = []
        segnale = ""
        mittente = ""
        destinatario = ""
        timestamp = 0

        comando = ""
        while True:
            ########################## Loop principale #########################
            ################# Ripristina variabili d'appoggio ##################
            pacchetto_segnale_entrata[:] = []
            comando = ""
            segnale = ""
            destinatario = ""
            mittente = ""
            timestamp = 0
            ############### Fine ripristino variabili d'appoggio ###############
            ########################## Ricevi segnale ##########################
            with self.lock_segnali_entrata:
                if not self.coda_segnali_entrata.empty():
                    pacchetto_segnale_entrata[:] = \
                                          self.coda_segnali_entrata.get_nowait()
            if len(pacchetto_segnale_entrata) == 4:
                logging.info(
                    str(type(self).__name__) + " messaggio diretto ricevuto")
                segnale,mittente,destinatario,timestamp = \
                                                       pacchetto_segnale_entrata
                pacchetto_segnale_entrata[:] = []
            elif len(pacchetto_segnale_entrata) == 3:
                logging.info(
                    str(type(self).__name__) + " messaggio broadcast ricevuto")
                segnale, mittente, timestamp = pacchetto_segnale_entrata
                pacchetto_segnale_entrata[:] = []
            elif len(pacchetto_segnale_entrata) == 0:
                pass
            else:
                with self.lock_segnali_uscita:
                    if not self.coda_segnali_uscita.full():
                        self.coda_segnali_uscita.put_nowait( \
                                                         ["segnale mal formato",
                                                          ""])
                pacchetto_segnale_entrata[:] = []
                sleep(ATTESA_CICLO_PRINCIPALE)
                continue
            pacchetto_segnale_entrata[:] = []
            if segnale != "":
                logging.info(
                    str(type(self).__name__) + " " + str(segnale) +
                    " ricevuto")
            ######################## Fine ricevi segnale #######################
            ############# Se segnale ricevuto, gestisci il segnale #############
            if segnale == "stop":  # Segnale ####################################
                with self.lock_segnali_uscita:
                    if not self.coda_segnali_uscita.full():
                        self.coda_segnali_uscita.put_nowait(
                            ["stop", "gestore_segnali"])
                return int(-1)
            elif segnale == "cassa presente":  # Segnale ########################
                with self.lock_segnali_uscita:
                    if not self.coda_segnali_uscita.full():
                        self.coda_segnali_uscita.put_nowait( \
                                                   ["pronto lettura codice",
                                                    "riconoscimento_cassa"])
                while True:
                    ################# Ripristina variabili d'appoggio ##########
                    pacchetto_segnale_entrata[:] = []
                    comando = ""
                    codice = ""
                    segnale = ""
                    destinatario = ""
                    mittente = ""
                    timestamp = 0
                    ############### Fine ripristino variabili d'appoggio #######
                    ########################## Ricevi segnale ##################
                    logging.info(
                        str(type(self).__name__) +
                        " in attesa di richiesta lettura codice")
                    with self.lock_segnali_entrata:
                        if not self.coda_segnali_entrata.empty():
                            pacchetto_segnale_entrata[:] = \
                                          self.coda_segnali_entrata.get_nowait()
                    if len(pacchetto_segnale_entrata) == 4:
                        segnale,mittente,destinatario,timestamp = \
                                                       pacchetto_segnale_entrata
                        pacchetto_segnale_entrata[:] = []
                    elif len(pacchetto_segnale_entrata) == 3:
                        segnale, mittente, timestamp = pacchetto_segnale_entrata
                        pacchetto_segnale_entrata[:] = []
                    elif len(pacchetto_segnale_entrata) == 0:
                        sleep(ATTESA_CICLO_PRINCIPALE)
                        continue
                    else:
                        with self.lock_segnali_uscita:
                            if not self.coda_segnali_uscita.full():
                                self.coda_segnali_uscita.put_nowait( \
                                                     ["segnale mal formato",""])
                        pacchetto_segnale_entrata[:] = []
                        sleep(ATTESA_CICLO_PRINCIPALE)
                        continue
                    ################## Gestisci il segnale #####################
                    logging.info(
                        str(type(self).__name__) + " " + str(segnale) +
                        " ricevuto")
                    if segnale == "leggi codice":
                        logging.info("Richiesta Lettura Codice")
                        while codice == "":
                            codice = self.leggi_codice_a_barre()
                        logging.info("Codice letto")
                        print(codice)
                        pacchetto_segnale_uscita[:] = [
                            str(codice), str(mittente)
                        ]
                        with self.lock_segnali_uscita:
                            if not self.coda_segnali_uscita.full():
                                self.coda_segnali_uscita.put_nowait( \
                                                   pacchetto_segnale_uscita)
                    elif segnale == "codice ricevuto":
                        logging.info(str(type(self).__name__) + " " + \
                                     segnale + \
                                     " ricevuto")
                        break
                    sleep(ATTESA_CICLO_PRINCIPALE)
            ####################### Fine Gestione segnale ######################
            ########### Leggi eventuale comando utente dallo scanner ###########
            if self.richiesta_comando.is_pressed:
                logging.info(
                    "In attesa del comando dal lettore codice a barre")
                comando_letto = self.leggi_codice_a_barre()
                logging.info(comando_letto)
                if comando_letto != "":
                    comando = comando_letto.lower()
                    if comando.find("aggiorna") == 0:
                        logging.info("Richiesta aggiornamento configurazione")
                        # Estrapola il nome dell'operazione da aggiornare
                        ignora, operazione = comando.split(" ")
                        print(comando)
                        # Richiedi la lista delle operazioni al Gestore Operazioni
                        pacchetto_segnale_uscita = [
                            "lista_operazioni", "gestore_pipeline"
                        ]
                        with self.lock_segnali_uscita:
                            if not self.coda_segnali_uscita.full():
                                self.coda_segnali_uscita.put_nowait( \
                                                       pacchetto_segnale_uscita)
                        lista_operazioni = []
                        while True:
                            pacchetto_segnale_entrata[:] = []
                            segnale = ""
                            mittente = ""
                            destinatario = ""
                            timestamp = 0
                            with self.lock_segnali_entrata:
                                if not self.coda_segnali_entrata.empty():
                                    pacchetto_segnale_entrata[:] = \
                                          self.coda_segnali_entrata.get_nowait()
                                    print(pacchetto_segnale_entrata)
                            if len(pacchetto_segnale_entrata) == 4:
                                segnale,mittente,destinatario,timestamp = \
                                                       pacchetto_segnale_entrata
                                pacchetto_segnale_entrata[:] = []
                            elif len(pacchetto_segnale_entrata) == 3:
                                segnale,mittente,destinatario,timestamp = \
                                                       pacchetto_segnale_entrata
                                pacchetto_segnale_entrata[:] = []
                            elif len(pacchetto_segnale_entrata) == 0:
                                pass
                            else:
                                with self.lock_segnali_uscita:
                                    if not self.coda_segnali_uscita.full():
                                        self.coda_segnali_uscita.put_nowait( \
                                                     ["segnale mal formato",""])
                                    sleep(0.001)
                                    if not self.coda_segnali_uscita.full():
                                        self.coda_segnali_uscita.put_nowait( \
                                                       pacchetto_segnale_uscita)
                                pacchetto_segnale_entrata[:] = []
                                sleep(ATTESA_CICLO_PRINCIPALE)
                                continue
                            # Se il mittente è il gestore pipeline e il destinatario
                            # è il Lettore Codice a barre, allora il segnale è la
                            # lista delle operazioni
                            if mittente == "gestore_pipeline" and \
                               destinatario == str(type(self).__name__):
                                lista_operazioni[:] = segnale.split(",")
                                # Se l'operazione richiesta per l'aggiornamento è
                                # tra le operazioni caricate nella pipeline,
                                # aggiorna; altrimenti segnala che l'operazione non
                                # è valida
                                if operazione in lista_operazioni:
                                    logging.info("Aggiornando " + operazione)
                                    segnale_aggiornamento = \
                                                    ["aggiorna",str(operazione)]
                                    with self.lock_segnali_uscita:
                                        if not self.coda_segnali_uscita.full():
                                            self.coda_segnali_uscita.put_nowait( \
                                                          segnale_aggiornamento)
                                    break
                                    while True:
                                        with self.lock_segnali_entrata:
                                            if not self.coda_segnali_entrata.empty(
                                            ):
                                                pacchetto_segnale_entrata[:] = \
                                          self.coda_segnali_entrata.get_nowait()
                                        if len(pacchetto_segnale_entrata) == 4:
                                            segnale,
                                            mittente,
                                            destinatario,
                                            timestamp = pacchetto_segnale_entrata
                                            pacchetto_segnale_entrata[:] = []
                                        elif len(pacchetto_segnale_entrata
                                                 ) == 3:
                                            segnale,
                                            mittente,
                                            destinatario = pacchetto_segnale_entrata
                                            pacchetto_segnale_entrata[:] = []
                                        elif len(pacchetto_segnale_entrata
                                                 ) == 0:
                                            pass
                                        else:
                                            with self.lock_segnali_uscita:
                                                if not self.coda_segnali_uscita.full(
                                                ):
                                                    self.coda_segnali_uscita.put_nowait(
                                                        [
                                                            "segnale mal formato",
                                                            ""
                                                        ])
                                            pacchetto_segnale_entrata[:] = []
                                            sleep(0.01)
                                            continue
                                        impostazione = self.leggi_codice_a_barre(
                                            0.1)
                                        if impostazione == "fine aggiornamento":
                                            with self.lock_segnali_uscita:
                                                if not self.coda_segnali_uscita.full(
                                                ):
                                                    self.coda_segnali_uscita.put_nowait(
                                                        [
                                                            str(impostazione),
                                                            str(mittente)
                                                        ])
                                            sleep(0.01)
                                            continue
                                        if segnale == "pronto":
                                            with self.lock_segnali_uscita:
                                                if not self.coda_segnali_uscita.full(
                                                ):
                                                    self.coda_segnali_uscita.put_nowait(
                                                        [
                                                            str(impostazione),
                                                            str(mittente)
                                                        ])
                                        elif segnale == "fine aggiornamento":
                                            with self.lock_segnali_uscita:
                                                if not self.coda_segnali_uscita.full(
                                                ):
                                                    self.coda_segnali_uscita.put_nowait(
                                                        ["ok",
                                                         str(mittente)])
                                            break
                                        sleep(0.01)
                                else:
                                    with self.lock_segnali_uscita:
                                        if not self.coda_segnali_uscita.full():
                                            self.coda_segnali_uscita.put_nowait( \
                                           ["L'operazione richiesta non è presente",
                                            str(mittente)])
                                        sleep(0.01)
                                        if not self.coda_segnali_uscita.full():
                                            self.coda_segnali_uscita.put_nowait( \
                                                              ["fine aggiornamento",
                                                               str(mittente)])
                                    break
                    elif comando == "stop":
                        with self.lock_segnali_uscita:
                            if not self.coda_segnali_uscita.full():
                                self.coda_segnali_uscita.put_nowait(
                                    ["stop", ""])
                        sleep(0.01)
                        with self.lock_segnali_uscita:
                            if not self.coda_segnali_uscita.full():
                                self.coda_segnali_uscita.put_nowait(
                                    ["stop", "gestore_segnali"])
                        return int(-1)
                    else:
                        logging.warn(comando + ": Comando non valido")
                    comando = ""
            sleep(ATTESA_CICLO_PRINCIPALE)
            ###################### Fine Loop Principale ########################
    def leggi_codice_a_barre(self, to=0):
        tempo_precedente = 0
        intervallo = 0
        codice = ""
        self.leggi.on()
        if to > 0:
            tempo_precedente = time()
        skip = 0
        ultimo_carattere = ''
        codice = ""
        codici_validi = {
            0: None,
            1: u'ESC',
            2: u'1',
            3: u'2',
            4: u'3',
            5: u'4',
            6: u'5',
            7: u'6',
            8: u'7',
            9: u'8',
            10: u'9',
            11: u'0',
            12: u'-',
            13: u'=',
            14: u'BKSP',
            15: u'TAB',
            16: u'Q',
            17: u'W',
            18: u'E',
            19: u'R',
            20: u'T',
            21: u'Y',
            22: u'U',
            23: u'I',
            24: u'O',
            25: u'P',
            26: u'[',
            27: u']',
            28: u'CRLF',
            29: u'LCTRL',
            30: u'A',
            31: u'S',
            32: u'D',
            33: u'F',
            34: u'G',
            35: u'H',
            36: u'J',
            37: u'K',
            38: u'L',
            39: u';',
            40: u'"',
            41: u'`',
            42: u'LSHFT',
            43: u'\\',
            44: u'Z',
            45: u'X',
            46: u'C',
            47: u'V',
            48: u'B',
            49: u'N',
            50: u'M',
            51: u',',
            52: u'.',
            53: u'/',
            54: u'RSHFT',
            56: u'LALT',
            57: u' ',
            100: u'RALT'
        }
        i = 0
        if to > 0:
            while True:
                event = self.device.read_one()
                if skip:
                    skip = 0
                    continue
                if event == None:
                    return ""
                elif event.type == evdev.ecodes.EV_KEY:
                    data = evdev.categorize(event)
                    if data.keystate == 1:
                        carattere = codici_validi.get(data.scancode) or u'NONE'
                        if carattere in codici_validi.values():
                            if carattere == 'LCTRL':
                                skip = 1
                                continue
                            codice += carattere
                            ultimo_carattere = carattere
                            i += 1
                if ultimo_carattere == str(self.terminatore):
                    codice = codice.replace("TAB", "")
                    codice = codice.replace("CTAB", "")
                    codice = codice.replace("ESC", "")
                    codice = codice.replace("BKSP", "")
                    codice = codice.replace("CRLF", "")
                    codice = codice.replace("LSHFT", "")
                    codice = codice.replace("RSHFT", "")
                    codice = codice.replace("LALT", "")
                    codice = codice.replace("RALT", "")
                    codice = codice.replace("/", "")
                    self.leggi.off()
                    return codice
                intervallo = time() - tempo_precedente
                if intervallo >= to:
                    self.leggi.off()
                    return ""
        else:
            for event in self.device.read_loop():
                if event.type == evdev.ecodes.EV_KEY:
                    data = evdev.categorize(event)
                    if data.keystate == 1:
                        carattere = codici_validi.get(data.scancode) or u'NONE'
                        if carattere in codici_validi.values():
                            if carattere == 'LCTRL':
                                skip = 1
                                continue
                            codice += carattere
                            ultimo_carattere = carattere
                            i += 1
                if (self.attiva_terminatore and \
                    ultimo_carattere == self.terminatore) \
                    or \
                    (self.attiva_limite_caratteri and \
                    i == (self.limite_caratteri)):
                    codice = codice.replace("TAB", "")
                    codice = codice.replace("CTAB", "")
                    codice = codice.replace("ESC", "")
                    codice = codice.replace("BKSP", "")
                    codice = codice.replace("CRLF", "")
                    codice = codice.replace("LSHFT", "")
                    codice = codice.replace("RSHFT", "")
                    codice = codice.replace("LALT", "")
                    codice = codice.replace("RALT", "")
                    codice = codice.replace("/", "")
                    self.leggi.off()
                    return codice
        self.leggi.off()
コード例 #33
0
            print(a, b, ratio)
            # turn on LEDs
            # red (port) LED is tack
            if tack > 0:
                #stbdLED.on()
                portLED.off()
            elif tack < 0:
                #stbdLED.off()
                portLED.on()

            # stbd (blue) LED is luff:
            if luff:
                luffLED.on()
            else:
                luffLED.off()

            writer.writerow([timestr, a, b, ratio, tack, luff])  # record data
            statLED.toggle()

            sleep(.25)
    f.close()


# run and record data as many times in a row as you need
while True:
    statLED.on()  # turn on LED to tell user it's ready
    portLED.off()  # turn off other LEDs while waiting
    #stbdLED.off() # not currently initialized
    luffLED.off()
    runtest()  # runs runtest() which waits for button press
def blinkingLED(gpio="GPIO18"):
    led = LED(gpio)
    led.on()
    sleep(0.5)
    led.off()
    sleep(0.5)
コード例 #35
0
def ledd():
    led = LED(17)
    led.off()
    led.on()
    sleep(.1)
    led.off()
コード例 #36
0
ファイル: traffic.py プロジェクト: PhilCleland/Traffic
from gpiozero import LED, Button, Buzzer
from time import sleep
from signal import pause
  
buzzer = Buzzer(2)  
button = Button(21)  
red = LED(17)
yellow = LED(11)
green = LED(26)


while True:            
            red.on()
            print("Stop")
            sleep(5)
            red.off()
            sleep(1)
            yellow.on()
            print("Get ready")
            sleep(3)
            yellow.off()
            sleep(1)
            green.on()
            print("Go go go")
            sleep(7)
            green.off()
            sleep(1)
            yellow.on()
            print("Get ready to stop")
            sleep(3)
            yellow.off()
コード例 #37
0
ファイル: relay_test.py プロジェクト: fentoncreeper/fishtank
from gpiozero import LED
from time import sleep

relay1 = LED(17)
relay2 = LED(18)


while True:
        relay1.on()
        relay2.off()
        sleep(1)
        relay1.off()
        relay2.on()
        sleep(1)

コード例 #38
0
ファイル: led2.py プロジェクト: uktechreviews/Pokedex
from gpiozero import LED
import time

red = LED(17)
green = LED(18)

while True:
	red.on()
	green.off()
	time.sleep(1)
	red.off()
	green.on()
	time.sleep(1)
コード例 #39
0
		print "exists"
	except :            
            print "db error"

        if results ==1:
                query2="INSERT INTO doorevents (cardid,doorid,detail) values ('%s','%s','%s')" % (b[0],b[1],'Auth')
                try:
                        print query2
                        cursor2.execute(query2)
                        db.commit()
                        print "door:",b[1]
                        if int(float(b[1]))==0 :
                                sleep(0.5)
                                door0.on()
                                sleep(3)
                                door0.off()
                                
                        if int(float(b[1]))==1 :
                                sleep(0.5)
                                door1.off()
                                sleep(1)
                                door1.on()
				sleep(1)

				
                        
                                        
                except :
                        print "db error 2"
                        db.rollback()
        else :
コード例 #40
0
btn = Button(17)  # button object

red = LED(26)  # red LED
amber = LED(19)  # amber LED
white = LED(13)  # white LED

state = 'red'  # Default State

print('Program Started')  # for testing

# will always run. Press [Ctrl] + C to interrupt app
while True:
    if (state is 'red'):
        red.on()
        amber.off()
        white.off()
        btn.wait_for_press()
        btn.wait_for_release()
        state = 'amber'
    elif (state is 'amber'):
        red.off()
        amber.blink(on_time=0.5, off_time=0.5)

        # take picture
        with PiCamera() as cam:
            cam.rotation = 90
            #cam.resolution = '640x480'
            cam.capture('/var/www/html/face.jpg', format='jpeg')
        print('pic taken1')
コード例 #41
0
#testing closing motion of gate

from gpiozero import LED
from time import sleep

motorPin = LED(18)
dirPin = LED(23)
#direction = 1
dirPin.on()

for i in range(0, 200):
	motorPin.on()
	sleep(0.005)
	motorPin.off()
	sleep(0.005)
コード例 #42
0
ファイル: motor_test.py プロジェクト: ARKopp/fabacademy2016
import explorerhat
from gpiozero import Button, LED, Motor
from time import sleep


button = Button(9)
led1 = LED(10)

motor1 = Motor(forward=19 , backward=20)
motor2 = Motor(forward=21 , backward=26)




while True:
        if button.is_pressed:
                print("Button pressed")
                led1.on()
                motor1.forward()
                motor2.forward()
        else:
        		print("Button is not pressed")
        		led1.off()
        		motor1.stop()
        		motor2.stop()
コード例 #43
0
ファイル: 2LogTemp.py プロジェクト: fdelia/raspberry-backup
    press = data[2].strip().split(' ')[0]
    hum = data[3].strip().split(' ')[0]
    #print(temp + ' ... ' + press + ' ... ' +hum)

    # measured rel. humidity - humidity (temp in F, pressure)
    ind = float(hum) - 1 / (float(temp)*9/5+32) * float(press)
    #ind = float(hum)/ float(temp)
    print (ind)
    inds.append(ind)

  if inds[-1] > inds[-2] and inds[-2] > inds[-3] and inds[-3] > inds[-4]:
    counter = 0
    while counter < 30:
      led2.on()
      sleep(0.5)
      led2.off()
      sleep(0.5)
      counter += 1
except:
  pass


# 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()
コード例 #44
0
red = LED(5)
yellow = LED(6)
green = LED(13)

button1 = Button(2)
button2 = Button(3)
button3 = Button(4)

while True:
    if button1.is_pressed:
        time.sleep(0.3)
        print("Button 1 Pressed")
        red.on()
        sample(LOOP_AMEN, rate=uniform(0.5,2))
    elif button2.is_pressed:
        time.sleep(0.1)
        print("Button 2 is Pressed")
        yellow.on()
        play(G5)
    elif button3.is_pressed:
        time.sleep(0.1)
        print("Button 3 is Pressed")
        green.on()
        play(D5)
    else:
        red.off()
        yellow.off()
        green.off()
        
コード例 #45
0
import time
from gpiozero import LED


print "BlueToothKeylessEntry"
ledUnlock = LED(17) #GPIO pin 17 on rpizero set to unlock
ledLock = LED(27) #GPIO pin 27 on rpizero set to lock
lockStatus = 0
while True:
    result = bluetooth.lookup_name('98:E7:F5:FB:XX:XX', timeout=5)
    if (result != None):  			#mac address found within proximity

	if (lockStatus == 0): 			#If car is not already unlocked
		ledUnlock.on()
		time.sleep(2)
		ledUnlock.off()
		time.sleep(2)
		lockStatus = 1
#						print "Car was locked, now it is unlocked"
    else:					#mac address not found

	if (lockStatus == 1):			#if car is not already locked
		ledLock.on()
		time.sleep(2)
		ledLock.off()
		time.sleep(2)
		lockStatus = 0
#						print "Car was unlocked, now it is locked"
    time.sleep(15)				#search for phone every 15 seconds

コード例 #46
0
ファイル: led3.py プロジェクト: Flye001/Pokedex
from gpiozero import LED
import time

activity = LED(47)

activity.on()
time.sleep(5)
activity.off()
コード例 #47
0
 print("".join(["Log File: ", name_string]))
 ss.read_info_string()
 ss.read_config_vars()
 print("Creating SD Log File")
 sd_log.make_headers(mavcon.start_date, mavcon.start_time,
                     str(int(mavcon.epoch_time / 1000)), ss.info_string,
                     ss.bbs, ss.gsc, ss.id)
 print("Creating USB Log File")
 usb_log.make_headers(mavcon.start_date, mavcon.start_time,
                      str(int(mavcon.epoch_time / 1000)), ss.info_string,
                      ss.bbs, ss.gsc, ss.id)
 t0 = mavcon.boot_time
 print("Starting Main Loop")
 loop_num = 0
 while True:
     act_led.off()
     if (loop_num % 10) == 0:
         print "Getting GPS Time"
         mavcon.get_date_time()
         t1 = mavcon.boot_time
     else:
         t1 = time()
     mavcon.fill_info_buffer()
     ss.read_histogram_data()
     met_module.read_hum()
     met_module.read_temp()
     sd_log.write_data_log(t1, mavcon.press_hPa, mavcon.lat, mavcon.lon,
                           mavcon.alt_m, mavcon.vz_ms, met_module.t_deg_c,
                           met_module.rh_true, ss.hist, ss.mtof, ss.period,
                           ss.checksum, ss.reject_glitch, ss.reject_ltof,
                           ss.reject_ratio)
コード例 #48
0
class ReSpeaker_4mic_hat(MycroftSkill):
    def __init__(self):
        super(ReSpeaker_4mic_hat, self).__init__(name="LED Ring - Respeaker")

    def initialize(self):
        self.log.info("Pixel Ring: Initializing")
        self.power = LED(5)
        self.power.on()
        pixel_ring.set_brightness(10)
        pattern = self.settings.get("theme", "mytheme1")
        pixel_ring.change_pattern(pattern)
        self.log.info(
            f"Pixel Ring Pattern - Input: {pattern} - Actual: {pixel_ring.pattern}"
        )
        pixel_ring.wakeup()
        self.enable()

    def enable(self):
        self.log.info("Pixel Ring: Enabling")

        self.add_event('recognizer_loop:wakeword', self.handle_listener_wakeup)
        self.add_event('recognizer_loop:record_end', self.handle_listener_off)

        self.add_event('mycroft.skill.handler.start',
                       self.handle_listener_think)
        self.add_event('mycroft.skill.handler.complete',
                       self.handle_listener_off)

        self.add_event('recognizer_loop:audio_output_start',
                       self.handler_listener_speak)
        self.add_event('recognizer_loop:audio_output_end',
                       self.handle_listener_off)

        pixel_ring.off()

    def disable(self):
        self.log.info("Pixel Ring: Disabling")
        self.remove_event('recognizer_loop:wakeup')
        self.remove_event('recognizer_loop:record_end')
        self.remove_event('recognizer_loop:audio_output_start')
        self.remove_event('recognizer_loop:audio_output_end')
        self.remove_event('mycroft.skill.handler.start')
        self.remove_event('mycroft.skill.handler.complete')

    def shutdown(self):
        self.log.info("Pixel Ring: Shutdown")
        pixel_ring.off()
        self.power.off()

    def handle_listener_wakeup(self, message):
        self.log.info("Pixel Ring: Wakeup")
        pixel_ring.wakeup()

    def handle_listener_off(self, message):
        self.log.info("Pixel Ring: Off")
        pixel_ring.off()

    def handle_listener_think(self, message):
        self.log.info("Pixel Ring: Think")
        pixel_ring.think()

    def handler_listener_speak(self, message):
        self.log.info("Pixel Ring: Speak")
        pixel_ring.speak()

    @intent_handler(IntentBuilder("").require("EnablePixelRing"))
    def handle_enable_pixel_ring_intent(self, message):
        self.enable()
        self.speak_dialog("EnablePixelRing")

    @intent_handler(IntentBuilder("").require("DisablePixelRing"))
    def handle_disable_pixel_ring_intent(self, message):
        self.disable()
        self.speak_dialog("DisablePixelRing")
コード例 #49
0
ファイル: ledMatrix.py プロジェクト: fdelia/raspberry-backup
from gpiozero import LED
from time import sleep

led = {}
led[2] = LED(17)
led[3] = LED(24)
led[4] = LED(5)
led[5] = LED(13)
led[6] = LED(12)
led[7] = LED(25)
led[0] = LED(16)
led[1] = LED(20)
ledC = LED(6)

while True:
	for i in range(0, 8):
		if i%2 == 0: ledC.on()
		else: ledC.off()
		led[i].on()
		sleep(1)
		led[i].off()
		
コード例 #50
0
def init_led():
    """Create and initialise an LED Object"""
    global led
    led = LED(LED_GPIO_PIN)
    led.off()
コード例 #51
0
ファイル: led.py プロジェクト: ezbins/python
from gpiozero import LED
from time import sleep
import random

led1 = LED(2)
led2 = LED(3)
while True:
    number = random.randrange(10)
    if number ==2:	
       led2.off()
       led1.on()
       print(number)
       sleep(2)
    if number ==3:
      led1.off()
      led2.on()
      print(number) 
      sleep(2)
コード例 #52
0
ファイル: sample_data.py プロジェクト: DougMHu/vIoThackathon
    # Parse arguments
    parser = argparse.ArgumentParser(description='Take magnetometer samples.')
    parser.add_argument('--num', default=100, type=int)
    parser.add_argument('--dur', type=int)
    parser.add_argument('--freq', default=10, type=int)
    parser.add_argument('outfile',
                        nargs='?',
                        type=argparse.FileType('w'),
                        default=sys.stdout)
    args = parser.parse_args()
    if args.dur:
        args.num = args.dur * args.freq

    # Initialize all GPIO off
    from gpiozero import LED
    hmc2 = LED(24)
    hmc2.off()
    hmc1 = LED(23)
    hmc1.off()
    hmc1.on()

    # Turn on HMC5883L at GPIO 23
    hmc2.off()
    hmc1.on()

    # Take samples and write them to outfile
    writeSamples(args.num, args.freq, args.outfile)

    # Turn off HMC5883L
    hmc1.off()
#A 3 LED traffic light sequence activate dby a button press
from gpiozero import LED, Button
from time import sleep

led_red = LED(17)
led_yellow = LED(27)
led_green = LED(22)
button= Button(5)
while True:
    button.wait_for_press()
    for n in range (3):
        led_red.on()
        led_yellow.off()
        sleep(1)
        led_yellow.on()
        sleep(1)
        led_red.off()
        led_yellow.off()
        led_green.on()
        sleep(1)
        led_green.off()
        led_yellow.on()
        led_red.off()
        sleep(1)
        led_red.on()
        led_yellow.off()
        sleep(1)
        led_red.off()
コード例 #54
0
ファイル: Espace.py プロジェクト: crir08/CodeMorse-DreamTeam
def Espace():
    led = LED(17)
    led.off()
    sleep(4)
コード例 #55
0
ファイル: lights.py プロジェクト: amos1969/geocraft
from mcpi.minecraft import Minecraft
from mcpi import block
from gpiozero import LED
red = LED(17)
amber = LED(27)
green = LED(9)
mc = Minecraft.create()

while True:
    pos = mc.player.getPos()
    blockType = mc.getBlockWithData(pos.x, pos.y-1, pos.z)
    if blockType.data == 14:
        red.on()
        amber.off()
        green.off()
    elif blockType.data == 4:
        red.off()
        amber.on()
        green.off()
    elif blockType.data == 5:
        red.off()
        amber.off()
        green.on()
    else:
        red.off()
        amber.off()
        green.off()
        
    

コード例 #56
0
from gpiozero import LED

from pids import pidSens
from gearCalc import gearDisp

# Initiate debug file
timeStamp = (strftime("%Y-%m-%d %H:%M:%S", gmtime()))
fileName = timeStamp + '-debug.txt'
f = open(fileName,  "w")
f.write("Initiate debug log \n")

# Blink display led 5 times to show device has started
# led will blink at 2500ms intervals while data is uploaded
# to firebase
led = LED(17)
led.off()
for i in range(0, 4):
    led.on()
    sleep(.5)
    led.off()
    sleep(.5)

# Connect to Car ECU
ecuAttempt = 1
try:
    f.write('Attempting Connection to OBD \n')
    connection = OBD()
    f.write(str(connection) + '\n')
except:
    sleep(.25)
    f.write("Connection to ECU #:{} unsuccsesfull, retrying...\n".format(
コード例 #57
0
ファイル: drop_cam2.py プロジェクト: uktechreviews/motion_cam
	disp.image(logo_dropbox)
	disp.display()
	led_drop.on()
	time.sleep(2)
	draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=255, fill=255)
	draw.text((3,0), 'Dropbox', font=font)
	draw.text((3,10), 'Upload', font=font)
	draw.text((3,20), 'in progress', font=font)
	disp.image(image)
	disp.display()
	subprocess.call('/home/pi/Dropbox-Uploader/dropbox_uploader.sh upload /home/pi/photo_output /photos', shell=True)
	draw.text((3,30), 'Completed', font=font)
	subprocess.call('sudo rm  /home/pi/photo_output/*.jpg', shell=True)
	disp.display()
	time.sleep(5)
	led_drop.off()
	draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=255, fill=255)
        draw.text((3,0), 'Files uploaded', font=font)
        draw.text((3,10), 'Files erased', font=font)
        draw.text((3,20), 'Shutting down', font=font)
        disp.image(image)
        disp.display()
	time.sleep(2)
	subprocess.call('sudo halt', shell=True)
draw.rectangle((0,0,LCD.LCDWIDTH,LCD.LCDHEIGHT), outline=255, fill=255)
draw.text((3,0), 'Pi Motion', font=font)
draw.text((3,10), 'Camera', font=font)
draw.text((3,20), 'Spencer Organ', font=font)
disp.image(image)
disp.display()
time.sleep(2)
コード例 #58
0
ファイル: 2-LEDBuzz.py プロジェクト: BenRPi/Zero-RFID-System
# CamJam EduKit 2 - Sensors (GPIO Zero)
# Worksheet 2 - LEDs and Buzzer

# Import Python libraries
from gpiozero import LED, Buzzer
import time

# Set up the LEDs and Buzzer
red = LED(18)
blue = LED(24)
buzzer = Buzzer(22)

print("Lights and sound on")
red.on()
blue.on()
buzzer.on()

# Pause for one second
time.sleep(1)

print("Lights and sound off")
red.off()
blue.off()
buzzer.off()
コード例 #59
0
ファイル: LEDFlash.py プロジェクト: Workshopshed/GPIOZero
from gpiozero import LED
from time import sleep

green = 12

led = LED(green)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)
コード例 #60
0
ファイル: IIoTTeam1.py プロジェクト: IIoTteam1/Garden-sense
            print('Danger!')
            print(str(GPIO.input(16)))
            Airquality = "prox,d=" + str(GPIO.input(16))
            relay.on()
            mqttc.publish(air_value, payload=Airquality, retain=True)
            return

        GPIO.add_event_detect(16, GPIO.RISING)
        GPIO.add_event_callback(16, action)

        try:
            while True:
                print('Safe.')
                print(str(GPIO.input(16)))
                Airquality = "prox,d=" + str(GPIO.input(16))
                relay.off()
                mqttc.publish(air_value, payload=Airquality, retain=True)
                time.sleep(1)
                break

        except KeyboardInterrupt:
            GPIO.cleanup()

        #moisture

        while True:
            if GPIO.input(channel) == GPIO.HIGH:
                print("dry")
                print(str(GPIO.input(channel)))
                moisture = "prox,d=" + str(0)
                relay.on()