[技术问答] 如何读取I2C总线上未知器件的地址

[复制链接]
1156|4
 楼主| xinpian101 发表于 2023-11-28 15:15 | 显示全部楼层 |阅读模式
如何读取I2C总线上未知器件的地址?
如果不确定一个器件的地址是什么,怎么读取出来。
 楼主| xinpian101 发表于 2023-11-28 15:21 | 显示全部楼层
  1. #include "Wire.h"

  2. void setup() {
  3.   Serial.begin(115200);
  4.   Wire.begin();
  5. }

  6. void loop() {
  7.   byte error, address;
  8.   int nDevices = 0;

  9.   delay(5000);

  10.   Serial.println("Scanning for I2C devices ...");
  11.   for(address = 0x01; address < 0x7f; address++){
  12.     Wire.beginTransmission(address);
  13.     error = Wire.endTransmission();
  14.     if (error == 0){
  15.       Serial.printf("I2C device found at address 0x%02X\n", address);
  16.       nDevices++;
  17.     } else if(error != 2){
  18.       Serial.printf("Error %d at address 0x%02X\n", error, address);
  19.     }
  20.   }
  21.   if (nDevices == 0){
  22.     Serial.println("No I2C devices found");
  23.   }
  24. }
 楼主| xinpian101 发表于 2023-11-28 15:21 | 显示全部楼层
这是Arduino里面的,不大懂,这个endTransmission是怎么知道有没有的。
gejigeji521 发表于 2023-11-28 22:04 | 显示全部楼层
遍历所有地址,测试是否有应答信号。
gejigeji521 发表于 2023-11-28 22:04 | 显示全部楼层
由于7位地址的话,只有127个地址,所以遍历很容易实现。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

129

主题

1650

帖子

1

粉丝
快速回复 在线客服 返回列表 返回顶部