Which function? Here's the complete code for the function that reads the registers of the external device via I2C:
Code: Select all
esp_err_t Max77818::readReg(uint8_t devAddr, uint8_t regAddr, uint16_t *data)
{
esp_err_t rc;
uint32_t len;
uint8_t addrRead;
uint8_t addrWrite;
string s;
size_t bytesFree;
// portMUX_TYPE mutex = portMUX_INITIALIZER_UNLOCKED;
bytesFree = heap_caps_get_free_size(MEMORY_CAPS);
if (bytesFree < 1024)
{
ESP_LOGW(TAG, "readReg(): there are currently %d bytes free in heap.", bytesFree);
}
if (devAddr == MAX77818_ADDR_FUELGAUGE)
{
len = 2; // fuel gauge registers are 2 bytes.
}
else
{
len = 1;
}
// note about data (address) field: the ESP32 docs say to shift addresses one bit to the left,
// but it appears that the addresses supplied in the MAX77818 data sheet already have been shifted.
// keep this in mind when setting addresses from the datasheet.
addrRead = devAddr | I2C_MASTER_READ;
addrWrite = devAddr | I2C_MASTER_WRITE;
// taskENTER_CRITICAL(&mutex);
m_i2c_cmd = i2c_cmd_link_create();
if (m_i2c_cmd != nullptr)
{
//ESP_LOGI(TAG, "i2cReadReg(): m_i2c_cmd is 0x%x.", (unsigned) m_i2c_cmd);
// build the i2c transfer.
rc = (i2c_master_start(m_i2c_cmd));
rc |= (i2c_master_write_byte(m_i2c_cmd, addrWrite, true));
rc |= (i2c_master_write_byte(m_i2c_cmd, regAddr, true));
rc |= (i2c_master_start(m_i2c_cmd));
rc |= (i2c_master_write_byte(m_i2c_cmd, addrRead, true));
rc |= (i2c_master_read(m_i2c_cmd, (uint8_t *) data, len, I2C_MASTER_LAST_NACK));
rc |= (i2c_master_stop(m_i2c_cmd));
if (rc == ESP_OK)
{
}
else
{
s = Max77818_addr_str.at(regAddr);
ESP_LOGE(TAG, "readReg(): error \"%s\" on %s, register 0x%x during I2C setup.",
esp_err_to_name(rc),
s.c_str(),
regAddr);
}
// execute the i2c transfer.
rc = (i2c_master_cmd_begin(I2C_PORT_NBR, m_i2c_cmd, I2C_WAITTIME_TICKS));
if (rc == ESP_OK)
{
//ESP_LOGI(TAG, "readReg(): device address 0x%02x, register 0x%02x data read as 0x%x.", devAddr, regAddr, *data);
}
else
{
s = Max77818_addr_str.at(regAddr);
ESP_LOGE(TAG, "readReg(): error \"%s\" on %s, register 0x%x during I2C read.",
esp_err_to_name(rc),
s.c_str(),
regAddr);
}
// if this was a one-byte read, clear the high byte of the data word.
if (devAddr != MAX77818_ADDR_FUELGAUGE)
{
*data &= 0xff;
}
}
else
{
ESP_LOGE(TAG, "readReg(): i2c_cmd_link_create() call failed; terminating.");
rc = ESP_FAIL;
vTaskDelay(portMAX_DELAY); // might not keep this here.
}
i2c_cmd_link_delete(m_i2c_cmd);
// taskEXIT_CRITICAL(&mutex);
return rc;
}