Beispiel #1
0
    def read(self, first_address, count):
        dat_buffer = []
        bytes_already_read = 0
        while bytes_already_read != count:
            read_len = min(MAX_WPILIB_I2C_READ_BYTES,
                           count - bytes_already_read)

            with self.mutex:
                try:
                    # first transfer address and length we want to read
                    register_address = first_address + bytes_already_read
                    self.i2c.transfer(
                        0x32, [I2C.Message([register_address, read_len])])

                    # now read the data
                    # NOTE: these two statements should theoretically be able to be combined into a single transaction,
                    # but when I tried, it didn't work
                    read_msg = I2C.Message(bytearray(read_len), read=True)
                    self.i2c.transfer(0x32, [read_msg])

                    #print("Read %d bytes at register %d: %s" % (read_len, register_address, binascii.hexlify(read_msg.data)))
                    if not read_msg.data:
                        break

                    dat_buffer.extend(read_msg.data)
                    bytes_already_read = len(dat_buffer)
                except Exception:
                    traceback.print_exc()
                    break

        if bytes_already_read != count:
            raise IOError("Read error")

        return dat_buffer
Beispiel #2
0
def run(i2c, time, steps, Filename):
    f = open(Filename + "_input.txt", "w+")
    time = float(time)
    volt = 0x0000
    while (int(volt) < 26214):
        i2c.transfer(
            0x11,
            [I2C.Message([0x3F, volt >> 8, volt & 0xFF00 >> 8], read=False)])
        volt = volt + steps
        os.system(
            "cat /sys/bus/iio/devices/iio:device0/in_voltage8_vpvn_raw >>" +
            Filename + "_output.txt")
        f.write('%0.2f\n' % (float(volt)))
        f.flush()
        os.fsync(f.fileno())
        sleep(time)
        if (int(volt) > 26214 - steps - 1):
            while (int(volt) > 0):
                volt = volt - steps
                i2c.transfer(0x11, [
                    I2C.Message([0x3F, volt >> 8, volt & 0xFF00 >> 8],
                                read=False)
                ])
                print('%.2f' % (float(volt)))
                os.system(
                    "cat /sys/bus/iio/devices/iio:device0/in_voltage8_vpvn_raw >>"
                    + Filename + "_output.txt")
                f.write('%0.2f\n' % (float(volt)))
                f.flush()
                os.fsync(f.fileno())
                sleep(time)
Beispiel #3
0
def pmbus_read(dev_addr, reg_addr, n_bytes):
    i2c = I2C("/dev/i2c-0")
    write = I2C.Message([reg_addr])
    read = I2C.Message([0x0] * n_bytes, read=True)
    i2c.transfer(dev_addr, [write, read])
    i2c.close()
    return bytes(bytearray(read.data)).encode('hex')
Beispiel #4
0
 def get_eeprom(self, eeprom_address=0x50):
     # Dua transfer I2C terpisah jika ukuran buffer kecil
     q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00] * 4000, read=True)]
     q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00] * 4000, read=True)]
     self.i2c.transfer(eeprom_address, q1)
     self.i2c.transfer(eeprom_address, q2)
     return np.array(q1[1].data + q2[1].data)
Beispiel #5
0
def bootloader_enter(ser, address, rst_gpio, inverted):

    # send payload
    req = bytearray(REQ_ENTER)
    chunks = os.path.getsize(FILE)
    chunks = int(math.ceil(float(chunks) / BLOCK_SIZE))
    print('Need to send %s chunks' % chunks)
    crc = get_crc()
    req.extend([chunks, crc, crc])
    # I2c transaction with bootloader request and ACK nand respond
    # toggle reset via sysFS GPIO
    rst_gpio.write(inverted)
    sleep(0.5)
    rst_gpio.write(not inverted)
    sleep(0.01)
    snd = [I2C.Message(req)]
    rcv = [I2C.Message([0x00, 0x00], read=True)]
    ser.transfer(address, snd)
    sleep(0.01)  # give some time to process the block
    ser.transfer(address, rcv)
    if bytearray(rcv[0].data) != bytearray(ACK):
        print("Bootloader NACK")
        sys.exit(1)

    return ser
def bmr458_mon(dev_addr, reg_addr):
    i2c = I2C("/dev/i2c-1")
    write = I2C.Message([reg_addr])
    read = I2C.Message([0x0] * 2, read=True)
    i2c.transfer(dev_addr, [write, read])
    i2c.close()
    return bytes(bytearray(read.data)).encode('hex')
Beispiel #7
0
    def Reset(self):
        """Reset the Notecard."""
        chunk_len = 0

        while not self.lock():
            pass

        try:
            while True:
                time.sleep(.001)
                reg = bytearray(2)
                reg[0] = 0
                reg[1] = chunk_len
                readlen = chunk_len + 2
                buf = bytearray(readlen)
                if use_periphery:
                    msgs = [I2C.Message(reg), I2C.Message(buf, read=True)]
                    self.i2c.transfer(self.addr, msgs)
                    buf = msgs[1].data
                elif use_micropython:
                    self.i2c.writeto(self.addr, reg, False)
                    self.i2c.readfrom_into(self.addr, buf)
                else:
                    self.i2c.writeto_then_readfrom(self.addr, reg, buf)
                available = buf[0]
                if available == 0:
                    break
                chunk_len = min(available, self.max)
        finally:
            self.unlock()

        pass
Beispiel #8
0
 def get_eeprom(self, eeprom_address=0x50):
     query = [
         I2C.Message([0x00, 0x00]),
         I2C.Message([0x00] * 8000, read=True)
     ]
     self.i2c.transfer(eeprom_address, query)
     return np.array(query[1].data)
Beispiel #9
0
 def __get_eeprom(self, eeprom_address=0x50):
     # Two separate I2C transfers in case the buffer size is small
     q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00]*4000, read=True)]
     q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00]*4000, read=True)]
     self.i2c.transfer(eeprom_address, q1)
     self.i2c.transfer(eeprom_address, q2)
     return np.array(q1[1].data + q2[1].data)
Beispiel #10
0
    def read_byte(self, address):
        msgs = [I2C.Message([address], read=False)]
        self.transfer(msgs)
        msgs = [I2C.Message([address], read=True)]
        ret_msg = self.transfer(msgs)

        return (ret_msg[0].data[0])
Beispiel #11
0
	def get_eeprom(self, eeprom_address=0x50):
		# My Raspberry pi keeps timing-out here, so we split it into
		# two different transfers:...
		q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00]*4000, read=True)]
		q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00]*4000, read=True)]
		self.i2c.transfer(eeprom_address, q1)
		self.i2c.transfer(eeprom_address, q2)
		return np.array(q1[1].data + q2[1].data)
Beispiel #12
0
def minipod_reg_wr(i2c_bus_addr, dev_addr, page_addr, reg_addr, reg_value):
    i2c = I2C("/dev/i2c-1")
    i2c.transfer(TCA9548_U93_ADDR,
                 [I2C.Message([i2c_bus_addr])])  # select I2C Bus
    i2c.transfer(dev_addr, [I2C.Message([127, page_addr])])  # set the page
    i2c.transfer(dev_addr,
                 [I2C.Message([reg_addr, reg_value])])  # write to reg_addr
    i2c.close()
Beispiel #13
0
def firefly_reg_wr(i2c_bus_addr,firefly_refdes,dev_addr,reg_page,reg_addr,reg_value):
  firefly_select(firefly_refdes)
  i2c = I2C("/dev/i2c-0")
  i2c.transfer(TCA9548_U165_ADDR, [I2C.Message([i2c_bus_addr])])   # select i2c bus
  
  i2c.transfer(dev_addr, [I2C.Message([127,reg_page])]) # select the register page
  i2c.transfer(dev_addr, [I2C.Message([reg_addr,reg_value])]) # write the value to registers
  i2c.close()		
Beispiel #14
0
 def __wait_for_data(self):
     query = [I2C.Message([0x02]), I2C.Message([0x00], read=True)]
     done = False
     while not done:
         self.i2c.transfer(self.address, query)
         if not (query[1].data[0]%2 == 1):
             time.sleep(0.005)
         else:
             done = True
Beispiel #15
0
    def Transaction(self, req):
        """Perform a Notecard transaction and return the result."""
        req_json = prepareRequest(req, self._debug)
        rsp_json = ""

        while not self.lock():
            pass

        try:
            self._sendPayload(req_json)

            chunk_len = 0
            received_newline = False
            start = time.time()
            transaction_timeout_secs = 10
            while True:
                time.sleep(.001)
                reg = bytearray(2)
                reg[0] = 0
                reg[1] = chunk_len
                readlen = chunk_len + 2
                buf = bytearray(readlen)
                if use_periphery:
                    msgs = [I2C.Message(reg), I2C.Message(buf, read=True)]
                    self.i2c.transfer(self.addr, msgs)
                    buf = msgs[1].data
                elif use_micropython:
                    self.i2c.writeto(self.addr, reg, False)
                    self.i2c.readfrom_into(self.addr, buf)
                else:
                    self.i2c.writeto_then_readfrom(self.addr, reg, buf)
                available = buf[0]
                good = buf[1]
                data = buf[2:2 + good]
                if good > 0 and buf[-1] == 0x0a:
                    received_newline = True
                try:
                    rsp_json += "".join(map(chr, data))
                except:
                    pass
                chunk_len = min(available, self.max)
                if chunk_len > 0:
                    continue
                if received_newline:
                    break
                if (time.time() >= start + transaction_timeout_secs):
                    raise Exception("notecard request or response was lost")
                time.sleep(0.05)

        finally:
            self.unlock()

        if self._debug:
            print(rsp_json.rstrip())
        rsp = json.loads(rsp_json)
        return rsp
Beispiel #16
0
def test_repstart():
  i2c = I2C("/dev/i2c-1")
  write = I2C.Message([0x88])
  read = I2C.Message([0x0]*2, read=True) # read 2 bytes

  msgs = [write, read]
  i2c.transfer(0x7F, msgs)

  value = msgs[1].data[1]*256 + msgs[1].data[0]
  return hex(value)
Beispiel #17
0
    def __read_top_and_bottom_blocks(self):
        read_block = [I2C.Message([0x0A]), I2C.Message([0x00]*258, read=True)]
        self.i2c.transfer(self.address, read_block)
        top_data = np.array(copy.copy(read_block[1].data))

        read_block = [I2C.Message([0x0B]), I2C.Message([0x00]*258, read=True)]
        self.i2c.transfer(self.address, read_block)
        bottom_data = np.array(copy.copy(read_block[1].data))

        return top_data, bottom_data
Beispiel #18
0
def tca6424_reg_rd(i2c_bus_addr,dev_addr,reg_addr):
  i2c = I2C("/dev/i2c-0")
  i2c.transfer(TCA9548_U165_ADDR, [I2C.Message([i2c_bus_addr])]) # select i2c bus

  read = I2C.Message([0x0]*1, read=True)
  i2c.transfer(dev_addr, [I2C.Message([reg_addr])])      # set reg_addr
  i2c.transfer(dev_addr, [read])
  i2c.close()
  
  print('read back is 0x{0:x}' .format(read.data[0]))
  return read.data[0]
Beispiel #19
0
    def get_temp_humid(self):
        """
        get_temp_humid()

        Get the temperature and humidity from the sensor. Returns an array with two integers - temp. [0] and humidity [1]
        """
        # Loop sentinel values
        failCount = 0
        # Commands to get data temp and humidity data from AM2315
        cmd_data = bytearray((self.cmdReadReg, 0x00, 0x04))

        # If we have failed more than twice to read the data, or have finished getting data break the loop.
        while (failCount < 2):
            try:
                cmd_msgs = [I2C.Message(cmd_data)]
                self.__i2c_master.transfer(self.i2c_addr, cmd_msgs)

                # Wait for the sensor to supply data to read.
                time.sleep(0.01)

                # Now read 8 bytes from the AM2315.
                read_data = bytearray(
                    (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
                read_msgs = [I2C.Message(read_data, read=True)]
                self.__i2c_master.transfer(self.i2c_addr, read_msgs)

                # Break the string we want out of the array the transaction returns.
                rawTH = bytearray(read_msgs[0].data)

                # Confirm the command worked by checking the response for the command we executed
                # and the number of bytes we asked for.
                if ((rawTH[0] == self.cmdReadReg) or
                    (rawTH[0] == self.cmdReadReg + 0x80)) and (rawTH[1]
                                                               == 0x04):

                    # And the MSB and LSB for each value together to yield our raw values.
                    humidRaw = (rawTH[2] << 8) | rawTH[3]

                    # Get signed int from AND'd temperature bytes.
                    tempRaw = self.get_signed((rawTH[4] << 8) | rawTH[5])

                    # The return data is scaled up by 10x, so compensate.
                    return (tempRaw / 10.0, humidRaw / 10.0)
            # No connection yet
            except AttributeError:
                pass
            # We usually fail to read data 50% of the time because the sensor goes to sleep, so try twice.
            except IOError:
                if failCount > 1:
                    raise IOError(
                        "am2315 IO Error: failed to read from sensor.")
                else:
                    failCount = failCount + 1
        return None, None
Beispiel #20
0
def i2c_read_reg(devregaddr):
    """
    使用periphery i2c库读取功能测试
    """
    # 构造数据结构
    # 第一个Message为要读取的设备地址
    # 第二个Message用于存放读取回来的消息,注意其中添加的read=True
    msgs = [I2C.Message([devregaddr]), I2C.Message([0x00], read=True)]
    # 发送消息,发送到i2cSlaveAddr
    i2c.transfer(I2CSLAVEADDR, msgs)
    print("从寄存器 0x{:02x} 读取出: 0x{:02x}".format(devregaddr, msgs[1].data[0]))
Beispiel #21
0
def minipod_reg_rd(i2c_bus_addr, dev_addr, page_addr, reg_addr):
    i2c = I2C("/dev/i2c-1")
    i2c.transfer(TCA9548_U93_ADDR,
                 [I2C.Message([i2c_bus_addr])])  # select i2c bus

    read = I2C.Message([0x0], read=True)
    i2c.transfer(dev_addr, [I2C.Message([127, page_addr])])  # set the page
    i2c.transfer(dev_addr, [I2C.Message([reg_addr])])  # set reg_addr
    i2c.transfer(dev_addr, [read])
    i2c.close()

    return read.data[0]
Beispiel #22
0
def firefly_reg_rd(i2c_bus_addr,firefly_refdes,dev_addr,reg_page,reg_addr):
  firefly_select(firefly_refdes)
  i2c = I2C("/dev/i2c-0")
  i2c.transfer(TCA9548_U165_ADDR, [I2C.Message([i2c_bus_addr])])   # select i2c bus

  read = I2C.Message([0x0]*1, read=True)
  i2c.transfer(dev_addr, [I2C.Message([127,reg_page])]) # select the register page
  i2c.transfer(dev_addr, [I2C.Message([reg_addr])])      # set reg_addr
  i2c.transfer(dev_addr, [read])
  i2c.close()
  
  print('read back is 0x{0:x}' .format(read.data[0]))
  return read.data[0] 
def ltc2499_current_mon(dev_addr, reg_addr0, reg_addr1):
    i2c = I2C("/dev/i2c-1")
    i2c.transfer(dev_addr, [I2C.Message([reg_addr1, reg_addr0])])
    sleep(0.5)
    read = I2C.Message([0x0] * 4, read=True)
    i2c.transfer(dev_addr, [read])
    adc_code = bytes(bytearray(read.data)).encode('hex')
    i2c.close()
    resolution = 2500. / 0x80000000
    if (int(adc_code, 16) < 0x40000000):
        amplitude = 0
    else:
        amplitude = (int(adc_code, 16) - 0x40000000) * resolution
    return amplitude / 40
Beispiel #24
0
def read_sensor():
    address = 0x06
    register = 0x01
    command = 0x03
    unused = 0x00

    sensor_id = detect_line_follower()

    if sensor_id == 2:
        raise NotImplementedError(
            'line follower (black board) is not supported with the line_follower.line_sensor module\n\
			please use the di_sensors.easy_line_follower.EasyLineFollower class to interface with both line followers (black + red boards)\n\
			check https://di-sensors.readthedocs.io documentation to find out more')

    try:
        i2c = I2C('/dev/i2c-' + str(bus_number))

        read_bytes = 10 * [0]
        msg1 = [I2C.Message([register, command] + 3 * [unused])]
        msg2 = [I2C.Message(read_bytes, read=True)]
        # we meed to do 2 transfers so we can avoid using repeated starts
        # repeated starts don't go hand in hand with the line follower
        i2c.transfer(address, msg1)
        i2c.transfer(address, msg2)

    except I2CError as error:
        return 5 * [-1]

    # unpack bytes received and process them
    # bytes_list = struct.unpack('10B',read_results[0])
    output_values = []
    input_values = msg2[0].data

    for step in range(5):
        # calculate the 16-bit number we got
        sensor_buffer[step].append(input_values[2 * step] * 256 +
                                   input_values[2 * step + 1])

        # if there're too many elements in the list
        # then remove one
        if len(sensor_buffer[step]) > max_buffer_length:
            sensor_buffer[step].pop(0)

        # eliminate outlier values and select the most recent one
        filtered_value = statisticalNoiseReduction(sensor_buffer[step], 2)[-1]

        # append the value to the corresponding IR sensor
        output_values.append(filtered_value)

    return output_values
Beispiel #25
0
    def get_co2(self):
        try:
            # Set the FCR register
            self.write_register(self.FCR, 0x07)
            # cmd_data = bytearray((self.FCR, 0x07))
            # cmd_msgs = [I2C.Message(cmd_data)]
            # self.__i2c_master.transfer(self.i2c_addr, cmd_msgs)

            # Read TXLVL register
            msgs = [I2C.Message([self.TXLVL]), I2C.Message([0x00], read=True)]
            self.__i2c_master.transfer(self.i2c_addr, msgs)
            txlvl = msgs[1].data[0]

            # Verify TXLVL
            if txlvl >= len(self.cmd_measure):
                # Send Command Bytes to THR Register
                cmd_data = bytearray([self.THR] + self.cmd_measure)
                cmd_msgs = [I2C.Message(cmd_data)]
                self.__i2c_master.transfer(self.i2c_addr, cmd_msgs)

                # Wait for the sensor to supply data to read.
                time.sleep(0.1)

                # Now read 9 bytes from the MHZ16.
                read_data = bytearray(
                    (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
                read_msgs = [I2C.Message(read_data, read=True)]
                self.__i2c_master.transfer(self.i2c_addr, read_msgs)

                # Break the string we want out of the array the transaction returns.
                response = bytearray(read_msgs[0].data)

                ## Compute checksum
                checksum = 0
                for i in range(0, 9):
                    checksum += response[i]

                # Confirm the command worked by checking the response for the command we executed
                # and validating checksum
                if (response[0] == 0xFF) and (response[1]
                                              == 0x9C) and (checksum % 256
                                                            == 0xFF):
                    return (response[2] << 24) + (response[3] << 16) + (
                        response[4] << 8) + response[5]

        except IOError:
            raise IOError("mhz16 IO Error: failed to read from sensor.")

        return None
Beispiel #26
0
  def get_eeprom(self, eeprom_address=0x50):
    """Get dump of EEPROM configuration data from the HTPA device.

    Keyword Arguments:
        eeprom_address {hexadecimal} -- Communication address (default: {0x50})

    Returns:
        np.array(bytes) -- EEPROM bytes
    """
    # Two separate I2C transfers in case the buffer size is small
    q1 = [I2C.Message([0x00, 0x00]), I2C.Message([0x00]*4000, read=True)]
    q2 = [I2C.Message([0x0f, 0xa0]), I2C.Message([0x00]*4000, read=True)]
    self.i2c.transfer(eeprom_address, q1)
    self.i2c.transfer(eeprom_address, q2)
    return np.array(q1[1].data + q2[1].data)
Beispiel #27
0
def do_i2c_block_write(i2c, block):
    page, register, value = block
    # change page if page changes
    if page != do_i2c_block_write.page:
        set_page(i2c, page)
        do_i2c_block_write.page = page
    print('  Writing     : {0:02x}{1:02x}'.format(register, value))
    i2c.transfer(SI5345_U137_ADDR, [I2C.Message([register, value])])
Beispiel #28
0
def detect_line_follower():
    """
	returns
	0 - for no line follower detected
	1 - for detecting the line follower (red board)
	2 - for detecting the line follower (black board)
	"""
    i2c = I2C('/dev/i2c-' + str(bus_number))
    address = 0x06

    # see if the device is up and running
    device_on = False
    try:
        read_byte = [0]
        msg1 = [I2C.Message(read_byte, read=True)]
        i2c.transfer(address, msg1)
        device_on = True
    except:
        pass

    if device_on is True:
        # then it means we have a line follower connected
        # we still don't know whether it is the black one or the red one
        board = 1
        try:
            read_bytes = 20 * [0]
            msg1 = [I2C.Message([0x12])]
            msg2 = [I2C.Message(read_bytes, read=True)]
            i2c.transfer(address, msg1)
            i2c.transfer(address, msg2)

            name = ""
            for c in range(20):
                if msg2[0].data[c] != 0:
                    name += chr(msg2[0].data[c])
                else:
                    break

            if name == 'Line Follower':
                board = 2
        except:
            pass
        return board
    else:
        return 0
Beispiel #29
0
    def write(self, address, pointer_reg, data_array):
        """
        Performs a standard I2C write opreation on a particular
        address. Requires the 7-bit I2C address, the pointer
        register, and a data array of the data package to send.

        """
        msgs = [I2C.Message([pointer_reg, data_array], read=False)]
        self.handle.transfer(address, msgs)
def ltc2499_temp_mon(dev_addr, reg_addr0, reg_addr1):
    # two delays as the chip is slow
    sleep(0.5)
    i2c = I2C("/dev/i2c-1")
    i2c.transfer(dev_addr,
                 [I2C.Message([reg_addr1, reg_addr0])])  # Reg for read
    sleep(0.5)

    read = I2C.Message([0x0] * 4, read=True)
    i2c.transfer(dev_addr, [read])
    i2c.close()
    adc_code = int(bytes(bytearray(read.data)).encode('hex'), 16)

    resolution = 2500. / 0x80000000
    amplitude = (adc_code - 0x40000000) * resolution
    if (adc_code == 0x3FFFFFFF): amplitude = -1

    temperature = 326 - 0.5 * amplitude
    return temperature