74 lines
1.9 KiB
C
Raw Normal View History

2025-02-15 17:44:58 -05:00
#ifndef I2C_H
#define I2C_H
#define I2C_BUS_PORT 0
#include <driver/i2c_master.h>
2025-02-16 14:31:50 -05:00
// TODO: Refactor tags for-each class.
2025-02-15 17:44:58 -05:00
static const char *TAG = "lcd-panel";
2025-02-16 14:31:50 -05:00
/**
* Encapsulates ESP I2C creation and usage.
*/
2025-02-15 17:44:58 -05:00
struct I2C {
2025-02-16 14:31:50 -05:00
/**
* Construct and initialize an ESP I2C master bus.
* An I2C constructor may only be called one time in any application.
*
* @param sda GPIO pin number for SDA
* @param scl GPIO pin number for SCL
* @param rst GPIO pin number for RST
*/
2025-02-15 17:44:58 -05:00
I2C(gpio_num_t sda, gpio_num_t scl, int rst = -1) :
2025-02-16 14:31:50 -05:00
I2C((i2c_master_bus_config_t) {
2025-02-15 17:44:58 -05:00
.i2c_port = I2C_BUS_PORT,
.sda_io_num = sda,
.scl_io_num = scl,
.clk_source = I2C_CLK_SRC_DEFAULT,
.glitch_ignore_cnt = 7,
.flags {
.enable_internal_pullup = true,
},
2025-02-16 14:31:50 -05:00
},
rst
) { }
/**
* Construct an ESP I2C master bus given a specific ESP I2C configuration.
* An I2C constructor may only be called one time in any application.
*
* @param config ESP I2C master bus configuration.
* @param rst GPIO pin number for RST
*/
explicit I2C(i2c_master_bus_config_t config, int rst = -1) :
esp_bus_config_(config),
rst_num_(rst)
2025-02-15 17:44:58 -05:00
{
2025-02-16 14:31:50 -05:00
i2c_master_bus_handle_t i2c;
2025-02-15 18:26:26 -05:00
ESP_LOGI(TAG, "Initializing new master I2C bus");
2025-02-16 14:31:50 -05:00
ESP_ERROR_CHECK(i2c_new_master_bus(&esp_bus_config_, &i2c));
2025-02-15 17:44:58 -05:00
}
~I2C() = default;
2025-02-16 14:31:50 -05:00
/**
* ESP I2C master bus handle getter.
* This will fail if an I2C instance was never constructed.
*/
static i2c_master_bus_handle_t get()
{
i2c_master_bus_handle_t i2c = nullptr;
ESP_ERROR_CHECK(i2c_master_get_bus_handle(0, &i2c));
return i2c;
}
2025-02-15 18:26:26 -05:00
2025-02-16 14:31:50 -05:00
/// ESP I2C master bus configuration used during initialization.
2025-02-15 18:26:26 -05:00
i2c_master_bus_config_t esp_bus_config_;
2025-02-16 14:31:50 -05:00
/// RST GPIO pin number.
int rst_num_;
2025-02-15 17:44:58 -05:00
};
#endif //I2C_H