简体   繁体   English

如何使用Python在Raspberry Pi上列出I2C地址?

[英]How to list I2C address on Raspberry Pi using Python?

My goal is to be able to see the list of avalible i2c addresses as soon as my program runs. 我的目标是能够在我的程序运行时立即看到可用的i2c地址列表。 The current program has the ability to list the addresses by user input through the following code: 当前程序可以通过以下代码通过用户输入列出地址:

while True:  
    if input.upper().startswith("LIST_ADDR"):  
        devices = device.list_i2c_devices()  
        for i in range(len (devices)):
            print devices[i]  

I have been able to use the code with using only the bottom 3 lines, however I now have five i2c devices currently attached to the Pi. 我仅使用底部3行就可以使用该代码,但是现在我有5个i2c设备连接到了Pi。 Using just the three lines of code is giving me on IndexError: string index out of range. 仅使用三行代码就给了我IndexError:超出范围的字符串索引。 To this I can keep calling the program about four or five times and then it will run without issues. 为此,我可以继续调用该程序大约四到五次,然后它将正常运行。 I was just wondering if there was a better way to achieve what I am looking for the program to do without having the error. 我只是想知道是否有更好的方法来实现我正在寻找的程序而不会出现错误。

I am still pretty new to coding so thank you in advance for your patience. 我对编码还是很陌生,所以在此先感谢您的耐心配合。

If you just want to test the I2C connection with raspberry Pi then you can use this code which will help you to detect all the I2C address of all the devuces in one go 如果您只想用树莓派测试I2C连接,则可以使用此代码,它可以帮助您一次性检测所有设备的所有I2C地址。

import os
import subprocess
import time

p = subprocess.Popen(['i2cdetect', '-y','1'],stdout=subprocess.PIPE,) 
#cmdout = str(p.communicate())

for i in range(0,9):
  line = str(p.stdout.readline())

print(line)

Basically I am executing linux command in Python by using this process 基本上我通过使用此过程在Python中执行linux命令

Hope this will help you out 希望这会帮到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM