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!")
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-m', '--model', required=True, help='File path of .tflite file.') parser.add_argument('-i', '--input', required=True, help='Image to be classified.') parser.add_argument('-l', '--labels', help='File path of labels file.') parser.add_argument('-k', '--top_k', type=int, default=1, help='Max number of classification results') parser.add_argument('-t', '--threshold', type=float, default=0.0, help='Classification score threshold') parser.add_argument('-c', '--count', type=int, default=5, help='Number of times to run inference') args = parser.parse_args() labels = read_label_file(args.labels) if args.labels else {} interpreter = make_interpreter(*args.model.split('@')) interpreter.allocate_tensors() _, height, width = interpreter.get_input_details()[0]['shape'] size = [height, width] image = Image.open(args.input).resize(size, Image.ANTIALIAS) common.set_input(interpreter, image) trigger = GPIO("/dev/gpiochip2", 13, "out") # pin 37 print('----INFERENCE TIME----') print('Note: The first inference on Edge TPU is slow because it includes', 'loading the model into Edge TPU memory.') #for _ in range(args.count): while (1): start = time.perf_counter() trigger.write(True) time.sleep(0.0005) trigger.write(False) #interpreter.invoke() inference_time = time.perf_counter() - start #classes = classify.get_classes(interpreter, args.top_k, args.threshold) print('%.1fms' % (inference_time * 1000)) print('-------RESULTS--------') for c in classes: print('%s: %.5f' % (labels.get(c.id, c.id), c.score))
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 write_GPIO(num, direction, val): # 1 == OUT, 0 == IN if direction == 1: gpio_out = GPIO(GPIO_num_list[num], "out") gpio_out.write(val) gpio_out.close() elif direction == 0: gpio_in = GPIO(GPIO_num_list[num], "in") gpio_in.close() else: gpio_in = GPIO(GPIO_num_list[num], "in") gpio_in.close()
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-m', '--model', required=True, help='File path of .tflite file.') parser.add_argument('-i', '--input', help='Image to be classified.') parser.add_argument('-l', '--labels', help='File path of labels file.') parser.add_argument('-k', '--top_k', type=int, default=1, help='Max number of classification results') parser.add_argument('-t', '--threshold', type=float, default=0.0, help='Classification score threshold') parser.add_argument('-c', '--count', type=int, default=5, help='Number of times to run inference') args = parser.parse_args() labels = read_label_file(args.labels) if args.labels else {} interpreter = make_interpreter(*args.model.split('@')) interpreter.allocate_tensors() _, height, width = interpreter.get_input_details()[0]['shape'] size = [height, width] trigger = GPIO("/dev/gpiochip2", 13, "out") # pin 37 print('----INFERENCE TIME----') print('Note: The first inference on Edge TPU is slow because it includes', 'loading the model into Edge TPU memory.') #for i in range(1,351): while 1: #input_image_name = "./testSample/img_"+ str(i) + ".jpg" #input_image_name = "./testSample/img_1.jpg" #image = Image.open(input_image_name).resize(size, Image.ANTIALIAS) arr = numpy.random.randint(0,255,(28,28), dtype='uint8') image = Image.fromarray(arr, 'L').resize(size, Image.ANTIALIAS) common.set_input(interpreter, image) start = time.perf_counter() trigger.write(True) interpreter.invoke() trigger.write(False) inference_time = time.perf_counter() - start print('%.6fms' % (inference_time * 1000)) classes = classify.get_classes(interpreter, args.top_k, args.threshold) print('RESULTS for image ', 1) for c in classes: print('%s: %.6f' % (labels.get(c.id, c.id), c.score))
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 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 aux_target_power(on: bool, voltage: float, sel_target_for_aux: bool): if not voltage: voltage = 3.0 else: if not on: raise click.UsageError( "Can't set voltage, when Shepherd is switched off") for pin_name in ["en_shepherd"]: pin = GPIO(gpio_pin_nums[pin_name], "out") pin.write(on) for pin_name in ["target_pwr_sel"]: pin = GPIO(gpio_pin_nums[pin_name], "out") pin.write(not sel_target_for_aux) cal = CalibrationData.from_default() sysfs_interface.write_dac_aux_voltage(cal, voltage)
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 _select_spi_slave(name): """Sets GPIO output in order to be able to speak with that SPI slave later. @param name: _KNOWN_SPI_SLAVES key. """ for pin, output_value in _KNOWN_SPI_SLAVES[name]['gpio'].items(): for attempt in [1, 0]: try: gpio_out = GPIO(pin, 'out') except GPIOError as e: if not attempt or e.errno != errno.EACCES: raise print('Warning, opening GPIO pin failed, retrying...') time.sleep(.5) gpio_out.write(output_value) gpio_out.close()
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)
class VariableLDO(object): """Driver for DAC controlled LDO regulator The shepherd cape hosts a linear voltage regulator, that can be used to 1) power a sensor node with a constant, but configurable voltage 2) pre-charge the capacitor before starting recording/emulation The circuit consists of a TI TPS73101 LDO and a TI DAC6571 DAC. The DAC is connected to the feedback pin of the LDO and biases the current from the output pin, effectively controlling the output voltage of the LDO. """ def __init__(self): self.dac = DAC6571() def __enter__(self, *args): self.enable_pin = GPIO(PIN_LDO_ENABLE, "out") self.enable_pin.write(False) self.dac.__enter__() return self def __exit__(self, *args): self.dac.__exit__() self.enable_pin.close() def set_output(self, state: bool): """Enables or disables LDO Args: state (bool): True to enable LDO, False to disable """ if not state: self.dac.set_voltage(0.0) self.enable_pin.write(state) def set_voltage(self, voltage: float): """Sets the voltage on the output of the LDO Args: voltage (float): Voltage in volt. Must be between 1.6V and 3.6V due to hardware limitations. """ if voltage > 3.6 or voltage < 1.6: raise ValueError("Fixed voltage must be between 1.6V and 3.6V") v_dac = V_FB_LDO - R24 * ((voltage - V_FB_LDO) / R25 - V_FB_LDO / R26) self.dac.set_voltage(v_dac)
class example1(config): 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)
class UserInputs(object): """Tests that values can be written and read from a GPIO pin""" def __init__(self, logging): self.gpio = None if isinstance(self, UserInputOne): self.gpio = GPIO(pin=85, direction=OUT) elif isinstance(self, UserInputTwo): self.gpio = GPIO(pin=86, direction=OUT) elif isinstance(self, UserInputThree): self.gpio = GPIO(pin=90, direction=OUT) self.logging = logging def test_high(self): """Tests that high values can be written and read from the GPIO pin""" return self._test(True) def test_low(self): """Tests that low values can be written and read from the GPIO pin""" return self._test(False) def _test(self, level): try: self.gpio.write(level) logging.debug("Value written") val = self.gpio.read() if val is level: self.logging.debug("Value read is the one same as the one written") return True else: message = "Value read is different to the one written: " + str(val) + " != " + str(level) self.logging.fatal() return False except Exception as ex: self.logging.fatal(ex) return False
class config(object): DONE_ITS = 100 CHUNK = 4 * 1024 DELAY = 10e-3 MODE = 3 def __init__(self, ss_pin, cdone_pin, creset_pin, spidev): self.ss = GPIO(ss_pin, "out") self.cdone = GPIO(cdone_pin, "in") self.creset = GPIO(creset_pin, "out") self.spidev = spidev def sleep(self): time.sleep(self.DELAY) def set_ss(self, val): self.ss.write(val) def reset(self, val): if val: self.creset.write(False) else: self.creset.write(True) def wait_done(self): done = 0 cnt = 0 while done == 0 and cnt < self.DONE_ITS: self.sleep() done = self.cdone.read() cnt += 1 return done def sram_config(self, image): self.reset(True) self.sleep() self.set_ss(False) self.sleep() self.reset(False) self.sleep() for i in range(0, len(image), self.CHUNK): self.spidev.transfer(image[i:i + self.CHUNK]) # extra 49 bits self.spidev.transfer(7 * [0])
class CynexoGPIO(): def __init__(self): self.gpio_FBtn = GPIO("/dev/gpiochip4", 12, "in") self.gpio_FBtn.edge = "falling" self.gpio_green = GPIO("/dev/gpiochip1", 24, "out") self.gpio_red = GPIO("/dev/gpiochip1", 25, "out") self.gpio_blue = GPIO("/dev/gpiochip2", 23, "out") def close(self): self.gpio_green.write(False) self.gpio_red.write(False) self.gpio_blue.write(False) self.gpio_FBtn.close() self.gpio_green.close() self.gpio_red.close() self.gpio_blue.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
# Toggle LED through GPIO function # Author: Peter Mankowski from periphery import GPIO import time # GPIO init gpio = GPIO(138, "low") # Parameters declarations count = 0 How_many_counts = 4 sleep_del = 0.1 """ gpio.write(True) time.sleep(1) """ # Toggle GPIO feature while (count < How_many_counts): count = count + 1 value = gpio.read() gpio.write(not value) time.sleep(sleep_del) gpio.close()
#! /usr/bin/python3 # LED Wiring to GPIO # Power: Pin 1 # Ground: Pin 6 # Signal: Pin 18 from periphery import GPIO import time gpio = GPIO(138, "out") gpio.write(True) time.sleep(1) gpio.write(False) time.sleep(1) gpio.write(True) time.sleep(1) gpio.write(False) time.sleep(1) gpio.write(True) time.sleep(1) gpio.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)
from periphery import GPIO import time import signal import sys flag = True def handler(signal, frame): global flag print('handler') flag = False signal.signal(signal.SIGINT, handler) # Open GPIO 125 with input direction gpio_in = GPIO(125, "in") # Open GPIO 126 with output direction gpio_out = GPIO(126, "out") while flag: value = gpio_in.read() print value gpio_out.write(value) time.sleep(1.0) gpio_out.write(False) gpio_in.close() gpio_out.close()
"""Digital IO (Output) using periphery""" import time from periphery import GPIO # 根据具体板卡的LED灯连接修改使用的Chip和Line LED_CHIP = "/dev/gpiochip3" LED_LINE_OFFSET = 19 led = GPIO(LED_CHIP, LED_LINE_OFFSET, "out") try: while True: led.write(False) time.sleep(0.1) led.write(True) time.sleep(0.1) finally: led.write(True) led.close()
class EEPROM(object): """Represents EEPROM device Convenient wrapper of Linux I2C EEPROM device. Knows about the format of the shepherd EEPROM info, including Beaglebone cape data and shepherd calibration data. """ _write_protect_pin: GPIO = None 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) def __enter__(self): self.fd = os.open(self.dev_path, os.O_RDWR | os.O_SYNC) return self def __exit__(self, *args): os.close(self.fd) def _read(self, address: int, n_bytes: int) -> bytes: """Reads a given number of bytes from given address. Args: address (int): Start address for read operation n_bytes (int): Number of bytes to read from address """ os.lseek(self.fd, address, 0) return os.read(self.fd, n_bytes) def _write(self, address: int, buffer: bytes) -> NoReturn: """Writes binary data from byte buffer to given address. Args: address (int): Start address for write operation buffer (bytes): Binary data to write Raises: TimeoutError: If write operation times out """ self._write_protect_pin.write(False) os.lseek(self.fd, address, 0) try: os.write(self.fd, buffer) except TimeoutError: logger.error( "Timeout writing to EEPROM. Is write protection disabled?") raise self._write_protect_pin.write(True) def __getitem__(self, key): """Retrieves attribute from EEPROM. Args: key (str): Name of requested attribute Raises: KeyError: If key is not a valid attribute """ if key not in eeprom_format.keys(): raise KeyError(f"{ key } is not a valid EEPROM parameter") raw_data = self._read(eeprom_format[key]["offset"], eeprom_format[key]["size"]) if eeprom_format[key]["type"] == "ascii": return raw_data.decode("utf-8") if eeprom_format[key]["type"] == "str": str_data = raw_data.split(b"\x00") return str_data[0].decode("utf-8") else: return raw_data def __setitem__(self, key: str, value): """Writes attribute to EEPROM. Args: key (str): Name of the attribute value: Value of the attribute Raises: KeyError: If key is not a valid attribute ValueError: If value does not meet specification of corresponding attribute """ if key not in eeprom_format.keys(): raise KeyError(f"{ key } is not a valid EEPROM parameter") if eeprom_format[key]["type"] == "ascii": if len(value) != eeprom_format[key]["size"]: raise ValueError( (f"Value { value } has wrong size. " f"Required size is { eeprom_format[key]['size'] }")) self._write(eeprom_format[key]["offset"], value.encode("utf-8")) elif eeprom_format[key]["type"] == "str": if len(value) < eeprom_format[key]["size"]: value += "\0" elif len(value) > eeprom_format[key]["size"]: raise ValueError((f"Value { value } is longer than maximum " f"size { eeprom_format[key]['size'] }")) self._write(eeprom_format[key]["offset"], value.encode("utf-8")) else: self._write(eeprom_format[key]["offset"], value) def write_cape_data(self, cape_data: CapeData) -> NoReturn: """Writes complete BeagleBone cape data to EEPROM Args: cape_data (CapeData): Cape data that should be written """ for key, value in cape_data.items(): self[key] = value def read_cape_data(self) -> CapeData: """Reads and returns BeagleBone cape data from EEPROM Returns: CapeData object containing data extracted from EEPROM """ data = dict() for key in eeprom_format.keys(): data[key] = self[key] return CapeData(data) def write_calibration(self, calibration_data: CalibrationData) -> NoReturn: """Writes complete BeagleBone cape data to EEPROM Args: calibration_data (CalibrationData): Calibration data that is going to be stored in EEPROM """ self._write(calibration_data_format["offset"], calibration_data.to_bytestr()) def read_calibration(self) -> CalibrationData: """Reads and returns shepherd calibration data from EEPROM Returns: CalibrationData object containing data extracted from EEPROM """ data = self._read(calibration_data_format["offset"], calibration_data_format["size"]) try: cal = CalibrationData.from_bytestr(data) except struct.error: cal = CalibrationData.from_default() logger.warning( "EEPROM seems to have no usable data - will set calibration from default-values" ) return cal
class PMS5003(object): 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 reset(self): if self.gpio_reset is None: return self.gpio_reset.write(False) self.enable() time.sleep(.1) self.gpio_reset.write(True) def enable(self): if not self.gpio_enable: return log.info("Enable sensor (via gpio %s)", self.gpio_enable.line) self.gpio_enable.write(True) def disable(self): if not self.gpio_enable: return log.info("Disable sensor (via gpio %s)", self.gpio_enable.line) self.gpio_enable.write(False) def discard_input(self): while self.port.input_waiting(): self.port.read(4096, 0) def warmup(self, seconds): log.info("Warming up for %s seconds", seconds) self.stop.wait(seconds) self.discard_input() @staticmethod def packet_from_data(data): numbers = struct.unpack('>16H', data) csum = sum(data[:-2]) if csum != numbers[-1]: log.warn("Bad packet data: %s / %s", data, csum) return return Packet(*numbers[2:-2]) def receive_one(self): while not self.stop.is_set(): c = self.port.read(1) if not c or c != '\x42': continue c = self.port.read(1, .1) if not c or c != '\x4d': continue data = bytearray(( 0x42, 0x4d, )) data += self.port.read(30, .1) if len(data) != 32: continue p = self.packet_from_data(data) if p: return p
def led_set(on_or_off): pin = GPIO(26, "out") pin.write(on_or_off) pin.close()
## 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()
from periphery import GPIO from periphery import SPI import time gpio_out = GPIO(17, "out") spi = SPI("/dev/spidev0.0", 0, 10000) gpio_out.write(True) data_out = [ ord('S'), ord(':'), ord('P'), ord('R'), ord('E'), ord(' '), ord('I'), ord('R'), ord(' '), ord('\n') ] data_in = spi.transfer(data_out) print("shifted out %-10s" % (''.join(chr(c) for c in data_out), )) print("shifted in %-10s" % (''.join(chr(c) for c in data_in), )) time.sleep(0.1) data_out = [ ord('S'), ord(':'),
class Pin: """Pins dont exist in CPython so...lets make our own!""" IN = "in" OUT = "out" LOW = 0 HIGH = 1 PULL_NONE = 0 PULL_UP = 1 PULL_DOWN = 2 id = None _value = LOW _mode = IN def __init__(self, pin_id): self.id = pin_id if isinstance(pin_id, tuple): self._num = int(pin_id[1]) self._chippath = "/dev/gpiochip{}".format(pin_id[0]) else: self._num = int(pin_id) self._chippath = "/dev/gpiochip0" self._line = None def __repr__(self): return str(self.id) def __eq__(self, other): return self.id == other 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) def value(self, val=None): """Set or return the Pin Value""" if val is not None: if val == self.LOW: self._value = val self._line.write(False) return None if val == self.HIGH: self._value = val self._line.write(True) return None raise RuntimeError("Invalid value for pin") return self.HIGH if self._line.read() else self.LOW
class TM1637: I2C_COMM1 = 0x40 I2C_COMM2 = 0xC0 I2C_COMM3 = 0x80 digit_to_segment = [ 0b0111111, # 0 0b0000110, # 1 0b1011011, # 2 0b1001111, # 3 0b1100110, # 4 0b1101101, # 5 0b1111101, # 6 0b0000111, # 7 0b1111111, # 8 0b1101111, # 9 0b1110111, # A 0b1111100, # b 0b0111001, # C 0b1011110, # d 0b1111001, # E 0b1110001 # F ] 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 bit_delay(self): sleep(0.001) return def set_segments(self, segments, pos=0): # Write COMM1 self.start() self.write_byte(self.I2C_COMM1) self.stop() # Write COMM2 + first digit address self.start() self.write_byte(self.I2C_COMM2 + pos) for seg in segments: self.write_byte(seg) self.stop() # Write COMM3 + brightness self.start() self.write_byte(self.I2C_COMM3 + self.brightness) self.stop() def start(self): self.gpio_clk.write(True) self.gpio_dio.write(True) self.gpio_dio.write(False) self.gpio_clk.write(False) def stop(self): self.gpio_clk.write(False) self.gpio_dio.write(False) self.gpio_clk.write(True) self.gpio_dio.write(True) def write_byte(self, data): #print("data={:x}".format(data)) for i in range(8): self.gpio_clk.write(False) if data & 0x01: self.gpio_dio.write(True) else: self.gpio_dio.write(False) data >>= 1 self.gpio_clk.write(True) self.gpio_clk.write(False) self.gpio_dio.write(True) self.gpio_clk.write(True) self.gpio_dio = GPIO(self.dio, "in") while self.gpio_dio.read(): sleep(0.001) if self.gpio_dio.read(): self.gpio_dio = GPIO(self.dio, "out") self.gpio_dio.write(False) self.gpio_dio = GPIO(self.dio, "in") self.gpio_dio = GPIO(self.dio, "out")
result = spi.transfer(buff) print("register address:0x%02X -- value:0x%02X" % (buff[1], result[2])) spi.close() #device tree SPI without CS from periphery import SPI from periphery import GPIO CS = GPIO("/dev/gpiochip0", 12, "out") spi = SPI("/dev/spidev0.0", 1, 1000000) tx = [0x02, 0x0F, 0x80] rx = [0x03, 0x0E] CS.write(False) spi.transfer(tx) CS.write(True) CS.write(False) spi.transfer(rx) temp = [0xFF] result = spi.transfer(temp) CS.write(True) print("the read register is: 0x%02X" % result[0]) spi.close() CS.close() #total
class Launcher(object): """Stores data coming from PRU's in HDF5 format Args: pin_button (int): Pin number where button is connected. Must be configured as input with pull up and connected against ground pin_led (int): Pin number of LED for displaying launcher status service_name (str): Name of shepherd systemd service """ def __init__( self, pin_button: int = 81, pin_led: int = 9, service_name: str = "shepherd", ): self.pin_button = pin_button self.pin_led = pin_led self.service_name = service_name 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 __exit__(self, *exc): self.gpio_led.close() self.gpio_button.close() def run(self) -> NoReturn: """Infinite loop waiting for button presses. Waits for falling edge on configured button pin. On detection of the edge, shepherd service is either started or stopped. Double button press while idle causes system shutdown. """ while True: logger.info("waiting for falling edge..") self.gpio_led.write(True) if not self.gpio_button.poll(): # note: poll is suspected to exit after ~ 1-2 weeks running -> fills mmc with random measurement # TODO: observe behavior, hopefully this change fixes the bug continue self.gpio_led.write(False) logger.debug("edge detected") if not self.get_state(): time.sleep(0.25) if self.gpio_button.poll(timeout=5): logging.debug("falling edge detected") logging.info("shutdown requested") self.initiate_shutdown() self.gpio_led.write(False) time.sleep(3) continue self.set_service(not self.get_state()) time.sleep(10) def get_state(self, timeout: float = 10) -> bool: """Queries systemd for state of shepherd service. Args: timeout (float): Time to wait for service state to settle Raises: TimeoutError: If state remains changing for longer than timeout """ ts_end = time.time() + timeout while True: systemd_state = self.shepherd_proxy.Get( "org.freedesktop.systemd1.Unit", "ActiveState", dbus_interface="org.freedesktop.DBus.Properties", ) if systemd_state in ["deactivating", "activating"]: time.sleep(0.1) continue else: break if time.time() > ts_end: raise TimeoutError("Timed out waiting for service state") logger.debug(f"service ActiveState: { systemd_state }") if systemd_state == "active": return True elif systemd_state == "inactive": return False raise Exception(f"Unknown state { systemd_state }") def set_service(self, requested_state: bool): """Changes state of shepherd service. Args: requested_state (bool): Target state of service """ active_state = self.get_state() if requested_state == active_state: logger.debug("service already in requested state") self.gpio_led.write(active_state) return if active_state: logger.info("stopping service") self.manager.StopUnit("shepherd.service", "fail") else: logger.info("starting service") self.manager.StartUnit("shepherd.service", "fail") time.sleep(1) new_state = self.get_state() if new_state != requested_state: raise Exception(f"state didn't change") return new_state def initiate_shutdown(self, timeout: int = 5) -> NoReturn: """ Initiates system shutdown. Args: timeout (int): Number of seconds to wait before powering off system """ logger.debug("initiating shutdown routine..") time.sleep(0.25) for _ in range(timeout): if self.gpio_button.poll(timeout=0.5): logger.debug("edge detected") logger.info("shutdown cancelled") return self.gpio_led.write(True) if self.gpio_button.poll(timeout=0.5): logger.debug("edge detected") logger.info("shutdown cancelled") return self.gpio_led.write(False) os.sync() logger.info("shutting down now") self.manager.PowerOff()