Skip to content
Snippets Groups Projects
Commit 8d162f3f authored by Jonathan Klimt's avatar Jonathan Klimt
Browse files

added i2c bus scan functionality

parent 080cdc87
Branches
Tags v2.11.3
No related merge requests found
Pipeline #987574 failed
#include "driver/i2c.h"
#include "driver/gpio.h"
/**
* @brief Scans the I2C bus and visualizes found devices
*
* @param[in] port I2C port to scan
* @param[in] gpio_sda SDA pin nr.
* @param[in] gpio_scl SCL pin nr.
* @param[in] frequency I2C bus frequency
*/
void i2c_bus_scan(i2c_port_t port, gpio_num_t gpio_sda, gpio_num_t gpio_scl,
uint32_t frequency);
#include "driver/i2c.h"
#include "esp_log.h"
static const char* TAG = "LEGOS I2C";
#define I2C_MASTER_TX_BUF_DISABLE 0
#define I2C_MASTER_RX_BUF_DISABLE 0
#define WRITE_BIT I2C_MASTER_WRITE
#define READ_BIT I2C_MASTER_READ
#define ACK_CHECK_EN 0x1
#define ACK_CHECK_DIS 0x0
static esp_err_t i2c_master_driver_initialize(i2c_port_t port,
gpio_num_t gpio_sda, gpio_num_t gpio_scl, uint32_t frequency)
{
i2c_config_t conf = {
.mode = I2C_MODE_MASTER,
.sda_io_num = gpio_sda,
.sda_pullup_en = GPIO_PULLUP_ENABLE,
.scl_io_num = gpio_scl,
.scl_pullup_en = GPIO_PULLUP_ENABLE,
.master.clk_speed = frequency,
// .clk_flags = 0, /*!< Optional, you can use
// I2C_SCLK_SRC_FLAG_* flags to choose i2c source clock here. */
};
return i2c_param_config(port, &conf);
}
void i2c_bus_scan(i2c_port_t port, gpio_num_t gpio_sda,
gpio_num_t gpio_scl, uint32_t frequency)
{
i2c_master_driver_initialize(port, gpio_sda, gpio_scl, frequency);
i2c_driver_install(port, I2C_MODE_MASTER, I2C_MASTER_RX_BUF_DISABLE,
I2C_MASTER_TX_BUF_DISABLE, 0);
uint8_t address;
printf("I2C Bus Map\n");
printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f\r\n");
for (int i = 0; i < 128; i += 16) {
printf("%02x: ", i);
for (int j = 0; j < 16; j++) {
fflush(stdout);
address = i + j;
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
i2c_master_write_byte(
cmd, (address << 1) | WRITE_BIT, ACK_CHECK_EN);
i2c_master_stop(cmd);
esp_err_t ret
= i2c_master_cmd_begin(port, cmd, 50 / portTICK_PERIOD_MS);
i2c_cmd_link_delete(cmd);
if (ret == ESP_OK) {
printf("%02x ", address);
} else if (ret == ESP_ERR_TIMEOUT) {
printf("UU ");
} else {
printf("-- ");
}
}
printf("\r\n");
}
i2c_driver_delete(port);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment