ESP32基于ESPIDF I2C设备探测和使用
- 📍I2C接口介绍和参考:
https://docs.espressif.com/projects/esp-idf/zh_CN/stable/esp32/api-reference/peripherals/i2c.html
📓I2C 主机探测
- 主要主要利用
i2c_master_probe()
函数,来检测设备是否已经连接到 I2C 总线上。如果该函数返回ESP_OK
,则表示该设备已经被检测到。
单独使用发送数据函数
i2c_master_transmit
、i2c_master_transmit_receive()
函数,并不能有效检测到目标地址。
- 📝 I2C设备探测实现:
void i2c_scan_devices()
{
uint8_t address;
esp_err_t ret;
bool found = false;
ESP_LOGI("I2C", "Scanning I2C devices...");
i2c_master_bus_config_t i2c_mst_config_1 = {
.clk_source = I2C_CLK_SRC_DEFAULT,
.i2c_port = 0,
.scl_io_num = EXAMPLE_PIN_NUM_SCL,
.sda_io_num = EXAMPLE_PIN_NUM_SDA,
.glitch_ignore_cnt = 7,
.flags.enable_internal_pullup = true,
};
i2c_master_bus_handle_t bus_handle;
for (address = 1; address < 127; address++)
{
ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config_1, &bus_handle));
ret = i2c_master_probe(bus_handle, (uint16_t)address, -1);// 探测设备
ESP_ERROR_CHECK(i2c_del_master_bus(bus_handle));
if (ret == ESP_OK)
{
ESP_LOGI("I2C", "Device found at address: 0x%02X", address);
found = true;
}
vTaskDelay(100 / portTICK_PERIOD_MS);
}
if (!found)
{
ESP_LOGI("I2C", "No I2C devices found");
}
}
- MPU6050
- I2C SSD1306
- AT24C02
AT24C02数据读取
- 驱动函数:
void at24c02_read_data(uint8_t mem_addr, uint8_t *data, size_t len) {
i2c_master_dev_handle_t dev_handle;
i2c_device_config_t dev_config = {
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = AT24C02_ADDR,
.scl_speed_hz = I2C_MASTER_FREQ_HZ,
};
// 创建设备句柄
esp_err_t ret = i2c_master_bus_add_device(bus_handle, &dev_config, &dev_handle);
if (ret != ESP_OK) {
ESP_LOGE("AT24C02", "Failed to add device: %s", esp_err_to_name(ret));
return;
}
// 发送要读取的存储地址
ret = i2c_master_transmit(dev_handle, &mem_addr, 1, 1000 / portTICK_PERIOD_MS);
if (ret != ESP_OK) {
ESP_LOGE("AT24C02", "Failed to send memory address: %s", esp_err_to_name(ret));
i2c_master_bus_rm_device(dev_handle);
return;
}
// 读取数据
ret = i2c_master_receive(dev_handle, data, len, 1000 / portTICK_PERIOD_MS);
if (ret != ESP_OK) {
ESP_LOGE("AT24C02", "Failed to read data: %s", esp_err_to_name(ret));
} else {
ESP_LOGI("AT24C02", "Data read successfully");
}
// 删除设备句柄
i2c_master_bus_rm_device(dev_handle);
}
- 📄读取数据
i2c_master_init();
uint8_t mem_addr = 0x00; // 要读取的存储地址
uint8_t data[35]; // 读取的数据缓冲区
size_t len = sizeof(data);
// 读取数据
at24c02_read_data(mem_addr, data, len);
// 打印读取的数据
ESP_LOGI("AT24C02", "Data at address 0x%02X:", mem_addr);
ESP_LOGI("AT24C02 Data[35]:", "%s", (char*)data);
//清空数组
memset(data, 0, sizeof(data));