Exemplo n.º 1
0
class interface:
    def __init__(self, bus_number: int):
        self.bus = SMBus(bus_number)
        return

    # Get a sensor readings from an arduino with a given id.
    # This will ultimately call the `get_sensor_[number]()`
    # function on the specified arduino. The arduino will
    # send the value over I2C and it will be returned from
    # this function.
    def get_sensor_reading(self, arduino_ID: int, sensor_number: int):
        # Request reading from sensor, Data returned as float in 4 Bytes
        sensor_data = bytearray(
            self.bus.read_block_data(arduino_ID, sensor_number, 4))
        # Convert 4 raw bytes into Float value
        # Uses BIG ENDIAN, This may be incorrect. If float values are
        # incorrect, try '>f' instead
        value = struct.unpack('>f', sensor_data[:4])
        return value

    # Send a text command to the arduino, This will call the `handle_commnd()`
    # function on thw arduino. No value is returned from the arduino.
    def send_command(self, arduino_ID: int, command_code: int,
                     extra_data: bytearray):
        # Create Data array to send
        data_array = bytearray(command_code) + extra_data
        # Send command over I2C
        self.bus.write_block_data(arduino_ID, I2C_COMMAND_CODE, data_array)
        return
class i2c_device:
	def __init__(self, addr, port=I2CBUS):
		self.addr = addr
		self.bus = SMBus(port)

	# Write a single command
	def write_cmd(self, cmd):
		self.bus.write_byte(self.addr, cmd)
		sleep(0.0001)

	# Write a command and argument
	def write_cmd_arg(self, cmd, data):
		self.bus.write_byte_data(self.addr, cmd, data)
		sleep(0.0001)

	# Write a block of data
	def write_block_data(self, cmd, data):
		self.bus.write_block_data(self.addr, cmd, data)
		sleep(0.0001)

	# Read a single byte
	def read(self):
		return self.bus.read_byte(self.addr)

	# Read
	def read_data(self, cmd):
		return self.bus.read_byte_data(self.addr, cmd)

	# Read a block of data
	def read_block_data(self, cmd):
		return self.bus.read_block_data(self.addr, cmd)