Created
March 9, 2021 16:17
-
-
Save comdet/06330864c9740ff6b60bfae2cd8a6327 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "driver/i2c.h" | |
#define DATA_LENGTH 512 | |
#define RW_TEST_LENGTH 4 | |
#define I2C_SLAVE_SCL_IO 5 | |
#define I2C_SLAVE_SDA_IO 4 | |
#define I2C_SLAVE_NUM 1 | |
#define I2C_SLAVE_TX_BUF_LEN (2 * DATA_LENGTH) | |
#define I2C_SLAVE_RX_BUF_LEN (2 * DATA_LENGTH) | |
#define ESP_SLAVE_ADDR 0x33 | |
uint8_t *data_wr = (uint8_t *)malloc(DATA_LENGTH); | |
uint8_t *data_rd = (uint8_t *)malloc(DATA_LENGTH); | |
static esp_err_t i2c_slave_init(void) | |
{ | |
i2c_port_t i2c_slave_port = (i2c_port_t)I2C_SLAVE_NUM; | |
i2c_config_t conf_slave; | |
conf_slave.sda_io_num = (gpio_num_t)I2C_SLAVE_SDA_IO; | |
conf_slave.sda_pullup_en = GPIO_PULLUP_ENABLE; | |
conf_slave.scl_io_num = (gpio_num_t)I2C_SLAVE_SCL_IO; | |
conf_slave.scl_pullup_en = GPIO_PULLUP_ENABLE; | |
conf_slave.mode = I2C_MODE_SLAVE; | |
conf_slave.slave.addr_10bit_en = 0; | |
conf_slave.slave.slave_addr = ESP_SLAVE_ADDR; | |
esp_err_t err = i2c_param_config(i2c_slave_port, &conf_slave); | |
if (err != ESP_OK) { | |
printf("....... error to config ........\n"); | |
return err; | |
} | |
return i2c_driver_install(i2c_slave_port, conf_slave.mode, I2C_SLAVE_RX_BUF_LEN, I2C_SLAVE_TX_BUF_LEN, 0); | |
} | |
static void disp_buf(uint8_t *buf, int len) | |
{ | |
for (int i = 0; i < len; i++) { | |
printf("%02x ", buf[i]); | |
if ((i + 1) % 16 == 0) { | |
printf("\n"); | |
} | |
} | |
printf("\n"); | |
} | |
void setup() { | |
Serial.begin(115200); | |
delay(1000); | |
int err = i2c_slave_init(); | |
if(err != 0){ | |
printf("init i2c error = %d\n",err); | |
} | |
} | |
void loop() { | |
i2c_port_t i2c_slave_port = (i2c_port_t)I2C_SLAVE_NUM; | |
//check master write data | |
int size = i2c_slave_read_buffer(i2c_slave_port, data_rd, RW_TEST_LENGTH, 1000 / portTICK_RATE_MS); | |
printf("Slave read: [%d] bytes ----\n", size); | |
//write buffer to master when needed | |
size_t d_size = i2c_slave_write_buffer(i2c_slave_port, data_wr, RW_TEST_LENGTH, 1000 / portTICK_RATE_MS); | |
if (d_size == 0) { | |
printf("i2c slave tx buffer full\n"); | |
} | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment