esp32 i2c总线扫描

printf("[PRESSURE] Scanning I2C bus...\n");
uint8_t devices_found = 0;
for (uint8_t addr = 0x08; addr < 0x78; addr++) {
  i2c_cmd_handle_t cmd = i2c_cmd_link_create();
  i2c_master_start(cmd);
  i2c_master_write_byte(cmd, (addr << 1) | I2C_MASTER_WRITE, true);
  i2c_master_stop(cmd);
  ret = i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, pdMS_TO_TICKS(50));
  i2c_cmd_link_delete(cmd);

  if (ret == ESP_OK) {
    printf("[PRESSURE] Found device at address 0x%02X\n", addr);
    devices_found++;
  }

// 每扫描8个地址让出CPU时间,防止看门狗超时
  if ((addr & 0x07) == 0) {
    vTaskDelay(pdMS_TO_TICKS(1));
  }
}
if (devices_found == 0) {
  printf("[PRESSURE] No I2C devices found! Check hardware connections.\n");
} else {
  printf("[PRESSURE] Total devices found: %d\n", devices_found);
}
 

 

posted @ 2026-01-23 11:23  bk街头狂舞  阅读(9)  评论(0)    收藏  举报