class Servo: def __init__(self, pin, min_pulse=1, max_pulse=2, frequency=50): self.debug = DebugMessages(self) self.min_pulse = min_pulse self.max_pulse = max_pulse self.mid_pulse = (min_pulse + max_pulse) / 2 self.looping = True self.pin = GPIO(pin, "out") self.frequency = frequency self.millis = self.mid_pulse self.old_millis = -1 self.thread = threading.Thread(target=self.loop, args=()) self.thread.start() def __del__(self): self.looping = False # self.debug.info(str(self.looping)) def loop(self): while self.looping: # self.debug.info(str(self.looping)) self.pin.write(True) time.sleep(self.millis / 1000) self.pin.write(False) time.sleep(((1000 / self.frequency) - self.millis) / 1000) self.old_millis = self.millis def set_angle(self, angle): if 180 >= angle >= 0: self.millis = ((angle - 90) / 90) * (self.mid_pulse - self.min_pulse) + self.mid_pulse else: raise ValueError("Angle out of bounds!")
class Leds: leds = [GPIO(0, "out"), GPIO(1, "out")] period = 0.2 frequency = 1 thread = [] def __init__(self): self.thread = threading.Thread(target=self.background, args=(self, )) self.thread.start() def enable(self): for led in self.leds: led.write(True) def disable(self): for led in self.leds: led.write(False) def toggle(self): for led in self.leds: value = led.read() led.write(not value) def set_frequency(self, value): self.frequency = value def background(self, val): while True: self.enable() time.sleep(self.period) self.disable() time.sleep(self.frequency - self.period)
def __init__(self, clk, dio): self.clk = clk self.dio = dio self.brightness = 0x0f self.gpio_clk = GPIO(self.clk, "out") self.gpio_dio = GPIO(self.dio, "out")
def init(self, mode=IN, pull=None): """Initialize the Pin""" if mode is not None: if mode == self.IN: self._mode = self.IN if self._line is not None: self._line.close() self._line = GPIO(self._chippath, int(self._num), self.IN) elif mode == self.OUT: self._mode = self.OUT if self._line is not None: self._line.close() self._line = GPIO(self._chippath, int(self._num), self.OUT) else: raise RuntimeError("Invalid mode for pin: %s" % self.id) if pull is not None: if pull == self.PULL_UP: raise NotImplementedError( "Internal pullups not supported in periphery, " "use physical resistor instead!" ) if pull == self.PULL_DOWN: raise NotImplementedError( "Internal pulldowns not supported in periphery, " "use physical resistor instead!" ) raise RuntimeError("Invalid pull for pin: %s" % self.id)
class InterruptButton(threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.gpio_CynexoFrontButton = GPIO("/dev/gpiochip4", 12, "in") self.gpio_CynexoFrontButton.edge = "falling" self.threadID = threadID self.name = name def play(self, data, periodsize, device, f): #Leggi e suona while data: device.write(data) data = f.readframes(periodsize) def run(self): f = wave.open(args[0], 'rb') periodsize = f.getframerate() // 8 device = alsaaudio.PCM() while(True): #Prebuffering data = f.readframes(periodsize) #Interrupt print("Interrupt Button:") self.gpio_CynexoFrontButton.read_event() #Play self.play(data, periodsize, device, f) f.close() f = wave.open(args[0], 'rb')
class PERIPHERY: """ peripheryパッケージを使用するGPIOピンの基底クラス。 """ def __init__(self, pin, mode=None, debug=False): """ GPIOオブジェクトを生成し、インスタンス変数へ格納する。 引数: pin int GPIOピン番号 debug boolean デバッグフラグ、デフォルトはFalse """ self.debug = debug self.pin = pin if mode != IN and mode != OUT and mode != PWM: raise ValueError('[PERIPHERY] unsupported mode: {}'.format(str(mode))) self.mode = mode try: from periphery import GPIO except ImportError: exit('[PERIPHERY] This code requires periphery package') if (pin == 73 or pin== 77) and mode != OUT: raise ValueError('[PERIPHERY] GPIO73 and GPIO77 currently support only the "out" direction.') if mode != PWM: self.gpio = GPIO(pin, mode) else: self.gpio = None if self.debug: print('[PERIPHERY] set pin:{} mode:{}'.format(str(pin), str(mode))) def shutdown(self): self.gpio.close()
def read_GPIOLIST(): for num in range(7): gpio_in = GPIO(GPIO_num_list[num]) GPIO_directon_list[num] = gpio_in.direction GPIO_value_list[num] = gpio_in.read() gpio_in.close() return GPIO_name_list, GPIO_directon_list, GPIO_value_list
def __init__(self, gpio_pin=None): threading.Thread.__init__(self) self._is_gpio = gpio_pin is not None if self._is_gpio: self._gpio = GPIO(gpio_pin, 'in') self._lock = threading.Lock() self._is_key_pressed = False self._last_key_pressed_time = time.monotonic()
def ledOn(gpiochip, pin): try: led = GPIO(gpiochip, pin, "out") led.write(True) except TypeError as e: print('{}'.format(e)) except LookupError: print('GPIO line was not found by the provided name') except: print('unknown error occurred')
def __init__(self, port, enable_pin=None, reset_pin=None): self.port = Serial(port, 9600) self.gpio_enable = None self.gpio_reset = None self.stop = Event() # suspend sensor by default if enable_pin: self.gpio_enable = GPIO(enable_pin, "low") if reset_pin: self.gpio_reset = GPIO(reset_pin, "high")
def __init__(self, pin, min_pulse=1, max_pulse=2, frequency=50): self.debug = DebugMessages(self) self.min_pulse = min_pulse self.max_pulse = max_pulse self.mid_pulse = (min_pulse + max_pulse) / 2 self.looping = True self.pin = GPIO(pin, "out") self.frequency = frequency self.millis = self.mid_pulse self.old_millis = -1 self.thread = threading.Thread(target=self.loop, args=()) self.thread.start()
def __init__(self): super(pumps, self).__init__() self.raspberry = GPIO(23, "out") self.raspberry.write(True) self.currant = GPIO(24, "out") self.currant.write(True) self.raspberry_counter = 0 self.currant_counter = 0 self.raspberry_state = False self.currant_state = False if not os.path.isfile('status.yaml'): self.store_yaml() self.read_yaml()
def start(self): # Open spidev0.0 device with mode 0 and max speed 100 kHz if (self.spi is None): self.spi = SPI("/dev/spidev0.0", 0, 30000) #, bit_order= "lsb") # Open GPIO pin connection if (self.signal_pin is None): self.signal_pin = GPIO(6, "in") if (self.comm_thread is None): print("starting comms thread") self.comm_thread = threading.Thread(target=self._comm_thread_fn, daemon=True) self.comm_thread.start()
def __init__( self, ss_pin=7, # 1 cdone_pin=22, creset_pin=27, speed=1e6, spidev_path="/dev/spidev0.1", ): self.spidev = SpiDev(spidev_path, self.MODE, speed) super().__init__(ss_pin, cdone_pin, creset_pin, self.spidev) # HACK: reset FPGA 1 self.flash_switch = GPIO(17, "out") self.flash_switch.write(False)
class pumps(Thread): def __init__(self): super(pumps, self).__init__() self.raspberry = GPIO(23, "out") self.raspberry.write(True) self.currant = GPIO(24, "out") self.currant.write(True) self.raspberry_counter = 0 self.currant_counter = 0 self.raspberry_state = False self.currant_state = False if not os.path.isfile('status.yaml'): self.store_yaml() self.read_yaml() def read_yaml(self): with open('status.yaml', 'r') as f: try: y = yaml.safe_load(f) self.raspberry_counter = int(y['raspberry_water']) self.currant_counter = int(y['currant_water']) except yaml.YAMLError as exception: print(exception) def store_yaml(self): with open('status.yaml', 'w') as f: yaml.dump( { 'raspberry_water': int(self.raspberry_counter), 'currant_water': int(self.currant_counter) }, f, default_flow_style=False) def increase_counter(self): if self.raspberry_state: self.raspberry_counter += 1 if self.currant_state: self.currant_counter += 1 if self.raspberry_state or self.currant_state: self.store_yaml() def get_counter_raspberry(self): return self.raspberry_counter def get_counter_currant(self): return self.currant_counter def set(self, pump, state=False): if pump == "raspberry": self.raspberry_state = state self.raspberry.write(not state) elif pump == "currant": self.currant_state = state self.currant.write(not state) def run(self): while True: self.increase_counter() time.sleep(1)
def targetpower(on, voltage): if not voltage: voltage = 3.0 else: if not on: raise click.UsageError( "Can't set voltage, when LDO is switched off") for pin_name in ["en_v_anlg", "en_lvl_cnv", "load"]: pin = GPIO(gpio_pin_nums[pin_name], "out") pin.write(on) with VariableLDO() as ldo: if on: ldo.set_voltage(voltage) ldo.set_output(on)
def play(device, f): periodsize = f.getframerate() // 8 device = alsaaudio.PCM() #Aspetta per farlo partire data = f.readframes(periodsize) #Prebuffering #Polling gpio4_12 = GPIO("/dev/gpiochip4", 12, "in") while (gpio4_12.read() == True): a = None #Leggi e suona while data: device.write(data) data = f.readframes(periodsize)
def __init__(self, bus_num: int = 2, address: int = 0x54, wp_pin: int = 49): """Initializes EEPROM by bus number and address. Args: bus_num (int): I2C bus number, e.g. 1 for I2C1 on BeagleBone address (int): Address of EEPROM, usually fixed in hardware or by DIP switch """ self.dev_path = (f"/sys/bus/i2c/devices/{ bus_num }" f"-{address:04X}/eeprom") self._write_protect_pin = GPIO(wp_pin, "out") self._write_protect_pin.write(True)
class WaterDetector(Sensor): """ water detector driver """ def __init__(self, gpio_pin): self._gpio_pin = gpio_pin self._gpio = None self._is_connected = False def connect(self): self._gpio = GPIO(self._gpio_pin, "in") self._is_connected = True return True def disconnect(self): self._is_connected = False self._gpio = None return True def is_connected(self): return self._is_connected def is_water_full(self): """ Returns: bool: return True if detect water full, otherwise return False """ return self._gpio.read()
class example2(config): # TODO: ss_pin should be 7 for rework def __init__( self, ss_pin=7, # 1 cdone_pin=22, creset_pin=27, speed=1e6, spidev_path="/dev/spidev0.1", ): self.spidev = SpiDev(spidev_path, self.MODE, speed) super().__init__(ss_pin, cdone_pin, creset_pin, self.spidev) # HACK: reset FPGA 1 self.flash_switch = GPIO(17, "out") self.flash_switch.write(False)
def read(self, pin): """Read bool value from a pin. Args: pin (int): the pin to read from Return: bool: value of digital pin reading """ with self._gpio_lock: gpio_pin = GPIO(pin, "in") value = gpio_pin.read() gpio_pin.close() self.logger.debug("Read value from GPIO pin {}: {}".format( pin, value)) return bool(value)
def __init__(self): global GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm try: self._LEDs = [GPIO(86, "out"), initPWM(1), initPWM(0), GPIO(140, "out"), initPWM(2)] self._buttons = [GPIO(141, "in"), GPIO(8, "in"), GPIO(7, "in"), GPIO(138, "in"), GPIO(6, "in")] except GPIOError as e: print("Unable to access GPIO pins. Did you run with sudo ?") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__()
def __init__(self): """ GPIO info: https://coral.ai/docs/dev-board/gpio/. Establish input and output pins of the DevBoard. Establish bluetooth connection with GM-10 Bluetooth Module to communicate with an Arduino """ global GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): """ Sets a pin to PWM """ pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm def initBluetooth(bd_addr, port): """ Establish bluetooth socket connection with DSD TECH HM-10 Bluetooth Module """ bluetooth_socket = None try: bluetooth_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) bluetooth_socket.connect((bd_addr,port)) except bluetooth.btcommon.BluetoothError as message: print(message) if bluetooth_socket: bluetooth_socket.send('</CLEAN/>') bluetooth_socket.close() finally: return bluetooth_socket try: self._OUTPUTS = [GPIO(140, 'out'), ] self._INPUTS = [GPIO(141, 'in'), ] self._bd_addr = BLUETOOTH_MODULE_ADDRESS self._bd_port = BLUETOOTH_MODULE_PORT self._bluetooth_socket = None self._bluetooth_socket = initBluetooth(self._bd_addr, self._bd_port) except GPIOError as e: print("Unable to access GPIO pins. Try running with sudo") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__()
def __init__( self, ss_pin=8, cdone_pin=4, creset_pin=17, speed=1e6, spidev_path="/dev/spidev0.0", ): self.spidev = SpiDev(spidev_path, self.MODE, speed) super().__init__(ss_pin, cdone_pin, creset_pin, self.spidev) # set SPI switch for FPGA to be SPI slave self.flash_switch = GPIO(5, "out") self.flash_switch.write(False) # HACK: reset FPGA 2 self.flash_switch = GPIO(27, "out") self.flash_switch.write(False)
def __enter__(self): self.gpio_led = GPIO(self.pin_led, "out") self.gpio_button = GPIO(self.pin_button, "in") self.gpio_button.edge = "falling" logger.debug("configured gpio") sysbus = dbus.SystemBus() systemd1 = sysbus.get_object("org.freedesktop.systemd1", "/org/freedesktop/systemd1") self.manager = dbus.Interface(systemd1, "org.freedesktop.systemd1.Manager") shepherd_object = self.manager.LoadUnit( f"{ self.service_name }.service") self.shepherd_proxy = sysbus.get_object("org.freedesktop.systemd1", str(shepherd_object)) logger.debug("configured dbus for systemd") return self
def __init__(self): """ GPIO info: https://coral.ai/docs/dev-board/gpio/ """ global GPIO, PWM from periphery import GPIO, PWM, GPIOError def initPWM(pin): pwm = PWM(pin, 0) pwm.frequency = 1e3 pwm.duty_cycle = 0 pwm.enable() return pwm #def initBluetooth(bd_addr, port): # bluetooth_socket = None # try: # bluetooth_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM) # bluetooth_socket.connect((bd_addr,port)) # except bluetooth.btcommon.BluetoothError as message: # print(message) # if bluetooth_socket: # bluetooth_socket.send('0') # bluetooth_socket.close() # finally: # return bluetooth_socket try: self._OUTPUTS = [ GPIO(140, 'out'), ] self._INPUTS = [ GPIO(141, 'in'), ] self._bd_addr = BLUETOOTH_MODULE_ADDRESS self._bd_port = BLUETOOTH_MODULE_PORT self._bluetooth_socket = None #self._bluetooth_socket = initBluetooth(self._bd_addr, self._bd_port) except GPIOError as e: print("Unable to access GPIO pins. Try running with sudo") sys.exit(1) super(UI_EdgeTpuDevBoard, self).__init__()
def __init__(self): """Initializes relevant variables. Args: """ for name, pin in target_pin_nums.items(): self.gpios[name] = GPIO(pin, "out") self.pin_names = list(target_pin_nums.keys()) self.pin_count = len(self.pin_names)
def __enter__(self): try: for name, pin in gpio_pin_nums.items(): self.gpios[name] = GPIO(pin, "out") self._set_shepherd_pcb_power(True) self.set_target_io_level_conv(False) logger.debug("Shepherd hardware is powered up") # If shepherd hasn't been terminated properly if sysfs_interface.get_state() != "idle": sysfs_interface.set_stop() sysfs_interface.wait_for_state("idle", 5) logger.debug(f"Switching to '{ self.mode }'-mode") sysfs_interface.write_mode(self.mode) # clean up msg-channel provided by kernel module self._flush_msgs() # Ask PRU for base address of shared mem (reserved with remoteproc) mem_address = sysfs_interface.get_mem_address() # Ask PRU for size of shared memory (reserved with remoteproc) mem_size = sysfs_interface.get_mem_size() logger.debug( f"Shared memory address: \t0x{mem_address:08X}, size: {mem_size} byte" ) # Ask PRU for size of individual buffers samples_per_buffer = sysfs_interface.get_samples_per_buffer() logger.debug(f"Samples per buffer: \t{ samples_per_buffer }") self.n_buffers = sysfs_interface.get_n_buffers() logger.debug(f"Number of buffers: \t{ self.n_buffers }") self.buffer_period_ns = sysfs_interface.get_buffer_period_ns() logger.debug(f"Buffer period: \t\t{ self.buffer_period_ns } ns") self.shared_mem = SharedMem( mem_address, mem_size, self.n_buffers, samples_per_buffer ) self.shared_mem.__enter__() except Exception: self._cleanup() raise sysfs_interface.wait_for_state("idle", 3) return self
def __init__(self, threadID, name): threading.Thread.__init__(self) self.gpio_green = GPIO("/dev/gpiochip1", 24, "out") self.gpio_red = GPIO("/dev/gpiochip1", 25, "out") self.gpio_blue = GPIO("/dev/gpiochip2", 23, "out") self.threadID = threadID self.name = name
def pull_up(pin, time): # Open GPIO 6 with output direction gpio_out = GPIO(pin, "out") # dispense some beans gpio_out.write(True) # This needs to be calibrated depending # on dispenser speed. time.sleep(time) # Stop spitting out beans gpio_out.write(False) gpio_out.close()
class Relay(): def __init__(self, pin): rospy.loginfo("Initializing relay") self.pin = pin self.gpio_out = GPIO(self.pin, "out") self.gpio_out.write(True) # initialize relay to be OFF def __exit__(self): self.gpio_out.close() def set(self, state): try: if state: rospy.loginfo("Turning ON relay") self.gpio_out.write(False) # active low else: rospy.loginfo("Turning OFF relay") self.gpio_out.write(True) except Exception as e: rospy.logwarn("Unable to set relay. Error: {}".format(e))
def read_analog_sensor(self): """ Reads the Sump Pump sensor. :return: Distance to Sump Pump water. :rtype: float """ trig=GPIO(23, 'out') echo=GPIO(24, 'in') # Pulse to trigger sensor trig.write(False) time.sleep(0.00001) trig.write(True) time.sleep(0.00001) trig.write(False) while echo.read()==False: pulse_start=time.time() while echo.read()==True: pulse_end= time.time() pulse_duration=pulse_end-pulse_start # Quick explaination of the formula: # The pulse duration is to the object and back, so the # distance is one half of the pulse duration. The speed of # sound in air is 340 meters/second. There are 100 centimeters # in a meter. distance=pulse_duration*340/2*100 distance=round(distance, 2) trig.close() echo.close() return distance
## GPIO test for Raspberry Pi # import pin controller from periphery import GPIO import time # Open GPIO 6 with output direction gpio_out = GPIO(6, "out") gpio_out.write(True) # sleep for 5 seconds time.sleep(5) gpio_out.write(False) gpio_out.close()
#!/usr/bin/python from periphery import GPIO import time # pinNum = 135; for Artik 5 pinNum = 22; #for Artik 10 LED = GPIO(pinNum, "out") while True: LED.write(True) time.sleep(1) LED.write(False) time.sleep(1)
def __init__(self, pin): rospy.loginfo("Initializing relay") self.pin = pin self.gpio_out = GPIO(self.pin, "out") self.gpio_out.write(True) # initialize relay to be OFF