Skip to content

Commit

Permalink
expose option to use an externally controlled bus handle
Browse files Browse the repository at this point in the history
  • Loading branch information
atanisoft authored and ZivLow committed Nov 10, 2024
1 parent 449106f commit 78270b5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
21 changes: 21 additions & 0 deletions interface/ina226_interface.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ INA226::INA226(const gpio_num_t sda_io_num, const gpio_num_t scl_io_num, const u
throw std::runtime_error(std::string("INA226 driver initialization failed. err = ") + start_driver.error().what());
}

INA226::INA226(i2c_master_bus_handle_t bus_handle, const uint16_t address, const uint32_t scl_frequency)
: i2c_bus_handle(bus_handle),
i2c_dev_cfg{
.dev_addr_length = I2C_ADDR_BIT_LEN_7,
.device_address = address,
.scl_speed_hz = scl_frequency,
}
{
esp_err_t err = i2c_master_bus_add_device(i2c_bus_handle, &i2c_dev_cfg, &i2c_dev_handle);
if (err != ESP_OK)
throw std::runtime_error("I2C add device failed. err = " + std::to_string(err));

err = CreateMutex(Lock);
if (err != ESP_OK)
throw std::runtime_error("I2C mutex creation failed. err = " + std::to_string(err));

auto start_driver = InitDriver();
if (start_driver.has_value() == false)
throw std::runtime_error(std::string("INA226 driver initialization failed. err = ") + start_driver.error().what());
}

esp_err_t INA226::CreateMutex(SemaphoreHandle_t &mutex) {
mutex = xSemaphoreCreateMutex();
if (!mutex) {
Expand Down
9 changes: 9 additions & 0 deletions interface/ina226_interface.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ class INA226 : public INA226_Driver {
*/
INA226(const gpio_num_t sda_io_num = static_cast<gpio_num_t>(CONFIG_I2C_MASTER_SDA), const gpio_num_t scl_io_num = static_cast<gpio_num_t>(CONFIG_I2C_MASTER_SCL), const uint16_t address = CONFIG_INA226_I2C_ADDRESS, const uint32_t scl_frequency = CONFIG_I2C_MASTER_FREQUENCY, const i2c_port_num_t i2c_port_num = static_cast<i2c_port_num_t>(CONFIG_I2C_MASTER_PORT_NUM));

/**
* @brief Initializes the INA226 using an existing I2C handle.
*
* @param[in] i2c_bus_handle Existing I2C bus handle to use for this INA226.
* @param[in] address I2C address of INA226. Defaults to 0x40.
* @param[in] scl_frequency Frequency of SCL pin. Defaults to 100000.
*/
INA226(i2c_master_bus_handle_t i2c_bus_handle, const uint16_t address = CONFIG_INA226_I2C_ADDRESS, const uint32_t scl_frequency = CONFIG_I2C_MASTER_FREQUENCY);

protected:
/**
* @brief I2C write function for ESP-IDF. Converts from little endian (ESP-IDF) to big endian (INA226).
Expand Down

0 comments on commit 78270b5

Please sign in to comment.