class Led: def __init__(self, pin): self._led_output = OutputDevice(pin) def on(self): self.state = True def off(self): self.state = False @property def state(self): return self._led_output.value @state.setter def state(self, value: bool): self._led_output.value = value def release(self): self.off() self._led_output.close() def __enter__(self) -> "Led": self.on() return self def __exit__(self, type, value, traceback): self.off()
class StepperMotor: __slots__ = [ '_coil_A_1_pin', '_coil_A_2_pin', '_coil_B_1_pin', '_coil_B_2_pin', ] # This is comming from: http://www.raspberrypi-spy.co.uk/2012/07/stepper-motor-control-in-python/ _seq = [[1, 0, 0, 1], [1, 0, 0, 0], [1, 1, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 1], [0, 0, 0, 1]] def __init__(self, coil_A_1_pin: int, coil_A_2_pin: int, coil_B_1_pin: int, coil_B_2_pin: int) -> None: self._coil_A_1_pin = OutputDevice(coil_A_1_pin) self._coil_A_2_pin = OutputDevice(coil_A_2_pin) self._coil_B_1_pin = OutputDevice(coil_B_1_pin) self._coil_B_2_pin = OutputDevice(coil_B_2_pin) def rotate(self, delay: float, steps: int) -> None: if steps >= 0: self.forward(delay, steps) else: self.backwards(delay, abs(steps)) def forward(self, delay: float, steps: int) -> None: for i in range(steps): for pattern in self._seq: self._set_step(*pattern) time.sleep(delay) def backwards(self, delay: float, steps: int) -> None: for i in range(steps): for pattern in reversed(self._seq): self._set_step(*pattern) time.sleep(delay) def stop(self) -> None: self._set_step(0, 0, 0, 0) def release(self) -> None: self.stop() self._coil_A_1_pin.close() self._coil_A_2_pin.close() self._coil_B_1_pin.close() self._coil_B_2_pin.close() def _set_step(self, w1: int, w2: int, w3: int, w4: int) -> None: self._coil_A_1_pin.value = w1 self._coil_A_2_pin.value = w2 self._coil_B_1_pin.value = w3 self._coil_B_2_pin.value = w4 def __enter__(self) -> "StepperMotor": return self def __exit__(self, type, value, traceback): self.release()
class Pump: def __init__(self, pin): self.pump = OutputDevice(pin) def __edit__(self): self.pump.close() def self_test(self): for i in range(0, 10): self.pump.on() time.sleep(0.1) self.pump.off() time.sleep(0.1) def on(self): self.pump.on() def off(self): self.pump.off()
class RoPiDistance: # initialization def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Distance...") log.debug("> echo 1 pin: " + str(_conf['echo_1_pin'])) log.debug("> trig 1 pin: " + str(_conf['trig_1_pin'])) log.debug("> echo 2 pin: " + str(_conf['echo_2_pin'])) log.debug("> trig 2 pin: " + str(_conf['trig_2_pin'])) # using InputDevice and OutputDevice rem_pi = PiGPIOFactory(host=remote_address) self.distance1_trig = OutputDevice(pin=_conf['trig_1_pin'], pin_factory=rem_pi) self.distance1_echo = InputDevice(pin=_conf['echo_1_pin'], pin_factory=rem_pi) self.distance2_trig = OutputDevice(pin=_conf['trig_2_pin'], pin_factory=rem_pi) self.distance2_echo = InputDevice(pin=_conf['echo_2_pin'], pin_factory=rem_pi) # values self.distance1 = Value('i', 0) self.distance2 = Value('i', 0) # processes log.debug("Initializing Distance processes...") self.process1 = Process(target=self.D1) self.process2 = Process(target=self.D2) self.process1.start() self.process2.start() log.debug("...init done!") # is close def is_close(self): distance1 = (self.distance1.value) < _conf['SAFETY_DISTANCE'] distance2 = (self.distance2.value) < _conf['SAFETY_DISTANCE'] log.debug("> is close ? " + str(distance1 or distance2)) return distance1 or distance2 # get distance 1 def get_distance1(self): log.debug("> Distance 1: " + str(self.distance1.value)) return self.distance1.value # get distance 2 def get_distance2(self): log.debug("> Distance 2: " + str(self.distance2.value)) return self.distance2.value # terminate def terminate(self): log.debug("Distance termination...") self.distance1_trig.close() self.distance1_echo.close() self.distance2_trig.close() self.distance2_echo.close() # control distance sensor 1 def D1(self): self.worker(self.distance1_trig, self.distance1_echo, self.distance1) # control distance sensor 1 def D2(self): self.worker(self.distance2_trig, self.distance2_echo, self.distance2) # worker def worker(self, trigger, echo, distance): while True: log.debug("Wait for sensor...") sleep(_conf['SENSORS_OFF_SPAN']) log.debug("Activate trigger...") trigger.on() sleep(_conf['TRIG_SPAN']) log.debug("Deactivate trigger...") trigger.off() log.debug("Calculate distance...") distance.value = self.calculate_distance( self.wait_for_signal(time(), echo), self.wait_for_distance(time(), echo)) # wait for pulse start def wait_for_signal(self, pulse_start, echo): log.debug("Wait for echo...") while echo.is_active == False: pulse_start = time() log.debug("echo started at:" + str(pulse_start)) return pulse_start # wait for pulse end def wait_for_distance(self, pulse_end, echo): log.debug("Wait for echo back...") while echo.is_active == True: pulse_end = time() log.debug("echo ended at:" + str(pulse_end)) return pulse_end # calculate distance def calculate_distance(self, pulse_start, pulse_end): log.debug("Calculate pulse duration...") pulse_duration = pulse_end - pulse_start distance = pulse_duration * _conf['SPEED_OF_SOUND'] log.debug("Distance is: " + str(distance)) return int(distance)
if 'entities' in msg and msg['entities'][0]['type'] == 'bot_command': command = msg['text'] if command == '/lamp': relay.toggle() snitchMsg('\nStatus: {}'.format(str(relay.value)), None ) elif command == '/status': statusCheck() # If not an auth user else: return else: bot.sendMessage(chat_id, 'You do\'nt have permission.') MessageLoop(bot, handle).run_as_thread() def statusCheck(): message=('<code>Door sensor:{}\nLED value:{}\nRelay status:{}\nBuzzer status: {}</code>'.format(button.value,led.value,relay.value,bz.value)) snitchMsg(message,'Html') try: initVal(button.is_pressed) button.when_pressed = closed button.when_released = opened pause() except KeyboardInterrupt: print ('\nExiting app\n') bz.close() relay.close()
#!/usr/bin/env python3 # reset del dispositivo from gpiozero import OutputDevice from time import sleep # reset on pin 17, active low rst = OutputDevice(17, False) rst.on() sleep(0.5) rst.off() rst.close() root@esp:/home/nuria/ESP8266pHAT/phatsniffer# more reset_phat.py #!/usr/bin/env python3 from gpiozero import OutputDevice from time import sleep # reset on pin 17, active low rst = OutputDevice(17, False) rst.on() sleep(0.5) rst.off() rst.close()
class RoPiMotor: # initialize def __init__(self, remote_address): # set PINs on BOARD log.debug("Initializing Motors...") log.debug("> back left PIN: " + str(_conf['motor_back_left_pin'])) log.debug("> back right PIN: " + str(_conf['motor_back_right_pin'])) log.debug("> front left PIN: " + str(_conf['motor_front_left_pin'])) log.debug("> front right PIN: " + str(_conf['motor_front_right_pin'])) # using OutputDevice rem_pi = PiGPIOFactory(host=remote_address) # left self.motor2_back = OutputDevice(pin=_conf['motor_back_left_pin'], pin_factory=rem_pi) self.motor2_front = OutputDevice(pin=_conf['motor_front_left_pin'], pin_factory=rem_pi) # right self.motor1_back = OutputDevice(pin=_conf['motor_back_right_pin'], pin_factory=rem_pi) self.motor1_front = OutputDevice(pin=_conf['motor_front_right_pin'], pin_factory=rem_pi) # directions self.motor1_direction = Value("i", 0) self.motor2_direction = Value("i", 0) # queues and processes log.debug("Initializing Motors queues and processes...") self.queue1 = Queue() self.queue2 = Queue() self.process1 = Process(target=self.M1) self.process2 = Process(target=self.M2) self.process1.start() self.process2.start() log.debug("...init done!") # clean a queue def clearQueue(self, q): while not q.empty(): q.get() # clean all queues def cleanQueues(self): log.debug("Cleaning queues...") self.clearQueue(self.queue1) self.clearQueue(self.queue2) # stop the motors def stop(self): self.cleanQueues() self.motor1_back.off() self.motor2_back.off() self.motor1_front.off() self.motor2_front.off() # control motor process 1 def M1(self): self.worker(self.motor1_back, self.motor1_front, self.queue1) # control motor process 2 def M2(self): self.worker(self.motor2_back, self.motor2_front, self.queue2) # worker def worker(self, motor_back, motor_front, queue): try: while True: if not queue.empty(): direction = queue.get().split("|") acceleration = float(direction[2]) speed = float(direction[1]) direction = direction[0] log.debug("Going direction [" + str(direction) + "] at [" + str(speed) + "] speed for " + str(acceleration) + "s") motor_back.off() motor_front.off() if direction == "f": motor_front.on() #(speed=speed) elif direction == "b": motor_back.on() #(speed=speed) sleep(acceleration) motor_front.off() motor_back.off() except KeyboardInterrupt: pass # go forward def forward(self, speed=1, duration=_conf['ACCELERATION_TIME']): if not self.motor1_direction.value == 1: self.clearQueue(self.queue1) self.motor1_direction.value = 1 if not self.motor2_direction.value == 1: self.clearQueue(self.queue2) self.motor2_direction.value = 1 self.queue1.put("f|" + str(speed) + "|" + str(duration)) self.queue2.put("f|" + str(speed) + "|" + str(duration)) # go backward def backward(self, speed=1, duration=_conf['ACCELERATION_TIME']): if not self.motor1_direction.value == -1: self.clearQueue(self.queue1) self.motor1_direction.value = -1 if not self.motor2_direction.value == -1: self.clearQueue(self.queue2) self.motor2_direction.value = -1 self.queue1.put("b|" + str(speed) + "|" + str(duration)) self.queue2.put("b|" + str(speed) + "|" + str(duration)) # go forward LEFT def forwardleft(self, speed=1, duration=_conf['ACCELERATION_TIME']): self.clearQueue(self.queue2) if not self.motor1_direction.value == 1: self.clearQueue(self.queue1) self.motor1_direction.value = 1 self.queue1.put("f|" + str(speed) + "|" + str(duration)) # go forward RIGHT def forwardright(self, speed=1, duration=_conf['ACCELERATION_TIME']): self.clearQueue(self.queue1) if not self.motor2_direction == 1: self.clearQueue(self.queue2) self.motor2_direction.value = 1 self.queue2.put("f|" + str(speed) + "|" + str(duration)) # go backward LEFT def backwardleft(self, speed=1, duration=_conf['ACCELERATION_TIME']): self.clearQueue(self.queue2) if not self.motor1_direction.value == -1: self.clearQueue(self.queue1) self.motor1_direction.value = -1 self.queue1.put("b|" + str(speed) + "|" + str(duration)) # go backward RIGHT def backwardright(self, speed=1, duration=_conf['ACCELERATION_TIME']): self.clearQueue(self.queue1) if not self.motor2_direction.value == -1: self.clearQueue(self.queue2) self.motor2_direction.value = -1 self.queue2.put("b|" + str(speed) + "|" + str(duration)) # terminate def terminate(self): log.debug("Motors termination...") self.process1.terminate() self.process2.terminate() self.stop() self.queue1.close() self.queue1.join_thread() self.queue2.close() self.queue2.join_thread() self.motor1_back.close() self.motor2_back.close() self.motor1_front.close() self.motor2_front.close()
class XmasTree(): # define our xmas tree as a Python class # When we create a new tree, we set the pins that it uses. # Each pin is a 'node' that is used to control 2 LEDs. Each LED # uses 2 nodes: one is the anode, the other the cathode def __init__(self, node1, node2, node3, node4): self.anode = InputDevice(node1) self.cathode = InputDevice(node2) self.node1 = node1 self.node2 = node2 self.node3 = node3 self.node4 = node4 # A function to turn off any LED which is on. def last_off(self): self.anode.close() self.cathode.close() # A function to turn on an LED # We pass in anode and cathode values def gen_on(self, anode, cathode): self.last_off() self.anode = OutputDevice(anode) self.cathode = OutputDevice(cathode) self.anode.on() self.cathode.off() def pwm_on(self, anode, cathode, fade_in, fade_out, n): self.last_off() self.anode = PWMOutputDevice(anode) self.cathode = OutputDevice(cathode) self.anode.pulse(fade_in_time=fade_in, fade_out_time=fade_out, n=n, background=False) self.cathode.off() # A function for each of the LEDs # It just calls the gen_on() and passes in # the correct anode and cathode values def red1_on(self): self.gen_on(self.node4, self.node3) def red2_on(self): self.gen_on(self.node3, self.node4) def red3_on(self): self.gen_on(self.node4, self.node2) def red4_on(self): self.gen_on(self.node2, self.node4) def red5_on(self): self.gen_on(self.node1, self.node2) def red6_on(self): self.gen_on(self.node2, self.node1) def yellow_on(self): self.gen_on(self.node3, self.node1) def all_on(self, time): t = 0.001 for p in range(int((time / t) / 7)): self.red1_on() sleep(t) self.red2_on() sleep(t) self.red3_on() sleep(t) self.red4_on() sleep(t) self.red5_on() sleep(t) self.red6_on() sleep(t) self.yellow_on() sleep(t) self.last_off() def yellow_pulse(self, fade_in, fade_out, n): self.pwm_on(self.node3, self.node1, fade_in, fade_out, n)
#!/usr/bin/env python3 # modo programacion # Se debe de enviar low al GPIO #0 mientras que se hace el reset from gpiozero import OutputDevice from time import sleep # reset on pin 17, active low rst = OutputDevice(17, False) # flash mode select on pin 27, active low flash = OutputDevice(27, False) flash.on() sleep(0.5) rst.on() sleep(0.5) rst.off() sleep(0.5) flash.off() rst.close() flash.close()
class lcdzero(SharedMixin, Device): def __init__(self, width, heigth, enable_pin, rw_pin, rs_pin, d4_pin, d5_pin, d6_pin, d7_pin): self.lock = None self.enable = None self.rw = None self.rs = None self.d4 = None self.d5 = None self.d6 = None self.d7 = None self.width = width self.heigth = heigth self.lcd_character = True self.lcd_command = False self.lcd_line = [0x80, 0xC0] # LCD RAM address for the 1st & 2nd line # Timing constants self.enable_pulse = 0.0005 self.enable_delay = 0.0005 self.verbose = False super(lcdzero, self).__init__() self.lock = RLock() try: self.enable = OutputDevice(enable_pin) if rw_pin is not None: self.rw = OutputDevice(rw_pin) if rs_pin is not None: self.rs = OutputDevice(rs_pin) if d4_pin is not None: self.d4 = OutputDevice(d4_pin) if d5_pin is not None: self.d5 = OutputDevice(d5_pin) if d6_pin is not None: self.d6 = OutputDevice(d6_pin) if d7_pin is not None: self.d7 = OutputDevice(d7_pin) except: self.close() raise self.lcd_init() def close(self): super(lcdzero, self).close() if getattr(self, 'lock', None): with self.lock: if self.enable is not None: self.enable.close() self.enable = None if self.rw is not None: self.rw.close() self.rw = None if self.rs is not None: self.rs.close() self.rs = None if self.d4 is not None: self.d4.close() self.d4 = None if self.d5 is not None: self.d5.close() self.d5 = None if self.d6 is not None: self.d6.close() self.d6 = None if self.d7 is not None: self.d7.close() self.d7 = None self.lock = None @property def closed(self): return self.lock is None @classmethod def _shared_key(cls, width, height, enable_pin, rw_pin, rs_pin, d4_pin, d5_pin, d6_pin, d7_pin): return (width, height, enable_pin, rw_pin, rs_pin, d4_pin, d5_pin, d6_pin, d7_pin) def lcd_init(self): # Initialise display self.rw.value = False # low RW port to write to display self.lcd_byte(0x33, self.lcd_command) # 110011 Initialise self.lcd_byte(0x32, self.lcd_command) # 110010 Initialise self.lcd_byte(0x06, self.lcd_command) # 000110 Cursor move direction self.lcd_byte( 0x0C, self.lcd_command) # 001100 Display On,Cursor Off, Blink Off self.lcd_byte( 0x28, self.lcd_command) # 101000 Data length, number of lines, font size self.lcd_byte(0x01, self.lcd_command) # 000001 Clear display sleep(self.enable_delay) def lcd_byte(self, bits, mode): # Send byte to data pins # bits = data # mode = True for character # False for command self.rs.value = mode # High bits self.d4.value = bool(bits & 0x10) self.d5.value = bool(bits & 0x20) self.d6.value = bool(bits & 0x40) self.d7.value = bool(bits & 0x80) # Toggle 'Enable' pin self.lcd_toggle_enable() # Low bits self.d4.value = bool(bits & 0x01) self.d5.value = bool(bits & 0x02) self.d6.value = bool(bits & 0x04) self.d7.value = bool(bits & 0x08) # Toggle 'Enable' pin self.lcd_toggle_enable() def lcd_toggle_enable(self): # Toggle enable sleep(self.enable_delay) self.enable.value = True sleep(self.enable_pulse) self.enable.value = False sleep(self.enable_delay) def display(self, message, row): # Send string to display if not message: message = "empty" message = message.center(self.width, " ") self.lcd_byte(self.lcd_line[row], self.lcd_command) for i in range(self.width): self.lcd_byte(ord(message[i]), self.lcd_character)
pwm = PWMOutputDevice(pwmPin, initial_value = v, frequency = f) print("Tekan ctrl-c untuk berhenti!") pl = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0] try: while True: zf.value = 0 for p in pl: pwm.value = p; sleep(0.25) print("dir = {}, val = {}".format(zf.value, p)) sleep(1) zf.value = 1 for p in pl: pwm.value = p; sleep(0.25) print("dir = {}, val = {}".format(zf.value, p)) sleep(1) except KeyboardInterrupt: v = pwm.value while v > 0.0: v -= 0.1 if v < 0.0: v = 0.0 else: if v>=0: pwm.value -= v; sleep(0.25) pwm.close() zf.close() print("\n\nDone...!")
LED_OUT = [] for pin in LED_PINS: LED_OUT.append(PWMOutputDevice(pin)) try: while True: left_dist = left_sonar.distance() time.sleep(.100) middle_dist = middle_sonar.distance() time.sleep(.100) right_dist = right_sonar.distance() time.sleep(.100) print("left: %s; middle: %s; right: %s;" % (distance_display(left_dist), distance_display(middle_dist), distance_display(right_dist))) for controllerKey in controllers: controllers[controllerKey].set_sensor_values( [left_dist, middle_dist, right_dist]) time.sleep(1) except KeyboardInterrupt: ECHO.close() LEFT_TRIGGER.close() MIDDLE_TRIGGER.close() RIGHT_TRIGGER.close() stop_light_driver_thread = True print("Measurement stopped by User")
class XmasTree(): def __init__(self): #self.A = InputDevice(21) #self.B = InputDevice(19) self.anode = InputDevice(26) self.cathode = InputDevice(20) def all_off(self): #self.A.close() #self.B.close() #self.C.close() #self.D.close() self.anode.close() self.cathode.close() def gen_on(self, an, cath): self.all_off() self.anode = OutputDevice(an) self.cathode = OutputDevice(cath) self.anode.value = True self.cathode.value = False def red1_on(self): self.all_off() self.C = OutputDevice(26) self.D = OutputDevice(20) self.C.value = True self.D.value = False def red2_on(self): self.all_off() self.C = OutputDevice(26) self.D = OutputDevice(20) self.C.value = False self.D.value = True def red3_on(self): self.all_off() self.B = OutputDevice(19) self.D = OutputDevice(20) self.B.value = False self.D.value = True def red4_on(self): self.all_off() self.B = OutputDevice(19) self.D = OutputDevice(20) self.B.value = True self.D.value = False def red5_on(self): self.all_off() self.B = OutputDevice(19) self.A = OutputDevice(21) self.B.value = True self.A.value = False def red6_on(self): self.all_off() self.B = OutputDevice(19) self.A = OutputDevice(21) self.A.value = True self.B.value = False def yellow_on(self): self.all_off() self.C = OutputDevice(26) self.A = OutputDevice(21) self.C.value = True self.A.value = False
from gpiozero import OutputDevice import time """ use the GPIO outputs to turn the pump and drainage line solenoid valve on and off, pressurize the line so it sprays the plants with mist for some period of time """ # todo: this should log somewhere when it runs # todo: pin numbers should be configurable main_pump = OutputDevice(14, active_high=False, initial_value=False) drain_solenoid = OutputDevice(15, active_high=False, initial_value=False) main_pump.on() time.sleep(4.5) drain_solenoid.on() main_pump.off() time.sleep(30) drain_solenoid.close() main_pump.close()