INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Convert Average pooling.
def convert_avgpool(params, w_name, scope_name, inputs, layers, weights, names): """ Convert Average pooling. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionar...
Convert 3d Max pooling.
def convert_maxpool3(params, w_name, scope_name, inputs, layers, weights, names): """ Convert 3d Max pooling. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionar...
Convert convert_adaptive_max_pool2d layer.
def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names): """ Convert convert_adaptive_max_pool2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node in...
Convert padding layer.
def convert_padding(params, w_name, scope_name, inputs, layers, weights, names): """ Convert padding layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary ...
Convert batch normalization layer.
def convert_batchnorm(params, w_name, scope_name, inputs, layers, weights, names): """ Convert batch normalization layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layer...
Convert instance normalization layer.
def convert_instancenorm(params, w_name, scope_name, inputs, layers, weights, names): """ Convert instance normalization layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs ...
Convert dropout.
def convert_dropout(params, w_name, scope_name, inputs, layers, weights, names): """ Convert dropout. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with k...
Convert relu layer.
def convert_relu(params, w_name, scope_name, inputs, layers, weights, names): """ Convert relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with k...
Convert leaky relu layer.
def convert_lrelu(params, w_name, scope_name, inputs, layers, weights, names): """ Convert leaky relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary ...
Convert sigmoid layer.
def convert_sigmoid(params, w_name, scope_name, inputs, layers, weights, names): """ Convert sigmoid layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary ...
Convert softmax layer.
def convert_softmax(params, w_name, scope_name, inputs, layers, weights, names): """ Convert softmax layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary ...
Convert tanh layer.
def convert_tanh(params, w_name, scope_name, inputs, layers, weights, names): """ Convert tanh layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with k...
Convert hardtanh layer.
def convert_hardtanh(params, w_name, scope_name, inputs, layers, weights, names): """ Convert hardtanh layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionar...
Convert selu layer.
def convert_selu(params, w_name, scope_name, inputs, layers, weights, names): """ Convert selu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with k...
Convert upsample_bilinear2d layer.
def convert_upsample_bilinear(params, w_name, scope_name, inputs, layers, weights, names): """ Convert upsample_bilinear2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs ...
Convert nearest upsampling layer.
def convert_upsample(params, w_name, scope_name, inputs, layers, weights, names): """ Convert nearest upsampling layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers:...
Convert gather ( embedding ) layer.
def convert_gather(params, w_name, scope_name, inputs, layers, weights, names): """ Convert gather (embedding) layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: d...
A context manager to temporarily set the training mode of model to mode resetting it when we exit the with - block. A no - op if mode is None.
def set_training(model, mode): """ A context manager to temporarily set the training mode of 'model' to 'mode', resetting it when we exit the with-block. A no-op if mode is None. """ if mode is None: yield return old_mode = model.training if old_mode != mode: mod...
By given pytorch model convert layers with specified convertors.
def pytorch_to_keras( model, args, input_shapes, change_ordering=False, training=False, verbose=False, names=False, ): """ By given pytorch model convert layers with specified convertors. Args: model: pytorch model args: pytorch model arguments input_shapes: keras input shap...
Attempt to return a PWM instance for the platform which the code is being executed on. Currently supports only the Raspberry Pi using the RPi. GPIO library and Beaglebone Black using the Adafruit_BBIO library. Will throw an exception if a PWM instance can t be created for the current platform. The returned PWM object h...
def get_platform_pwm(**keywords): """Attempt to return a PWM instance for the platform which the code is being executed on. Currently supports only the Raspberry Pi using the RPi.GPIO library and Beaglebone Black using the Adafruit_BBIO library. Will throw an exception if a PWM instance can't be creat...
Enable PWM output on specified pin. Set to intiial percent duty cycle value ( 0. 0 to 100. 0 ) and frequency ( in Hz ).
def start(self, pin, dutycycle, frequency_hz=2000): """Enable PWM output on specified pin. Set to intiial percent duty cycle value (0.0 to 100.0) and frequency (in Hz). """ if dutycycle < 0.0 or dutycycle > 100.0: raise ValueError('Invalid duty cycle value, must be between 0...
Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0. 0 to 100. 0 ( inclusive ).
def set_duty_cycle(self, pin, dutycycle): """Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0.0 to 100.0 (inclusive). """ if dutycycle < 0.0 or dutycycle > 100.0: raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inc...
Set frequency ( in Hz ) of PWM output on specified pin.
def set_frequency(self, pin, frequency_hz): """Set frequency (in Hz) of PWM output on specified pin.""" if pin not in self.pwm: raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin)) self.pwm[pin].ChangeFrequency(frequency_hz)
Stop PWM output on specified pin.
def stop(self, pin): """Stop PWM output on specified pin.""" if pin not in self.pwm: raise ValueError('Pin {0} is not configured as a PWM. Make sure to first call start for the pin.'.format(pin)) self.pwm[pin].stop() del self.pwm[pin]
Enable PWM output on specified pin. Set to intiial percent duty cycle value ( 0. 0 to 100. 0 ) and frequency ( in Hz ).
def start(self, pin, dutycycle, frequency_hz=2000): """Enable PWM output on specified pin. Set to intiial percent duty cycle value (0.0 to 100.0) and frequency (in Hz). """ if dutycycle < 0.0 or dutycycle > 100.0: raise ValueError('Invalid duty cycle value, must be between 0...
Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0. 0 to 100. 0 ( inclusive ).
def set_duty_cycle(self, pin, dutycycle): """Set percent duty cycle of PWM output on specified pin. Duty cycle must be a value 0.0 to 100.0 (inclusive). """ if dutycycle < 0.0 or dutycycle > 100.0: raise ValueError('Invalid duty cycle value, must be between 0.0 to 100.0 (inc...
Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI BEAGLEBONE_BLACK or UNKNOWN.
def platform_detect(): """Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.""" # Handle Raspberry Pi pi = pi_version() if pi is not None: return RASPBERRY_PI # Handle Beaglebone Black # TO...
Set order of bits to be read/ written over serial lines. Should be either MSBFIRST for most - significant first or LSBFIRST for least - signifcant first.
def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ if order == MSBFIRST: self._device.lsbfirst = False elif order == LSBF...
Set SPI mode which controls clock polarity and phase. Should be a numeric value 0 1 2 or 3. See wikipedia page for details on meaning: http:// en. wikipedia. org/ wiki/ Serial_Peripheral_Interface_Bus
def set_mode(self,mode): """Set SPI mode which controls clock polarity and phase. Should be a numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus """ if mode < 0 or mode > 3: raise Valu...
Set SPI mode which controls clock polarity and phase. Should be a numeric value 0 1 2 or 3. See wikipedia page for details on meaning: http:// en. wikipedia. org/ wiki/ Serial_Peripheral_Interface_Bus
def set_mode(self, mode): """Set SPI mode which controls clock polarity and phase. Should be a numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus """ if mode < 0 or mode > 3: raise Val...
Set order of bits to be read/ written over serial lines. Should be either MSBFIRST for most - significant first or LSBFIRST for least - signifcant first.
def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ # Set self._mask to the bitmask which points at the appropriate bit to # read or w...
Half - duplex SPI write. If assert_ss is True the SS line will be asserted low the specified bytes will be clocked out the MOSI line and if deassert_ss is True the SS line be put back high.
def write(self, data, assert_ss=True, deassert_ss=True): """Half-duplex SPI write. If assert_ss is True, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line, and if deassert_ss is True the SS line be put back high. """ # Fail MOSI is not speci...
Half - duplex SPI read. If assert_ss is true the SS line will be asserted low the specified length of bytes will be clocked in the MISO line and if deassert_ss is true the SS line will be put back high. Bytes which are read will be returned as a bytearray object.
def read(self, length, assert_ss=True, deassert_ss=True): """Half-duplex SPI read. If assert_ss is true, the SS line will be asserted low, the specified length of bytes will be clocked in the MISO line, and if deassert_ss is true the SS line will be put back high. Bytes which are read w...
Full - duplex SPI read and write. If assert_ss is true the SS line will be asserted low the specified bytes will be clocked out the MOSI line while bytes will also be read from the MISO line and if deassert_ss is true the SS line will be put back high. Bytes which are read will be returned as a bytearray object.
def transfer(self, data, assert_ss=True, deassert_ss=True): """Full-duplex SPI read and write. If assert_ss is true, the SS line will be asserted low, the specified bytes will be clocked out the MOSI line while bytes will also be read from the MISO line, and if deassert_ss is true the S...
Set the input or output mode for a specified pin. Mode should be either GPIO. OUT or GPIO. IN.
def setup(self, pin, value): """Set the input or output mode for a specified pin. Mode should be either GPIO.OUT or GPIO.IN. """ self._validate_pin(pin) # Set bit to 1 for input or 0 for output. if value == GPIO.IN: self.iodir[int(pin/8)] |= 1 << (int(pin%8))...
Set multiple pins high or low at once. Pins should be a dict of pin name to pin value ( HIGH/ True for 1 LOW/ False for 0 ). All provided pins will be set to the given values.
def output_pins(self, pins): """Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values. """ [self._validate_pin(pin) for pin in pins.keys()] # Set each c...
Read multiple pins specified in the given list and return list of pin values GPIO. HIGH/ True if the pin is pulled high or GPIO. LOW/ False if pulled low.
def input_pins(self, pins): """Read multiple pins specified in the given list and return list of pin values GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low. """ [self._validate_pin(pin) for pin in pins] # Get GPIO state. self.gpio = self._device....
Turn on the pull - up resistor for the specified pin if enabled is True otherwise turn off the pull - up resistor.
def pullup(self, pin, enabled): """Turn on the pull-up resistor for the specified pin if enabled is True, otherwise turn off the pull-up resistor. """ self._validate_pin(pin) if enabled: self.gppu[int(pin/8)] |= 1 << (int(pin%8)) else: self.gppu[in...
Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written.
def write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """ if gpio is not None: self.gpio = gpio self._device.writeList(self.GPIO, self.gpio)
Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written.
def write_iodir(self, iodir=None): """Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written. """ if iodir is not None: self.iodir = iodir self._device.writeList(self.IODIR, self.iodir)
Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written.
def write_gppu(self, gppu=None): """Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written. """ if gppu is not None: self.gppu = gppu self._device.writeList(self.GPPU, self.gppu)
Disable the FTDI drivers for the current platform. This is necessary because they will conflict with libftdi and accessing the FT232H. Note you can enable the FTDI drivers again by calling enable_FTDI_driver.
def disable_FTDI_driver(): """Disable the FTDI drivers for the current platform. This is necessary because they will conflict with libftdi and accessing the FT232H. Note you can enable the FTDI drivers again by calling enable_FTDI_driver. """ logger.debug('Disabling FTDI driver.') if sys.platf...
Re - enable the FTDI drivers for the current platform.
def enable_FTDI_driver(): """Re-enable the FTDI drivers for the current platform.""" logger.debug('Enabling FTDI driver.') if sys.platform == 'darwin': logger.debug('Detected Mac OSX') # Mac OS commands to enable FTDI driver. _check_running_as_root() subprocess.check_call('ke...
Return a list of all FT232H device serial numbers connected to the machine. You can use these serial numbers to open a specific FT232H device by passing it to the FT232H initializer s serial parameter.
def enumerate_device_serials(vid=FT232H_VID, pid=FT232H_PID): """Return a list of all FT232H device serial numbers connected to the machine. You can use these serial numbers to open a specific FT232H device by passing it to the FT232H initializer's serial parameter. """ try: # Create a libf...
Close the FTDI device. Will be automatically called when the program ends.
def close(self): """Close the FTDI device. Will be automatically called when the program ends.""" if self._ctx is not None: ftdi.free(self._ctx) self._ctx = None
Helper function to call write_data on the provided FTDI device and verify it succeeds.
def _write(self, string): """Helper function to call write_data on the provided FTDI device and verify it succeeds. """ # Get modem status. Useful to enable for debugging. #ret, status = ftdi.poll_modem_status(self._ctx) #if ret == 0: # logger.debug('Modem status ...
Helper function to call the provided command on the FTDI device and verify the response matches the expected value.
def _check(self, command, *args): """Helper function to call the provided command on the FTDI device and verify the response matches the expected value. """ ret = command(self._ctx, *args) logger.debug('Called ftdi_{0} and got response {1}.'.format(command.__name__, ret)) ...
Helper function to continuously poll reads on the FTDI device until an expected number of bytes are returned. Will throw a timeout error if no data is received within the specified number of timeout seconds. Returns the read data as a string if successful otherwise raises an execption.
def _poll_read(self, expected, timeout_s=5.0): """Helper function to continuously poll reads on the FTDI device until an expected number of bytes are returned. Will throw a timeout error if no data is received within the specified number of timeout seconds. Returns the read data as a s...
Enable MPSSE mode on the FTDI device.
def _mpsse_enable(self): """Enable MPSSE mode on the FTDI device.""" # Reset MPSSE by sending mask = 0 and mode = 0 self._check(ftdi.set_bitmode, 0, 0) # Enable MPSSE by sending mask = 0 and mode = 2 self._check(ftdi.set_bitmode, 0, 2)
Synchronize buffers with MPSSE by sending bad opcode and reading expected error response. Should be called once after enabling MPSSE.
def _mpsse_sync(self, max_retries=10): """Synchronize buffers with MPSSE by sending bad opcode and reading expected error response. Should be called once after enabling MPSSE.""" # Send a bad/unknown command (0xAB), then read buffer until bad command # response is found. self._w...
Set the clock speed of the MPSSE engine. Can be any value from 450hz to 30mhz and will pick that speed or the closest speed below it.
def mpsse_set_clock(self, clock_hz, adaptive=False, three_phase=False): """Set the clock speed of the MPSSE engine. Can be any value from 450hz to 30mhz and will pick that speed or the closest speed below it. """ # Disable clock divisor by 5 to enable faster speeds on FT232H. se...
Read both GPIO bus states and return a 16 bit value with their state. D0 - D7 are the lower 8 bits and C0 - C7 are the upper 8 bits.
def mpsse_read_gpio(self): """Read both GPIO bus states and return a 16 bit value with their state. D0-D7 are the lower 8 bits and C0-C7 are the upper 8 bits. """ # Send command to read low byte and high byte. self._write('\x81\x83') # Wait for 2 byte response. da...
Return command to update the MPSSE GPIO state to the current direction and level.
def mpsse_gpio(self): """Return command to update the MPSSE GPIO state to the current direction and level. """ level_low = chr(self._level & 0xFF) level_high = chr((self._level >> 8) & 0xFF) dir_low = chr(self._direction & 0xFF) dir_high = chr((self._direction >...
Set the input or output mode for a specified pin. Mode should be either OUT or IN.
def setup(self, pin, mode): """Set the input or output mode for a specified pin. Mode should be either OUT or IN.""" self._setup_pin(pin, mode) self.mpsse_write_gpio()
Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin mode ( IN or OUT ). Optional starting values of pins can be provided in the values dict ( with pin name to pin value ).
def setup_pins(self, pins, values={}, write=True): """Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin mode (IN or OUT). Optional starting values of pins can be provided in the values dict (with pin name to pin value). """ # General imp...
Set the specified pin the provided high/ low value. Value should be either HIGH/ LOW or a boolean ( true = high ).
def output(self, pin, value): """Set the specified pin the provided high/low value. Value should be either HIGH/LOW or a boolean (true = high).""" if pin < 0 or pin > 15: raise ValueError('Pin must be between 0 and 15 (inclusive).') self._output_pin(pin, value) self....
Set multiple pins high or low at once. Pins should be a dict of pin name to pin value ( HIGH/ True for 1 LOW/ False for 0 ). All provided pins will be set to the given values.
def output_pins(self, pins, write=True): """Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values. """ for pin, value in iter(pins.items()): self._o...
Read multiple pins specified in the given list and return list of pin values GPIO. HIGH/ True if the pin is pulled high or GPIO. LOW/ False if pulled low.
def input_pins(self, pins): """Read multiple pins specified in the given list and return list of pin values GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.""" if [pin for pin in pins if pin < 0 or pin > 15]: raise ValueError('Pin must be between 0 and 15 (i...
Set SPI mode which controls clock polarity and phase. Should be a numeric value 0 1 2 or 3. See wikipedia page for details on meaning: http:// en. wikipedia. org/ wiki/ Serial_Peripheral_Interface_Bus
def set_mode(self, mode): """Set SPI mode which controls clock polarity and phase. Should be a numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus """ if mode < 0 or mode > 3: raise Val...
Set order of bits to be read/ written over serial lines. Should be either MSBFIRST for most - significant first or LSBFIRST for least - signifcant first.
def set_bit_order(self, order): """Set order of bits to be read/written over serial lines. Should be either MSBFIRST for most-significant first, or LSBFIRST for least-signifcant first. """ if order == MSBFIRST: self.lsbfirst = 0 elif order == LSBFIRST: ...
Half - duplex SPI write. The specified array of bytes will be clocked out the MOSI line.
def write(self, data): """Half-duplex SPI write. The specified array of bytes will be clocked out the MOSI line. """ #check for hardware limit of FT232H and similar MPSSE chips if (len(data) > 65536): print('the FTDI chip is limited to 65536 bytes (64 KB) of input/ou...
Half - duplex SPI read. The specified length of bytes will be clocked in the MISO line and returned as a bytearray object.
def read(self, length): """Half-duplex SPI read. The specified length of bytes will be clocked in the MISO line and returned as a bytearray object. """ #check for hardware limit of FT232H and similar MPSSE chips if (1 > length > 65536): print('the FTDI chip is limite...
Half - duplex SPI write then read. Send command and payload to slave as bytearray then consequently read out response from the slave for length in bytes. Designed for use with NOR or NAND flash chips and possibly SD cards... etc... Read command is cut in half and performed twice in series to prevent single byte errors....
def bulkread(self, data = [], lengthR = 'None', readmode = 1): """Half-duplex SPI write then read. Send command and payload to slave as bytearray then consequently read out response from the slave for length in bytes. Designed for use with NOR or NAND flash chips, and possibly SD cards...etc...
Full - duplex SPI read and write. The specified array of bytes will be clocked out the MOSI line while simultaneously bytes will be read from the MISO line. Read bytes will be returned as a bytearray object.
def transfer(self, data): """Full-duplex SPI read and write. The specified array of bytes will be clocked out the MOSI line, while simultaneously bytes will be read from the MISO line. Read bytes will be returned as a bytearray object. """ #check for hardware limit of FT232H an...
Put I2C lines into idle state.
def _idle(self): """Put I2C lines into idle state.""" # Put the I2C lines into an idle state with SCL and SDA high. self._ft232h.setup_pins({0: GPIO.OUT, 1: GPIO.OUT, 2: GPIO.IN}, {0: GPIO.HIGH, 1: GPIO.HIGH})
End I2C transaction and get response bytes including ACKs.
def _transaction_end(self): """End I2C transaction and get response bytes, including ACKs.""" # Ask to return response bytes immediately. self._command.append('\x87') # Send the entire command to the MPSSE. self._ft232h._write(''.join(self._command)) # Read response bytes...
Send I2C start signal. Must be called within a transaction start/ end.
def _i2c_start(self): """Send I2C start signal. Must be called within a transaction start/end. """ # Set SCL high and SDA low, repeat 4 times to stay in this state for a # short period of time. self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.LOW}, write=False) self._comma...
Set I2C signals to idle state with SCL and SDA at a high value. Must be called within a transaction start/ end.
def _i2c_idle(self): """Set I2C signals to idle state with SCL and SDA at a high value. Must be called within a transaction start/end. """ self._ft232h.output_pins({0: GPIO.HIGH, 1: GPIO.HIGH}, write=False) self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY)
Send I2C stop signal. Must be called within a transaction start/ end.
def _i2c_stop(self): """Send I2C stop signal. Must be called within a transaction start/end. """ # Set SCL low and SDA low for a short period. self._ft232h.output_pins({0: GPIO.LOW, 1: GPIO.LOW}, write=False) self._command.append(self._ft232h.mpsse_gpio() * _REPEAT_DELAY) ...
Read the specified number of bytes from the I2C bus. Length is the number of bytes to read ( must be 1 or more ).
def _i2c_read_bytes(self, length=1): """Read the specified number of bytes from the I2C bus. Length is the number of bytes to read (must be 1 or more). """ for i in range(length-1): # Read a byte and send ACK. self._command.append('\x20\x00\x00\x13\x00\x00') ...
Write the specified number of bytes to the chip.
def _i2c_write_bytes(self, data): """Write the specified number of bytes to the chip.""" for byte in data: # Write byte. self._command.append(str(bytearray((0x11, 0x00, 0x00, byte)))) # Make sure pins are back in idle state with clock low and data high. se...
Attempt to detect if a device at this address is present on the I2C bus. Will send out the device s address for writing and verify an ACK is received. Returns true if the ACK is received and false if not.
def ping(self): """Attempt to detect if a device at this address is present on the I2C bus. Will send out the device's address for writing and verify an ACK is received. Returns true if the ACK is received, and false if not. """ self._idle() self._transaction_start() ...
Write an 8 - bit value on the bus ( without register ).
def writeRaw8(self, value): """Write an 8-bit value on the bus (without register).""" value = value & 0xFF self._idle() self._transaction_start() self._i2c_start() self._i2c_write_bytes([self._address_byte(False), value]) self._i2c_stop() response = self._...
Write a 16 - bit value to the specified register.
def write16(self, register, value, little_endian=True): """Write a 16-bit value to the specified register.""" value = value & 0xFFFF value_low = value & 0xFF value_high = (value >> 8) & 0xFF if not little_endian: value_low, value_high = value_high, value_low ...
Write bytes to the specified register.
def writeList(self, register, data): """Write bytes to the specified register.""" self._idle() self._transaction_start() self._i2c_start() self._i2c_write_bytes([self._address_byte(False), register] + data) self._i2c_stop() response = self._transaction_end() ...
Read a length number of bytes from the specified register. Results will be returned as a bytearray.
def readList(self, register, length): """Read a length number of bytes from the specified register. Results will be returned as a bytearray.""" if length <= 0: raise ValueError("Length must be at least 1 byte.") self._idle() self._transaction_start() self._i2...
Read an 8 - bit value on the bus ( without register ).
def readRaw8(self): """Read an 8-bit value on the bus (without register).""" self._idle() self._transaction_start() self._i2c_start() self._i2c_write_bytes([self._address_byte(False)]) self._i2c_stop() self._i2c_idle() self._i2c_start() self._i2c_w...
Read a signed byte from the specified register.
def readS8(self, register): """Read a signed byte from the specified register.""" result = self.readU8(register) if result > 127: result -= 256 return result
Read a signed 16 - bit value from the specified register with the specified endianness ( default little endian or least significant byte first ).
def readS16(self, register, little_endian=True): """Read a signed 16-bit value from the specified register, with the specified endianness (default little endian, or least significant byte first).""" result = self.readU16(register, little_endian) if result > 32767: res...
Return the default bus number based on the device platform. For a Raspberry Pi either bus 0 or 1 ( based on the Pi revision ) will be returned. For a Beaglebone Black the first user accessible bus 1 will be returned.
def get_default_bus(): """Return the default bus number based on the device platform. For a Raspberry Pi either bus 0 or 1 (based on the Pi revision) will be returned. For a Beaglebone Black the first user accessible bus, 1, will be returned. """ plat = Platform.platform_detect() if plat == Pla...
Return an I2C device for the specified address and on the specified bus. If busnum isn t specified the default I2C bus for the platform will attempt to be detected.
def get_i2c_device(address, busnum=None, i2c_interface=None, **kwargs): """Return an I2C device for the specified address and on the specified bus. If busnum isn't specified, the default I2C bus for the platform will attempt to be detected. """ if busnum is None: busnum = get_default_bus() ...
Enable repeated start conditions for I2C register reads. This is the normal behavior for I2C however on some platforms like the Raspberry Pi there are bugs which disable repeated starts unless explicitly enabled with this function. See this thread for more details: http:// www. raspberrypi. org/ forums/ viewtopic. php?...
def require_repeated_start(): """Enable repeated start conditions for I2C register reads. This is the normal behavior for I2C, however on some platforms like the Raspberry Pi there are bugs which disable repeated starts unless explicitly enabled with this function. See this thread for more details: ...
Write an 8 - bit value on the bus ( without register ).
def writeRaw8(self, value): """Write an 8-bit value on the bus (without register).""" value = value & 0xFF self._bus.write_byte(self._address, value) self._logger.debug("Wrote 0x%02X", value)
Write an 8 - bit value to the specified register.
def write8(self, register, value): """Write an 8-bit value to the specified register.""" value = value & 0xFF self._bus.write_byte_data(self._address, register, value) self._logger.debug("Wrote 0x%02X to register 0x%02X", value, register)
Write a 16 - bit value to the specified register.
def write16(self, register, value): """Write a 16-bit value to the specified register.""" value = value & 0xFFFF self._bus.write_word_data(self._address, register, value) self._logger.debug("Wrote 0x%04X to register pair 0x%02X, 0x%02X", value, register, register+1)
Write bytes to the specified register.
def writeList(self, register, data): """Write bytes to the specified register.""" self._bus.write_i2c_block_data(self._address, register, data) self._logger.debug("Wrote to register 0x%02X: %s", register, data)
Read a length number of bytes from the specified register. Results will be returned as a bytearray.
def readList(self, register, length): """Read a length number of bytes from the specified register. Results will be returned as a bytearray.""" results = self._bus.read_i2c_block_data(self._address, register, length) self._logger.debug("Read the following from register 0x%02X: %s", ...
Read an 8 - bit value on the bus ( without register ).
def readRaw8(self): """Read an 8-bit value on the bus (without register).""" result = self._bus.read_byte(self._address) & 0xFF self._logger.debug("Read 0x%02X", result) return result
Read an unsigned byte from the specified register.
def readU8(self, register): """Read an unsigned byte from the specified register.""" result = self._bus.read_byte_data(self._address, register) & 0xFF self._logger.debug("Read 0x%02X from register 0x%02X", result, register) return result
Read an unsigned 16 - bit value from the specified register with the specified endianness ( default little endian or least significant byte first ).
def readU16(self, register, little_endian=True): """Read an unsigned 16-bit value from the specified register, with the specified endianness (default little endian, or least significant byte first).""" result = self._bus.read_word_data(self._address,register) & 0xFFFF self._logge...
Attempt to return a GPIO instance for the platform which the code is being executed on. Currently supports only the Raspberry Pi using the RPi. GPIO library and Beaglebone Black using the Adafruit_BBIO library. Will throw an exception if a GPIO instance can t be created for the current platform. The returned GPIO objec...
def get_platform_gpio(**keywords): """Attempt to return a GPIO instance for the platform which the code is being executed on. Currently supports only the Raspberry Pi using the RPi.GPIO library and Beaglebone Black using the Adafruit_BBIO library. Will throw an exception if a GPIO instance can't be cr...
Set multiple pins high or low at once. Pins should be a dict of pin name to pin value ( HIGH/ True for 1 LOW/ False for 0 ). All provided pins will be set to the given values.
def output_pins(self, pins): """Set multiple pins high or low at once. Pins should be a dict of pin name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins will be set to the given values. """ # General implementation just loops through pins and writes them out ...
Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type ( IN or OUT ).
def setup_pins(self, pins): """Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type (IN or OUT). """ # General implementation that can be optimized by derived classes. for pin, value in iter(pins.items()): self.setup(pin, va...
Set the input or output mode for a specified pin. Mode should be either OUTPUT or INPUT.
def setup(self, pin, mode, pull_up_down=PUD_OFF): """Set the input or output mode for a specified pin. Mode should be either OUTPUT or INPUT. """ self.rpi_gpio.setup(pin, self._dir_mapping[mode], pull_up_down=self._pud_mapping[pull_up_down])
Enable edge detection events for a particular GPIO channel. Pin should be type IN. Edge must be RISING FALLING or BOTH. Callback is a function for the event. Bouncetime is switch bounce timeout in ms for callback
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1): """Enable edge detection events for a particular GPIO channel. Pin should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a function for the event. Bouncetime is switch bounce timeout in ms for callba...
Wait for an edge. Pin should be type IN. Edge must be RISING FALLING or BOTH.
def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge])
Clean up GPIO event detection for specific pin or all pins if none is specified.
def cleanup(self, pin=None): """Clean up GPIO event detection for specific pin, or all pins if none is specified. """ if pin is None: self.rpi_gpio.cleanup() else: self.rpi_gpio.cleanup(pin)
Add a callback for an event already defined using add_event_detect (). Pin should be type IN. Bouncetime is switch bounce timeout in ms for callback
def add_event_callback(self, pin, callback, bouncetime=-1): """Add a callback for an event already defined using add_event_detect(). Pin should be type IN. Bouncetime is switch bounce timeout in ms for callback """ kwargs = {} if bouncetime > 0: kwargs['boun...
Wait for an edge. Pin should be type IN. Edge must be RISING FALLING or BOTH.
def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge])
Clean up GPIO event detection for specific pin or all pins if none is specified.
def cleanup(self, pin=None): """Clean up GPIO event detection for specific pin, or all pins if none is specified. """ if pin is None: self.bbio_gpio.cleanup() else: self.bbio_gpio.cleanup(pin)