def __init__(self, clk_pin, dt_pin, callback): self.clk = gpiozero.InputDevice(clk_pin, pull_up=False) self.dt = gpiozero.InputDevice(dt_pin, pull_up=False) self.callback = callback self.position = 5 self.task = None
def __init__( self, control_panel_service, led_indexes, electromagnet_pin, jack_pin, manual_mode_jack_port_pin, marmitron_mode_jack_port_pin, table_button_pin, table_up_pin, table_down_pin, table_up_down_pins_active_high, table_max_amplitude_duration, table_up_down_minimum_delay, colors, ): self.service = control_panel_service self._status = None self.led_strip = neopixel.NeoPixel(board.D18, 9) self.led_tasks = {} self.scene_led_indexes = led_indexes["scene"] self.manual_mode_led_index = led_indexes["manual_mode"] self.marmitron_mode_led_index = led_indexes["marmitron_mode"] self.lights_status_led_index = led_indexes["lights_status"] self.menu_status_led_index = led_indexes["menu_status"] self.table_led_index = led_indexes["table"] self.electromagnet_led_index = led_indexes["electromagnet"] self.electromagnet = gpiozero.OutputDevice(electromagnet_pin) self.table_button = gpiozero.Button(table_button_pin) # Never have the table_up_pin and table_down_pin active at the same time or electronics might crash self.table_motor_up = gpiozero.OutputDevice( table_up_pin, active_high=table_up_down_pins_active_high) self.table_motor_up.off() self.table_motor_down = gpiozero.OutputDevice( table_down_pin, active_high=table_up_down_pins_active_high) self.table_motor_down.off() self.table_max_amplitude_duration = table_max_amplitude_duration self.table_up_down_minimum_delay = table_up_down_minimum_delay self.table_stop_motor_task = None self.table_led_task = None self.table_watch_button_task = LoopingCall(self.check_table_button) self.has_manual_mode_been_set_once = False self.jack = gpiozero.OutputDevice(jack_pin) self.jack.on() self.manual_mode_jack_port = gpiozero.InputDevice( manual_mode_jack_port_pin) self.marmitron_mode_jack_port = gpiozero.InputDevice( marmitron_mode_jack_port_pin) self.colors = colors self.check_jack_ports()
def __init__(self, objcfg): # Initiate mux control output pins using gpiozero self.coin = gpiozero.DigitalOutputDevice(objcfg.mux_coin, True, False, None) self.tilt = gpiozero.DigitalOutputDevice(objcfg.mux_tilt, True, False, None) self.action = gpiozero.DigitalOutputDevice(objcfg.mux_action, True, False, None) # Initiate mux input pins using gpiozero self.input = [None] * 8 self.input[0] = gpiozero.InputDevice(objcfg.mux.input[0], True, None, None) self.input[1] = gpiozero.InputDevice(objcfg.mux.input[1], True, None, None) self.input[2] = gpiozero.InputDevice(objcfg.mux.input[2], True, None, None) self.input[3] = gpiozero.InputDevice(objcfg.mux.input[3], True, None, None) self.input[4] = gpiozero.InputDevice(objcfg.mux.input[4], True, None, None) self.input[5] = gpiozero.InputDevice(objcfg.mux.input[5], True, None, None) self.input[6] = gpiozero.InputDevice(objcfg.mux.input[6], True, None, None) self.input[7] = gpiozero.InputDevice(objcfg.mux.input[7], True, None, None)
def main(): args = get_args() mic = gpiozero.InputDevice(args.port) vals = [] print(f"Recording #values: {args.num_values}") os.makedirs(args.folder, exist_ok=True) time_start = helper.get_timestamp() try: for _ in tqdm.tqdm(range(args.num_values)): vals.append(mic.value) time.sleep(args.sleep_time) except KeyboardInterrupt: # CTRL + C is catched pass finally: if len(vals) == 0: return time_end = helper.get_timestamp() filename = f'{args.folder}/recording_{time_start}.txt' print(f"Saving recording (filename: {filename})") with open(filename, 'w') as f: f.write(f"#{time_start},{time_end}\n") f.write('\n'.join(str(x) for x in vals))
def setup_cb(pin,mode): #print("pin=%d,status=%d" %(pin,) # do gpio setup if mode == "out": try: led = GPIO.LED(pin) self.add_digital_hw_pin(pin, None, gpioOut_h, led) logging.getLogger().debug(str(pin)+ str(mode)) except: pass if mode == "in": print(pull) if pull=="up": button = GPIO.DigitalInputDevice(pin, pullup=True) elif pull=="down": button = GPIO.DigitalInputDevice(pin, pullup=False) elif pull=="button": button = GPIO.Button(pin) else: button = GPIO.InputDevice(pin) self.add_digital_hw_pin(pin, gpioRead_h, None, button) # note the gpiozero button / led objects are payload as "state" logging.getLogger().debug(str(pin)+ str(mode))
def getDistance(): try: PIN_TRIGGER = generalSettings.distanceSensorPin_TRIGGER PIN_ECHO = generalSettings.distanceSensorPin_ECHO sensorOutput = gpiozero.OutputDevice(PIN_TRIGGER, active_high=True, initial_value=False) sensorInput = gpiozero.InputDevice(PIN_ECHO) sensorOutput.on() time.sleep(0.00001) sensorOutput.off() global pulse_start_time global pulse_end_time while not sensorInput.is_active: pulse_start_time = time.time() while sensorInput.is_active: pulse_end_time = time.time() pulse_duration = pulse_end_time - pulse_start_time distance = round(pulse_duration * 17150, 2) return distance finally: pass
def gpio_in(): input = gpiozero.InputDevice(7) try: if input.is_active(): return 'Auf' else: return "Zu" except: return 'Zu'
def __init__(self, pwmPin, forwardPin, backwardPin, encoderPin=None): ''' `forwardPin`: the motor rotate forward when this pin is on\n `backwardPin`: the motor rotate backward when this pin is on\n `encoderPin`: pin of motor's encoder phase A, default to None ''' self.pwmPin = gpiozero.OutputDevice(pwmPin) self.pwmPin.on() self.motor = gpiozero.Motor(forwardPin, backwardPin) if encoderPin is not None: self.encoderPin = gpiozero.InputDevice(encoderPin)
def __init__(self, pin, sensor_id, nickname, d_threshold, w_threshold, mode): self.sensor_reader = gpiozero.InputDevice(pin) self.nickname = nickname self.sensor_id = sensor_id self.d_threshold = d_threshold self.w_threshold = w_threshold self.mode = VH400SensorMode(mode) self.vwc = 0 # State variables self.state = VH400SensorState.startup self.prev_state = self.state
def __init__(self, *args, **kwargs): super(VentsLocker, self).__init__(*args, **kwargs) power_pin = self.config["power_pin"] limit_switch_pin = self.config["limit_switch_pin"] self.unlock_frequency = self.config["unlock_frequency"] self.unlock_falling_edge_delay = self.config[ "unlock_falling_edge_delay"] self.device = gpiozero.OutputDevice(power_pin) self.limit_switch_power = gpiozero.OutputDevice( self.config["limit_switch_power_pin"]) self.limit_switch_power.on() self.limit_switch = gpiozero.InputDevice(limit_switch_pin) self.locked = self.config["locked_by_default"] self.check_lock_mistake()
def main(): args = get_args() init_logging(args.log_level) clean_opts = helper.clean_args(args) logging.info(f'Options: {clean_opts}') notifications.init_notifications(args.telegram_bot_token, args.telegram_chat_id) notifications.send_notification(f'Starting to record with options: {clean_opts})') mic = gpiozero.InputDevice(args.port) q = collections.deque(maxlen=args.rolling_window_size) c = 0 while True: time.sleep(args.sleep_time) c = c + 1 q.append(mic.value) # Wait until rolling window is full if len(q) < args.rolling_window_size: continue # Only calculate average after "rolling_window_size" iterations to decrease load if c % args.rolling_window_size != 0: continue if helper.signal_detected(q, threshold=args.threshold): notifications.send_notification( f'Threshold was crossed! Rolling average: {helper.average(q)} (Threshold: {args.threshold})' ) logging.info(f'Signal detected: {helper.get_timestamp()}') q.clear() time.sleep(args.cool_down_in_s)
def read(self) -> int: if hasattr(self, "_output"): del self._output self._input = gp.InputDevice(self.pin, pull_up=True) return self._input.value
def __init__(self, dev_id: int, max_allowable_current: int, file_ID: str = None, target_freq: float = 200, do_read_fsrs: bool = False): '''Exo object is the primary interface with the Dephy ankle exos, and corresponds to a single physical exoboot. Args: dev_id: int. Unique integer to identify the exo in flexsea's library. Returned by connect_to_exo file_ID: str. Unique string added to filename. If None, no file will be saved. do_read_dsrs: bool indicating whether to read FSRs ''' self.dev_id = dev_id self.max_allowable_current = max_allowable_current self.file_ID = file_ID self.do_read_fsrs = do_read_fsrs if self.dev_id is None: print( 'Exo obj created but no exoboot connected. Some methods available' ) elif self.dev_id in constants.LEFT_EXO_DEV_IDS: self.side = constants.Side.LEFT self.motor_sign = -1 self.ankle_to_motor_angle_polynomial = constants.LEFT_ANKLE_TO_MOTOR self.ankle_angle_offset = constants.LEFT_ANKLE_ANGLE_OFFSET elif self.dev_id in constants.RIGHT_EXO_DEV_IDS: self.side = constants.Side.RIGHT self.motor_sign = 1 self.ankle_to_motor_angle_polynomial = constants.RIGHT_ANKLE_TO_MOTOR self.ankle_angle_offset = constants.RIGHT_ANKLE_ANGLE_OFFSET else: raise ValueError( 'dev_id: ', self.dev_id, 'not found in constants.LEFT_EXO_DEV_IDS or constants.RIGHT_EXO_DEV_IDS' ) self.motor_offset = 0 # ankle velocity filter is hardcoded for simplicity, but can be factored out if necessary self.ankle_velocity_filter = filters.Butterworth(N=2, Wn=10, fs=target_freq) if self.do_read_fsrs: print('do_read_fsrs: True. Checking if rpi') if fxu.is_pi() or fxu.is_pi64(): import gpiozero # pylint: disable=import-error if self.side == constants.Side.LEFT: self.heel_fsr_detector = gpiozero.InputDevice( pin=constants.LEFT_HEEL_FSR_PIN, pull_up=True) self.toe_fsr_detector = gpiozero.InputDevice( pin=constants.LEFT_TOE_FSR_PIN, pull_up=True) else: self.heel_fsr_detector = gpiozero.InputDevice( pin=constants.RIGHT_HEEL_FSR_PIN, pull_up=True) self.toe_fsr_detector = gpiozero.InputDevice( pin=constants.RIGHT_TOE_FSR_PIN, pull_up=True) else: raise Exception('Can only use FSRs with rapberry pi!') self.data = self.DataContainer(do_include_FSRs=do_read_fsrs) self.has_calibrated = False self.is_clipping = False if self.file_ID is not None: self.setup_data_writer(file_ID=file_ID) if self.dev_id is not None: self.update_gains(Kp=constants.DEFAULT_KP, Ki=constants.DEFAULT_KI, Kd=constants.DEFAULT_KD, k_val=0, b_val=0, ff=constants.DEFAULT_FF) self.TR_from_ankle_angle = interpolate.PchipInterpolator( constants.ANKLE_PTS, self.motor_sign * constants.TR_PTS)
fanRelay = gpiozero.OutputDevice(fanRelayPin, active_high=False, initial_value=True) plant1Relay = gpiozero.OutputDevice(plant1RelayPin, active_high=False, initial_value=True) plant2Relay = gpiozero.OutputDevice(plant2RelayPin, active_high=False, initial_value=True) plant3Relay = gpiozero.OutputDevice(plant3RelayPin, active_high=False, initial_value=True) hoseRelay = gpiozero.OutputDevice(hoseRelayPin, active_high=False, initial_value=True) floatSwitch = gpiozero.InputDevice(floatSwitchPin, active_state=None) #set DHT Device @ dhtPin dht_device = adafruit_dht.DHT11(dhtPin) #soil moisture device setup # Create an ADS1115 ADC (16-bit) instance. adc = Adafruit_ADS1x15.ADS1115() GAIN = 1 # Firebase Database Configuration config = { "apiKey": "AIzaSyAfAAQdELCHn_sVD14nKEh3DA2aKw7mJ-U", #----- Change to customize! ----- "authDomain": "egrow-20d1c.firebaseapp.com", #----- Change to customize! -----
def __init__(self, name, jack_port_pin): self.name = name self.jack_port = gpiozero.InputDevice(jack_port_pin)
abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) os.chdir(dname) pygame.init() #pygame.display.set_mode((100, 100)) pygame.mixer.init(48000, -16, 2, 1024) pygame.mixer.music.load("Phone.mp3") #pygame.mixer.music.play() #time.sleep(5) #pygame.mixer.music.stop() #Dictionary containing the file strings and the length of that audio file in seconds# receiverInput = gpiozero.InputDevice(27, pull_up=True) receiverOutput = gpiozero.OutputDevice(17, initial_value=False) matInput = gpiozero.InputDevice(22, pull_up=True) matOutput = gpiozero.OutputDevice(23, initial_value=False) previouslyChosen = 0 audioFiles = [("only-2-socks.mp3", 12), ("struggle-different-culture.mp3", 36), ("housebound.mp3", 44), ("invisible-illness.mp3", 43), ("using-PAs.mp3", 30), ("cultural-pressures.mp3", 61), ("depression.mp3", 30), ("hoarding genes.mp3", 21), ("disabled-fear-of-judgement.mp3", 82), ("hoarding-fire.mp3", 135), ("no-water-washing.mp3", 70)] #audioObjects = [pygame.mixer.Sound(file) for file in audioFiles] pygame.mixer.music.load("beep.mp3") pygame.mixer.music.play() def idle(): while True: if(matInput.value and not receiverInput.value):
#!/usr/bin/python3 import gpiozero as GPIO import time inpin = GPIO.InputDevice(4, pull_up=False) outpin = GPIO.OutputDevice(17, active_high=True, initial_value=False) print('Input initially measures: ' + str(inpin.is_active)) print('Turning on the Output...') outpin.on() print('Input now measures: ' + str(inpin.is_active))
import gpiozero import time import random in_clock = gpiozero.InputDevice(23) in_data = gpiozero.InputDevice(24) out_clock = gpiozero.OutputDevice(25) out_data = gpiozero.OutputDevice(8) timeout = 0.1 #s def read_string(): status = in_clock.value next_timeout = time.clock() + timeout data = [0] * 100000 data_size = 0 while True: new_status = in_clock.value new_time = time.clock() if new_status != status: next_timeout = new_time + timeout status = new_status data[data_size] = in_data.value data_size += 1 elif new_time > next_timeout: if data_size != 0: return decode_buffer(data, data_size)
def __init__(self, send: List[int], recv: List[int], pull_up=True): self.data = np.full((len(send), len(recv)), False) self.send = [gp.OutputDevice(pin) for pin in send] self.recv = [gp.InputDevice(pin, pull_up=pull_up) for pin in recv]
def __init__(self, pin, name, beetle): self.pin = gpiozero.InputDevice(pin, pull_up=True) beetle.state.set(name, self.pin.value)
import pyrebase import gpiozero import time trigger = gpiozero.OutputDevice(14) echo = gpiozero.InputDevice(15) config = { "authDomain": "iot-2020umng.firebaseapp.com", "databaseURL": "https://iot-2020umng.firebaseio.com/", "apiKey": "TPAksSAwOnNnGAD445el8lQDGpglK7Ntr204QOtu", "storageBucket": "", } KEY_PATH = "/Goldberg/moduloB" DIST_FOR_TRIGGER = 10 # cm def main(): firebase = pyrebase.initialize_app(config) database = firebase.database() finished = False while not finished: print("starting") trigger.value = False time.sleep(0.1) trigger.value = True start_time = time.clock() waiting = True timeout = False
# pin 3 = output # |SPI |1 Bit |4 Bit # strand 2 == microsd 1 |N/A |N/A |SD Serial Data 2 # strand 4 == microsd 2 |SPI Card Select|Card Detection |SD Serial Data 3 # strand 6 == microsd 3 |MOSI |Command/Response |Command/Response # strand 8 == microsd 4 |Power |Power |Power # strand 10 == microsd 5 |SCLK |Serial Clock |Serial Clock # strand 11 == microsd 6 |Ground |Ground |Ground # strand 12 == microsd 7 |MISO |SD Serial Data 0 |SD Serial Data 0 # strand 14 == microsd 8 |N/A |N/A |SD Serial Data 1 with \ gpiozero.InputDevice(16) as pin16, \ gpiozero.InputDevice(19) as pin19, \ gpiozero.InputDevice(20) as pin20, \ gpiozero.InputDevice(21) as pin21, \ gpiozero.InputDevice(26) as pin26,\ gpiozero.OutputDevice(3) as pinout: pinout.on() while True: print("16:19:20:21:26") print("{} :{} :{} :{} :{}".format(1 if pin16.value else 0, 1 if pin19.value else 0, 1 if pin20.value else 0, 1 if pin21.value else 0, 1 if pin26.value else 0))
def getSensor5(): sensorInput = gpiozero.InputDevice( generalSettings.infraredSensorPins[4]) return sensorInput.is_active
#!/usr/bin/python3 import gpiozero import time input = 18 ip = gpiozero.InputDevice(input, True) if ip.value: print("Input ", input, " detected.") else: print("Input ", input, " not detected.")