def arm_bomb(self): if gpioctrl: explode = OutputDevice(gpioexplode, active_high=False) explode2 = OutputDevice(gpioexplode2, active_high=False) takephoto() logging.debug("ARM button pressed! Arming bomb now!") self.statusled.blink(on_time=0.05, off_time=0.05) self.buzzer.source = self.statusled.values else: logging.debug("Arming bomb now!") stoptimers(1) if gpioctrl: time.sleep(2.5) explode.on() time.sleep(0.8) explode2.on() takephoto() time.sleep(2) takephoto() explode.off() time.sleep(1) explode2.off() takephoto() closeall(0, 0)
class GPIOResource(resource.Resource): def get_link_description(self): # Publish additional data in .well-known/core return dict(**super().get_link_description(), title=f"GPIO Resource - pin: {self.pin}") def __init__(self, pin): super().__init__() self.pin = pin self.resource = OutputDevice(pin) async def render_get(self, request): print(f'GPIO {self.pin}: GET') payload = f"{self.resource.value}" return Message(payload=payload.encode(), code=Code.CONTENT) async def render_post(self, request): payload = request.payload.decode() print(f'GPIO {self.pin}: POST {payload}') if payload in ['0', 'off']: self.resource.off() elif payload in ['1', 'on']: self.resource.on() else: return Message(code=Code.BAD_REQUEST) return Message(code=Code.CHANGED)
class Bistrobot: def __init__(self, feeder_pin, sensor_pin): self.feeder = OutputDevice(feeder_pin) self.sensor = Button(sensor_pin) def get_sensor_status(self): return self.sensor.is_pressed def reset_rotation(self): if not self.sensor.is_pressed: self.feeder.on() while not self.sensor.is_pressed: pass while self.sensor.is_pressed: pass feeder.off() def trigger_portion(self): if not self.sensor.is_pressed: self.feeder.on() while not self.sensor.is_pressed: pass sleep(0.2) self.feeder.off() self.feeder.on() while self.sensor.is_pressed: pass sleep(0.2) self.feeder.off() def serve_meal(self, portions, wait_time=100): for i in range(0, portions): self.trigger_portion() if i < portions - 1: sleep(wait_time)
def main(argv): global ON_THRESHOLD, OFF_THRESHOLD, GPIO_PIN, SLEEP_INTERVAL parser = argparse.ArgumentParser(description='Fan control') parser.add_argument( '--on-threshold', dest='on_threshold', default=os.environ.get('ON_THRESHOLD'), help='(degrees Celsius) Fan kicks on at this temperature.') parser.add_argument( '--off-threshold', dest='off_threshold', default=os.environ.get('OFF_THRESHOLD'), help='(degress Celsius) Fan shuts off at this temperature.') parser.add_argument( '--sleep-interval', dest='sleep_interval', default=os.environ.get('SLEEP_INTERVAL'), help='(seconds) How often we check the core temperature.') parser.add_argument( '--gpio-pin', dest='gpio_pin', default=os.environ.get('GPIO_PIN'), help='Which GPIO pin you\'re using to control the fan.') args = parser.parse_args(args=argv) # Read input if args.on_threshold is not None: ON_THRESHOLD = int(args.on_threshold) if args.off_threshold is not None: OFF_THRESHOLD = int(args.off_threshold) if args.sleep_interval is not None: SLEEP_INTERVAL = int(args.sleep_interval) if args.gpio_pin is not None: GPIO_PIN = int(args.gpio_pin) # Validate the on and off thresholds if OFF_THRESHOLD >= ON_THRESHOLD: raise RuntimeError('OFF_THRESHOLD must be less than ON_THRESHOLD') print( f'Starting thresholds (OFF-ON): [{OFF_THRESHOLD},{ON_THRESHOLD}], poll interval: {SLEEP_INTERVAL}s and GPIO pin {GPIO_PIN}' ) fan = OutputDevice(GPIO_PIN) while True: temp = get_temp() # Start the fan if the temperature has reached the limit and the fan # isn't already running. # NOTE: `fan.value` returns 1 for "on" and 0 for "off" if temp > ON_THRESHOLD and not fan.value: fan.on() # Stop the fan if the fan is running and the temperature has dropped # to 10 degrees below the limit. elif fan.value and temp < OFF_THRESHOLD: fan.off() time.sleep(SLEEP_INTERVAL)
def badge_scan(self, badge_id): lock = OutputDevice(RELAY_RL1_MAKER_SPACE_AUTH_BOARD_J12) # BCM-6 badge_int = int(badge_id, 16) print "Badge str", str(badge_int) print "var type", type(str(badge_int)) print "Badge hex", badge_id temp_list = id_list ts = time.time() sttime = datetime.datetime.fromtimestamp(ts).strftime( '%m%d%Y_%H:%M:%S - ') if badge_int in temp_list: time.sleep(0.5) print("Unlocking with badge:") print badge_id lock.on() #Unlock time.sleep(2.0) #Pause 3.0 seconds = 1500 milliseconds lock.off() #lock print("Lock") with open("badgelog.txt", "a") as myfile: myfile.write(sttime + "Door unlocked with badge: " + badge_id + "\n") else: print("Badge not found in member database.") with open("badgelog.txt", "a") as myfile: myfile.write(sttime + "Unknown badge attempted: " + badge_id + "\n")
class Letter: def __init__(self, index, on_plug_callback, on_unplug_callback, reaction_pin, led_pin, success_color): self._color = None self.index = index self.on_plug_callback = on_plug_callback self.on_unplug_callback = on_unplug_callback self.reaction_pin = InputDevice(reaction_pin, pull_up=True) self.is_chopstick_plugged = self.reaction_pin.is_active self.led_pin = OutputDevice(led_pin) self.success_color = success_color @property def color(self): return self._color @color.setter def color(self, value): self._color = value if value == 'blue': self.led_pin.on() else: self.led_pin.off() logger.info("Letter {}: {}".format(self.index, value)) def check_chopstick(self): if self.reaction_pin.is_active != self.is_chopstick_plugged: self.is_chopstick_plugged = self.reaction_pin.is_active if self.is_chopstick_plugged: self.on_plug_callback(self.index) else: self.on_unplug_callback(self.index) def reaction_do_nothing(self): pass def reaction_toggle_blue_orange(self): if self.color == "blue": self.color = "orange" elif self.color == "orange": self.color = "blue" else: logger.info("Color is {}: nothing to do".format(self.color)) def reaction_set_blue(self): self.color = "blue" def reaction_set_orange(self): self.color = "orange" def reaction_switch_off(self): self.color = "switched_off" def __bool__(self): return self.color == self.success_color
def blink(out: OutputDevice, count: int): for i in range(count): out.on() print(f'Output @ {out.pin} is ON [{i+1}/{count}]') time.sleep(1) out.off() print(f'Output @ {out.pin} is OFF') time.sleep(1)
def activate_relay(): try: relay = OutputDevice(RELAY_PIN, active_high=False, initial_value=False) relay.on() time.sleep(2) relay.off() except BadPinFactory: raise BadRequest("You have issues with your gpiozero installation", 40009, {'ext': 1})
class RelayManager(): def __init__(self, pin): self.relay = OutputDevice(pin) def Switch(self, state): if state == True: self.relay.off() elif state == False: self.relay.on()
class WaterGun(object): def __init__(self, gpio_num): self.gun = OutputDevice(gpio_num, active_high=False) def fire(self, shots_num): self.gun.on() time.sleep(shots_num) self.gun.off()
def _align(self, new_state: bool, output: OutputDevice, name: str): if new_state: if not output.is_active: output.on() self.log.info(f'{name}@{output.pin}:ON') else: if output.is_active: output.off() self.log.info(f'{name}@{output.pin}:OFF')
class Lock: def __init__(self, pin, pulse=100): self._output = OutputDevice(pin=pin, active_high=False, initial_value=False) self._pulse = pulse def unlock(self): self._output.on() sleep(self._pulse / 1000) self._output.off()
class DoorRemote: def __init__(self): self._garageOpener = OutputDevice(18, active_high=False, initial_value=False) pass def click_door(self): logging.info("Clicking door") self._garageOpener.on() time.sleep(.5) self._garageOpener.off()
class RelayHeaterThermostat(Thermostat): def __init__(self, pin, hostname, port=5000): self.relay = OutputDevice(pin) super().__init__(hostname, port) def commandState(self, state): if state == True: self.relay.on() elif state == False: self.relay.off() super().commandState(state)
class Fan(object): def __init__(self, numberPin): self.relay = OutputDevice(numberPin) def value(self): return self.relay.value def fanOff(self): self.relay.off() def fanOn(self): self.relay.on()
def main(): fan = OutputDevice(18) while True: temp = int(vc.measure_temp()) print(temp) if temp >= 50: fan.on() print("fan.on()") elif temp <= 45: fan.off() print("fan.off()") time.sleep(1)
class IO: def __init__(self): self.foo = OutputDevice(19, initial_value=True) self.relay = OutputDevice(27) self.sensor = Button(13, pull_up=None, active_state=True) def isClosed(self): return self.sensor.is_pressed def pressButton(self): self.relay.on() sleep(0.5) self.relay.off()
class RPIGateController(GateController): def __init__(self): super().__init__() self.gpio_pin = OutputDevice(self.Config.gpio_pin_number) self.gpio_pin.off() self.logger = logging.getLogger('rpiplatesrecognition_client.RPIGateController') def press_button(self): self.logger.debug("Pressing button for: " + str(self.Config.button_press_time) + "seconds") self.gpio_pin.on() sleep(self.Config.button_press_time) self.gpio_pin.off()
class TB6612FNG: def __init__(self, IN1, IN2, PWM, STBY): self.input_1 = OutputDevice(IN1) self.input_2 = OutputDevice(IN2) self.speed_control = PWMOutputDevice(PWM) self.standby = OutputDevice(STBY) self.standby.on() self.speed_control.value = 1 def forward(self): print('Motor forward') self.input_1.on() self.input_2.off() def backward(self): print('Motor backward') self.input_1.off() self.input_2.on() def stop(self): print('Motor stop') self.input_1.off() self.input_2.off() def brake(self): print('Motor brake') self.input_1.on() self.input_2.on() def set_speed(self, speed): print('Setting motor speed to ' + str(speed)) self.speed_control.value = speed
def main(): # use pigpio factory = PiGPIOFactory() sole_pin = OutputDevice(SOLENOID_PIN_0, pin_factory=factory) args = sys.argv count = int(args[1]) # pull/push for _ in range(count): sole_pin.on() time.sleep(0.100) sole_pin.off() time.sleep(0.100) return
class Fan: def __init__(self, gpio_pin): self.device = OutputDevice(gpio_pin) def is_on(self): return bool(self.device.value) def is_off(self): return not self.is_on() def turn_on(self): self.device.on() def turn_off(self): self.device.off()
def main(): # use pigpio factory = PiGPIOFactory() tap_pin = OutputDevice(RELAY_PIN_0, pin_factory=factory) args = sys.argv count = int(args[1]) # tap for _ in range(count): tap_pin.on() time.sleep(0.050) tap_pin.off() time.sleep(0.050) return
def get_pulse_time(trig_pin, echo_pin): ###### Add your echo and trig pin as an argument trig = OutputDevice(trig_pin) echo = InputDevice(echo_pin) trig.on() sleep(0.00001) trig.off() pulse_start = time() while echo.is_active == False: pulse_start = time() pulse_end = time() while echo.is_active == True: pulse_end = time() return pulse_end - pulse_start
class PowerClient: def __init__(self, pin): self.gpio = OutputDevice(pin) def turnOn(self): self.gpio.on() def turnOff(self): self.gpio.off() def read(self): return self.gpio.value def isOn(self): return self.read() == 1
class Stepper(): def __init__( self, # sleep_pin: int, step_pin: int, direction_pin: int, reverse: bool = False, step_type: StepType = StepType.FULL): # self.enable = OutputDevice(config.enable) # self.sleep = OutputDevice(sleep_pin, initial_value=True) self.step = OutputDevice(step_pin) self.direction = OutputDevice(direction_pin, initial_value=reverse) self.step_type: StepType = step_type def set_step_type(self, step_type: StepType): self.step_type = step_type def set_direction(self, reverse: bool): if (reverse): self.direction.off() else: self.direction.on() def forward(self, steps: int, reverse: bool = False, step_type: StepType = StepType.FULL, init_delay: int = .05, step_delay: int = .005) -> NoReturn: r"""Forward movements. Arguments steps (int): number of steps that stepper will do reverse (bool): move backward or counterclockwise step_type (StepType): type of step """ # self.sleep.off() self.set_direction(reverse) self.set_step_type(step_type) time.sleep(init_delay) try: for _ in range(steps): self.step.off() time.sleep(step_delay) self.step.on() time.sleep(step_delay) except KeyboardInterrupt: print("User Keyboard Interrupt") except Exception as stepper_error: print(sys.exc_info()[0]) print(stepper_error) finally: # self.sleep.off() self.step.off() self.direction.off()
class DeskDriverProxy: def __init__(self, up_pin, down_pin): self.__up_driver__ = OutputDevice(up_pin) self.__down_driver__ = OutputDevice(down_pin) def stop(self): self.__up_driver__.off() self.__down_driver__.off() def up(self): self.stop() self.__up_driver__.on() def down(self): self.stop() self.__down_driver__.on()
class Solenoid: #Initializes a solenoid on a GPIO pin. Called before using a solenoid def __init__(self, gpio_pin): self.solenoid = OutputDevice(gpio_pin) def on(self): self.solenoid.on() def off(self): self.solenoid.off() def actuate(self): self.solenoid.on() sleep(.5) self.solenoid.off() sleep(4)
class GpioMatrix(MatrixDevice): def __init__(self, _M, _N): super().__init__(_M, _N) self.currentColumn = 0 # Set matrix pins to 'OutputDevice' # Pins swapped so we can hold matrix upside self.R1 = OutputDevice(17) self.G1 = OutputDevice(18) self.B1 = OutputDevice(22) self.R2 = OutputDevice(23) self.G2 = OutputDevice(24) self.B2 = OutputDevice(25) self.A = OutputDevice(7) self.B = OutputDevice(8) self.C = OutputDevice(9) self.OE = OutputDevice(2) self.CLK = OutputDevice(3) self.LAT = OutputDevice(4) def selectSection(self, section): # Quick hack for strange functionality section = (section + 7) % (self.M // 2) self.A.value = bool(section & 0b001) self.B.value = bool(section & 0b010) self.C.value = bool(section & 0b100) def writeTopPixel(self, pixel): self.R1.value = pixel.r self.G1.value = pixel.g self.B1.value = pixel.b def writeBottomPixel(self, pixel): self.R2.value = pixel.r self.G2.value = pixel.g self.B2.value = pixel.b def clock(self): self.CLK.on() self.CLK.off() def setLatch(self, arg): self.LAT.value = arg def setOutputEnable(self, arg): self.OE.value = arg
class UltraSonic(object): def __init__(self): self.trig = OutputDevice(17) self.echo = InputDevice(27) def get_pulse_time(self): self.trig.on() sleep(0.0001) self.trig.off() pulse_start = 0 pulse_end_time = 0 while not self.echo.is_active: pulse_start = time() while self.echo.is_active: pulse_end_time = time() sleep(0.06) return pulse_end_time - pulse_start def calculate_distance(self, duration): velocidade = 343 dist = velocidade * duration / 2 # return dist * 100 # transform to meters return dist def getDist(self, normal=False): distInitial = 0.0 distEnd = 0.0 print('get dist Initial') distInitial = round(self.calculate_distance(self.get_pulse_time()), 2) sleep(0.06) distEnd = round(self.calculate_distance(self.get_pulse_time()), 2) print('if get Dist') if abs(distEnd - distInitial ) >= 0.02 and distEnd < 4: # tolerancia de erro do sensor if normal: # se quiser normalizado entre 0 e 1 return (4 - distEnd) / (4 - 0.02) else: return distEnd * 10 return 0
class Stepper: def __init__(self, enablePin, directionPin, pulsePin, stepsPerRev=3200.0): self.stepsPerDeg = stepsPerRev / 360.0 self.enable = OutputDevice(enablePin) self.direction = OutputDevice(directionPin) self.pulse = OutputDevice(pulsePin) self.pos = 0 self.home = 0 self.on() def step(self): self.pulse.toggle() def dirPos(self): self.direction.on() def dirNeg(self): self.direction.off() def on(self): # 0 is on self.enable.off() def off(self): # 1 is off self.enable.on() def move(self, angle): print("moving") toMove = angle - self.pos self.pos = self.pos + toMove if (toMove > 0): self.dirPos() else: self.dirNeg() toMove = -toMove for i in range(int(toMove * self.stepsPerDeg) * 2): self.step() time.sleep(0.001) def moveRelative(self, angle): print("pos: {}", self.pos) print("angle: {}", angle) self.move(self.home + angle)
class MotorUtil: def __init__(self): self.enable = OutputDevice(GPIO_PIN_ENABLE) self.motor = Motor(GPIO_PIN_FORWARD, GPIO_PIN_BACKWARD) def turn_motor_async(self, duration=MOTOR_DEFAULT_DURATION, speed=MOTOR_DEFAULT_SPEED, override=False): runner = threading.Thread(target=self.turn_motor, args=(duration, speed, override)) runner.start() return def turn_motor(self, duration=MOTOR_DEFAULT_DURATION, speed=MOTOR_DEFAULT_SPEED, override=False): """Turns a Pi motor for the specified duration.""" global IS_RUNNING global LAST_RUN if IS_RUNNING: print("Already running!") return False if not override: current_date = right_now() if date_str(current_date) == date_str(LAST_RUN): print("Already ran in this minute, ignoring.") return False LAST_RUN = right_now() IS_RUNNING = True print(date_str(LAST_RUN)) self.enable.on() self.motor.forward(speed) sleep(duration) self.enable.off() IS_RUNNING = False print("Motor going to idle.") return True
class Driver(object): """ Driver for siren modules; receives commands from SignalTowerServer """ def __init__(self, green_pin, red_pin, siren_pin): super(Driver, self).__init__() self.green_light = OutputDevice(green_pin) self.red_light = OutputDevice(red_pin) self.siren = OutputDevice(siren_pin) def exec_instr(self, instruction): if instruction[0]: self.green_light.on() else: self.green_light.off() if instruction[1]: self.red_light.on() else: self.red_light.off() if instruction[2]: self.siren.on() else: self.siren.off()