#include <stdio.h>
#include "driver/i2c.h"
#define I2C_EXAMPLE_MASTER_SDA_IO 22 /*!< gpio number for I2C master data */
#define I2C_EXAMPLE_MASTER_SCL_IO 23 /*!< gpio number for I2C master clock */
#define I2C_EXAMPLE_MASTER_NUM I2C_NUM_0 /*!< I2C port number for master dev */
#define I2C_EXAMPLE_MASTER_TX_BUF_DISABLE 0 /*!< I2C master do not need buffer */
#define I2C_EXAMPLE_MASTER_RX_BUF_DISABLE 0 /*!< I2C master do not need buffer */
#define I2C_EXAMPLE_MASTER_FREQ_HZ (10 * 1000) /*!< I2C master clock frequency */
#define DATA_LENGTH 1 //18 /*!<Data buffer length for test buffer*/
#define I2C_SLAVE_ADDR (8) /*!< slave address*/
#define WRITE_BIT I2C_MASTER_WRITE /*!< I2C master write */
#define READ_BIT I2C_MASTER_READ /*!< I2C master read */
#define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0 /*!< I2C ack value */
#define NACK_VAL 0x1 /*!< I2C nack value */
static esp_err_t i2c_example_master_read_slave(i2c_port_t i2c_num, uint8_t *data_rd, size_t size)
{
esp_err_t err = ESP_OK;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(cmd, (I2C_SLAVE_ADDR << 1) | READ_BIT, ACK_CHECK_EN);
if (size > 1)
{
i2c_master_read(cmd, data_rd, size - 1, ACK_VAL);
}
i2c_master_read_byte(cmd, data_rd + size - 1, NACK_VAL);
i2c_master_stop(cmd);
err = i2c_master_cmd_begin(i2c_num, cmd, 1000 / portTICK_RATE_MS);
i2c_cmd_link_delete(cmd);
return err;
}
static void i2c_example_master_init()
{
int i2c_master_port = I2C_EXAMPLE_MASTER_NUM;
i2c_config_t conf;
conf.mode = I2C_MODE_MASTER;
conf.sda_io_num = I2C_EXAMPLE_MASTER_SDA_IO;
conf.sda_pullup_en = GPIO_PULLUP_ENABLE;
conf.scl_io_num = I2C_EXAMPLE_MASTER_SCL_IO;
conf.scl_pullup_en = GPIO_PULLUP_ENABLE;
conf.master.clk_speed = I2C_EXAMPLE_MASTER_FREQ_HZ;
esp_err_t err = i2c_param_config(i2c_master_port, &conf);
if (ESP_OK == err)
{
err = i2c_driver_install(i2c_master_port, conf.mode,
I2C_EXAMPLE_MASTER_RX_BUF_DISABLE,
I2C_EXAMPLE_MASTER_TX_BUF_DISABLE, 0);
printf("i2c_driver_install 0x%x \n", err);
}
else
{
printf("i2c_param_config fail 0x%x \n", err);
}
}
static void i2c_test_task(void *arg)
{
uint8_t data_rd[DATA_LENGTH] = {0};
int cnt = 0;
esp_err_t ret = 0;
while (1)
{
printf("cnt: %d\n", cnt++);
vTaskDelay(100 / portTICK_RATE_MS);
ret = i2c_example_master_read_slave(I2C_EXAMPLE_MASTER_NUM, data_rd, DATA_LENGTH);
if (ESP_OK == ret)
{
data_rd[DATA_LENGTH] = 0;
printf("Data: %s \n", data_rd);
}
else
{
printf("err: 0x%x %s \n", ret, esp_err_to_name(ret));
}
}
}
void app_main()
{
i2c_example_master_init();
xTaskCreate(i2c_test_task, "i2c_test_task_1", 1024 * 5, (void *)1, 10, NULL);
}