49 lines
1.5 KiB
C
49 lines
1.5 KiB
C
#pragma once
|
|
#include "driver/i2c.h"
|
|
|
|
#include "esp_log.h"
|
|
|
|
#define I2C_MASTER_TX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
|
|
#define I2C_MASTER_RX_BUF_DISABLE 0 /*!< I2C master doesn't need buffer */
|
|
#define I2C_MASTER_SDA_IO CONFIG_I2C_SDA
|
|
#define I2C_MASTER_SCL_IO CONFIG_I2C_SCL
|
|
|
|
#define I2C_MASTER_FREQ_HZ 400000 /*!< I2C master clock frequency */
|
|
#define I2C_MASTER_NUM CONFIG_I2C_NUM
|
|
|
|
static const char *I2C_TAG = "APP_I2C";
|
|
|
|
void init_i2c() {
|
|
i2c_config_t conf = {
|
|
.mode = I2C_MODE_MASTER,
|
|
.sda_io_num = I2C_MASTER_SDA_IO,
|
|
.scl_io_num = I2C_MASTER_SCL_IO,
|
|
.sda_pullup_en = GPIO_PULLUP_ENABLE,
|
|
.scl_pullup_en = GPIO_PULLUP_ENABLE,
|
|
.master.clk_speed = I2C_MASTER_FREQ_HZ,
|
|
};
|
|
i2c_param_config(I2C_MASTER_NUM, &conf);
|
|
ESP_ERROR_CHECK(i2c_driver_install(I2C_MASTER_NUM, conf.mode,
|
|
I2C_MASTER_RX_BUF_DISABLE,
|
|
I2C_MASTER_TX_BUF_DISABLE, 0));
|
|
|
|
ESP_LOGI(I2C_TAG, "I2C initialized");
|
|
}
|
|
|
|
uint8_t i2c_check_slave_exists(uint8_t address) {
|
|
ESP_LOGI(I2C_TAG, "Checking if slave 0x%2x exists", address);
|
|
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
|
|
i2c_master_start(cmd);
|
|
i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, 1);
|
|
i2c_master_stop(cmd);
|
|
esp_err_t ret = i2c_master_cmd_begin(I2C_NUM_0, cmd, 100 / portTICK_RATE_MS);
|
|
i2c_cmd_link_delete(cmd);
|
|
|
|
if (ret == ESP_OK) {
|
|
ESP_LOGW(I2C_TAG, "Slave 0x%2x found", address);
|
|
return 1;
|
|
} else {
|
|
ESP_LOGW(I2C_TAG, "Slave 0x%2x not found", address);
|
|
return 0;
|
|
}
|
|
} |