如何从I2CDETECT控制台输出中提取I2C地址



我是Linux环境的新手,但是由于我的新项目,我正在学习并且喜欢它(来自VXWork时代(。现在,我的问题是如何使用bash脚本从此命令" i2cdetect"过滤i2c地址。我听说我可以使用SED或AWKD扫描和搜索文本。因此,基本上我想获得每个I2C地址,例如这些0C,5B,5C,UU,6E,6F。

我感谢您得到的任何线索或帮助。

root@plnx_aarch64:/#i2cdetect -y -r 3 0 1 2 3 4 5 6 7 8 9 A B C D E F

00:-----------------------

10:--------------------

20:----------------------

30:-------------------

40:--------------------

50:------------------------------

60:--------------------6e 6f

70:uu ---------

我写了一个函数来执行此操作。我不确定是否有更好的方法,但这似乎确实有效。

import re
def get_addresses(i2cdetect_output):
    ''' Takes output from i2cdetect and extracts the addresses
        for the entries.
    '''
    # Get the rows, minus the first one
    i2cdetect_rows = i2cdetect_output.split('rn')[1:]
    i2cdetect_matrix = []
    # Add the rows to the matrix without the numbers and colon at the beginning
    for row in i2cdetect_rows:
        i2cdetect_matrix.append(filter(None, re.split(' +', row))[1:])
    # Add spaces to the first and last rows to make regularly shaped matrix
    i2cdetect_matrix[0] = ['  ', '  ', '  '] + i2cdetect_matrix[0]
    i2cdetect_matrix[7] = i2cdetect_matrix[7][:-1] + ['  ', '  ', '  ', '  ', '  ', '  ', '  ', '  ']

    # Make a list of the addresses present
    address_list = []
    for i in range(len(i2cdetect_matrix)):
        for j in range(len(i2cdetect_matrix[i])):
            if i2cdetect_matrix[i][j] not in ('  ', '--', 'UU'):
                address_list.append(str(i) + str(format(j, 'x')))
            if i2cdetect_matrix[i][j] == 'UU':
                address_list.append('UU')
    return address_list
   i2cdetect_hex_regex = re.compile(r'[0-9A-Fa-f]{2} ')
   @staticmethod
   def i2c_address_list() -> list:
      from subprocess import PIPE, Popen
      
      process = Popen(args=['/usr/sbin/i2cdetect', '-y', '1'], stdout=PIPE)
      stdout, _ = process.communicate()
      process.terminate()
      stdout = stdout.decode('ascii')
      
      address_list = I2C.i2cdetect_hex_regex.findall(stdout)
      address_list = [int(x.strip(), base=16) for x in address_list]
      
      return address_list

尝试这个尺寸!它还显示了如何运行I2C检测命令(假设您不需要Sudo;这适用于我的情况(。如您所见,i2cdetect输出中的十六进制是" hh"形式的独特之处。(注意太空字符(。列上的那些具有":":&quot。在那里而不是空间,所以它不应该捡起这些。

最新更新