I2CPy I/O

I2C.readfrom(addr, nbytes)

Read the given number of bytes from the I2C peripheral specified by addr.

Parameters
  • addr (int) – An integer representing the peripheral address of the device on the I2C bus.

  • nbytes (int) – An integer indicating the number of bytes to read from the I2C device.

Returns

The bytes received from the I2C device as a bytearray.

Return type

bytearray

Raises

StreamError – Raised due to an error in the underlying Quanser Stream API. A suitable error message may be retrieved using get_error_message.

Example

>>> from quanser.communications.i2cpy import I2C
>>>
>>> ADDRESS = 42 # set to the peripheral address of the device on the I2C bus
>>>
>>> i2c = I2C()
>>> try:
>>>     response = i2c.readfrom(ADDRESS, 6) # read 6 bytes from the I2C device
>>> finally:
>>>     i2c.deinit()
I2C.readfrom_mem(addr, memaddr, nbytes, addrsize=8)

Read the given number of bytes from the I2C peripheral specified by addr starting from the memory address, memaddr.

Parameters
  • addr (int) – An integer representing the peripheral address of the device on the I2C bus.

  • memaddr (int) – An integer representing the memory address within the peripheral from which to read.

  • nbytes (int) – An integer indicating the number of bytes to read from the I2C device.

  • addrsize (int) – An integer indicating the number of bits for the address. The default is 8.

Returns

A bytearray of the bytes received from the I2C device.

Return type

bytearray

Raises
  • ValueError – Raised when a parameter value is invalid.

  • StreamError – Raised due to an error in the underlying Quanser Stream API. A suitable error message may be retrieved using get_error_message.

Examples

This example performs a single read from a memory address on an I2C device.

>>> from quanser.communications.i2cpy import I2C
>>>
>>> ADDRESS = 42 # set to the peripheral address of the device on the I2C bus
>>> MEMORY  = 8  # set to the memory address in the peripheral
>>>
>>> i2c = I2C()
>>> try:
>>>     response = i2c.readfrom_mem(ADDRESS, MEMORY, 6) # read 6 bytes from the I2C device starting at memory address MEMORY
>>> finally:
>>>     i2c.deinit()

This is a complete example of reading from an ADS1115 analog sensor.

>>> from quanser.communications.i2cpy import I2C
>>> import time
>>>
>>> # ADS1115 default I2C address(ADDR pin to GND)
>>> ADS1115_ADDR = 0x48
>>>
>>> # ADS1115 Register Addresses
>>> REG_CONVERSION = 0x00
>>> REG_CONFIG = 0x01
>>>
>>> # ADS1115 Config Register Bits(single - shot mode, AIN0, ±4.096V, 128SPS)
>>> CONFIG_OS_SINGLE = 0x8000  # Start single conversion
>>> CONFIG_MUX_AIN0 = 0x4000   # MUX[2:0] = 100 (AIN0 vs GND)
>>> CONFIG_PGA_4_096V = 0x0200 # ±4.096V range
>>> CONFIG_MODE_SINGLE = 0x0100
>>> CONFIG_DR_128SPS = 0x0080  # 128 samples per second
>>> CONFIG_COMP_DISABLE = 0x0003
>>>
>>> # Combine config bits
>>> BASE_CONFIG = (CONFIG_MUX_AIN0 | CONFIG_PGA_4_096V |
>>>                CONFIG_MODE_SINGLE | CONFIG_DR_128SPS |
>>>                CONFIG_COMP_DISABLE)
>>>
>>> # LSB size for ±4.096V range(from datasheet)
>>> LSB_SIZE = 4.096 / 32768.0  # volts per bit
>>>
>>> def read_adc_single_ended(i2c, channel=0):
>>>     """Read a single-ended ADC value from the given channel (0-3)."""
>>>     if not (0 <= channel <= 3):
>>>         raise ValueError("Channel must be 0-3")
>>>
>>>     # Adjust MUX bits for channel
>>>     mux_bits = 0x4000 + (channel << 12)
>>>     config = CONFIG_OS_SINGLE | mux_bits | CONFIG_PGA_4_096V | CONFIG_MODE_SINGLE | CONFIG_DR_128SPS | CONFIG_COMP_DISABLE
>>>
>>>     # Write config register (big - endian)
>>>     b = bytearray([(config >> 8) & 0xFF, config & 0xFF])
>>>     i2c.writeto_mem(ADS1115_ADDR, REG_CONFIG, b)
>>>
>>>     # Wait for conversion(depends on data rate; 128SPS ~8ms)
>>>     time.sleep(0.01)
>>>
>>>     # Read conversion result(big - endian)
>>>     raw = i2c.readfrom_mem(ADS1115_ADDR, REG_CONVERSION, 2)
>>>     raw = ((raw[0] & 0xFF) << 8) | (raw[1] >> 8)  # Swap bytes
>>>
>>>     return raw
>>>
>>> def main():
>>>     try:
>>>         # Open I2C bus 0
>>>         i2c = I2C()
>>>         try:
>>>             while True:
>>>                 raw_value = read_adc_single_ended(i2c, channel = 0)
>>>                 voltage = raw_value * LSB_SIZE
>>>                 print(f"Raw: {raw_value}, Voltage: {voltage:.4f} V")
>>>                 time.sleep(1)
>>>         finally:
>>>             i2c.deinit()
>>>
>>>     except KeyboardInterrupt:
>>>         print("\nExiting...")
>>>     except Exception as e:
>>>         print(f"Error: {e}")
>>>     except:
>>>         print("Unrecognized error")
>>>
>>> if __name__ == "__main__":
>>>     main()
>>>     input("Press Enter to continue...")
I2C.readfrom_mem_into(addr, memaddr, buf, addrsize=8)

Read from the I2C peripheral specified by addr into the given buffer starting from the memory address, memaddr.

The number of bytes read is determined by the length of the buffer provided.

Parameters
  • addr (int) – An integer representing the peripheral address of the device on the I2C bus.

  • memaddr (int) – An integer representing the memory address within the peripheral from which to read.

  • buf (bytearray) – A bytearray into which the data received will be stored. The length of this array determines the number of bytes read.

  • addrsize (int) – An integer indicating the number of bits for the address. The default is 8.

Raises
  • ValueError – Raised when a parameter value is invalid.

  • StreamError – Raised due to an error in the underlying Quanser Stream API. A suitable error message may be retrieved using get_error_message.

Example

>>> from quanser.communications.i2cpy import I2C
>>>
>>> ADDRESS = 42 # set to the peripheral address of the device on the I2C bus
>>> MEMORY  = 8  # set to the memory address in the peripheral
>>>
>>> i2c = I2C()
>>> try:
>>>     buf = bytearray(6)
>>>     response = i2c.readfrom_mem_into(ADDRESS, MEMORY, buf) # read 6 bytes from the I2C device starting at memory address MEMORY into buf
>>> finally:
>>>     i2c.deinit()
I2C.writeto(addr, buf)

Write the bytes from buf to the I2C peripheral specified by addr.

If the number of bytes exceeds buffer_size then an error will occur.

Parameters
  • addr (int) – An integer representing the peripheral address of the device on the I2C bus.

  • buf (Buffer) – A buffer containing the bytes to write to the I2C device.

Raises

StreamError – Raised due to an error in the underlying Quanser Stream API. A suitable error message may be retrieved using get_error_message.

Example

>>> from quanser.communications.i2cpy import I2C
>>>
>>> ADDRESS = 42 # set to the peripheral address of the device on the I2C bus
>>>
>>> i2c = I2C()
>>> try:
>>>     i2c.writeto(ADDRESS, [10, 20, 30, 40, 50]) # write 5 bytes to the I2C device
>>> finally:
>>>     i2c.deinit()
I2C.writeto_mem(addr, memaddr, buf, addrsize=8)

Write the bytes from buf to the given memory address in the I2C peripheral specified by addr.

If the number of bytes for the memory address and data exceeds buffer_size then an error will occur.

Parameters
  • addr (int) – An integer representing the peripheral address of the device on the I2C bus.

  • memaddr (int) – An integer representing the memory address within the peripheral to which to write.

  • buf (Buffer) – A buffer containing the bytes to write to the I2C device.

  • addrsize (int) – An integer indicating the number of bits for the address. The default is 8.

Raises
  • ValueError – Raised when a parameter value is invalid.

  • StreamError – Raised due to an error in the underlying Quanser Stream API. A suitable error message may be retrieved using get_error_message.

Example

>>> from quanser.communications.i2cpy import I2C
>>>
>>> ADDRESS = 42 # set to the peripheral address of the device on the I2C bus
>>>
>>> i2c = I2C()
>>> try:
>>>     i2c.writeto(ADDRESS, [10, 20, 30, 40, 50]) # write 5 bytes to the I2C device
>>> finally:
>>>     i2c.deinit()