Files
Leo-ElixirLights/components/lighting/src/i2cPort.cpp
T

75 lines
2.3 KiB
C++

/**
* @file i2cPort.cpp
* @author Gustice
* @brief C++ Wrapper for I2C-interface
*
* @copyright Copyright (c) 2020
*/
#include "i2cPort.hpp"
#include "esp_log.h"
const int TxBufDisabled = 0; /*!< I2C master doesn't need buffer */
const int RxBufDisabled = 0; /*!< I2C master doesn't need buffer */
constexpr int I2C_TOOL_TIMEOUT_VALUE_MS = 50;
#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 */
I2cMaster::I2cMaster(i2c_port_t port, gpio_num_t sda, gpio_num_t scl) : Port(port) {
i2c_master_bus_config_t i2c_bus_config{
.i2c_port = port,
.sda_io_num = sda,
.scl_io_num = scl,
.clk_source = I2C_CLK_SRC_DEFAULT,
.glitch_ignore_cnt = 7,
};
i2c_bus_config.flags.enable_internal_pullup = 1;
ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_bus_config, &_busHandle));
}
bool I2cMaster::probe(uint8_t addr) {
esp_err_t ret = i2c_master_probe(_busHandle, addr, I2C_TOOL_TIMEOUT_VALUE_MS);
return ret == ESP_OK;
}
I2cMaster::Slave::Slave(I2cMaster &interface, uint8_t addr, ClockRate rate) : Addr(addr), Interface(interface) {
i2c_device_config_t i2c_dev_conf{
.device_address = addr,
.scl_speed_hz = rate,
};
ESP_ERROR_CHECK(i2c_master_bus_add_device(interface._busHandle, &i2c_dev_conf, &_devHandle));
}
I2cMaster::Slave::~Slave() {
i2c_master_bus_rm_device(_devHandle);
}
bool I2cMaster::Slave::writeTo(const std::vector<uint8_t> &data) {
esp_err_t ret = i2c_master_transmit(_devHandle, data.data(), data.size(), I2C_TOOL_TIMEOUT_VALUE_MS);
if (ret != ESP_OK) {
if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGW("I2C", "Bus is busy");
}
return false;
}
return true;
}
std::vector<uint8_t> I2cMaster::Slave::readFrom(const std::vector<uint8_t> &address, unsigned size) {
if (size == 0) {
return {};
}
std::vector<uint8_t> buffer(size);
esp_err_t ret = i2c_master_transmit_receive(_devHandle, address.data(), address.size(), buffer.data(), buffer.size(), I2C_TOOL_TIMEOUT_VALUE_MS);
if (ret != ESP_OK) {
if (ret == ESP_ERR_TIMEOUT) {
ESP_LOGW("I2C", "Bus is busy");
}
return {};
}
return buffer;
}
constexpr int DisableBuffer = 0; /*!< I2C master doesn't need buffers */