void I2CTransfer(uint16_t deviceAddr, uint8_t cmdArray[], uint8_t dataArray[], uint16_t cmdLen, uint16_t dataLen, uint16_t flag)
{
    // This function handles I2C communication with the BQ27441 battery gauge.
    // It is used by i2cReadRegister and i2cWriteRegister for both read and write operations.
    // First, it checks the flag to determine whether to perform a read or write operation.
    // Then, based on the flag, it sends the write command and data to the BQ27441 device.
    
    deviceAddr = BQ27441_G1_ADDR;
    
    // Check the flag
    if (flag == I2C_FLAG_WRITE_READ)
    {
        // Send write command and data
        LL_I2C_HandleTransfer(I2C1, deviceAddr << 1, LL_I2C_ADDRSLAVE_7BIT, cmdArray, cmdLen, LL_I2C_MODE_RELOAD, LL_I2C_GENERATE_START_WRITE);
        while (!LL_I2C_IsActiveFlag_TXIS(I2C1)) { }
        LL_I2C_TransmitData8(I2C1, *dataArray);
        while (!LL_I2C_IsActiveFlag_TC(I2C1)) { }

        // Generate start condition for read operation
        LL_I2C_HandleTransfer(I2C1, deviceAddr << 1, LL_I2C_ADDRSLAVE_7BIT, cmdArray, cmdLen, LL_I2C_MODE_RELOAD, LL_I2C_GENERATE_START_READ);
        while (!LL_I2C_IsActiveFlag_RXNE(I2C1)) { }
        *dataArray = LL_I2C_ReceiveData8(I2C1);
        while (!LL_I2C_IsActiveFlag_TC(I2C1)) { }
    }
    else if (flag == I2C_FLAG_WRITE_WRITE)
    {
        // Send write command and data
        LL_I2C_HandleTransfer(I2C1, deviceAddr << 1, LL_I2C_ADDRSLAVE_7BIT, cmdArray, cmdLen, LL_I2C_MODE_RELOAD, LL_I2C_GENERATE_START_WRITE);
        while (!LL_I2C_IsActiveFlag_TXIS(I2C1)) { }
        LL_I2C_TransmitData8(I2C1, *dataArray);
        while (!LL_I2C_IsActiveFlag_TC(I2C1)) { }

        // Send second write command and data
        LL_I2C_HandleTransfer(I2C1, deviceAddr << 1, LL_I2C_ADDRSLAVE_7BIT, cmdArray, cmdLen, LL_I2C_MODE_RELOAD, LL_I2C_GENERATE_START_WRITE);
        while (!LL_I2C_IsActiveFlag_TXIS(I2C1)) { }
        LL_I2C_TransmitData8(I2C1, *(dataArray + 1));
        while (!LL_I2C_IsActiveFlag_TC(I2C1)) { }
    }
}

static uint16_t i2cReadRegister(uint16_t addr, uint8_t regOffset)
{
    uint16_t result = 0x00;

    uint8_t cmdArray[1];
    uint8_t dataArray[2];

    cmdArray[0] = regOffset;
    I2CTransfer(addr << 1, cmdArray, dataArray, 1, 2, I2C_FLAG_WRITE_READ);

    result = (dataArray[1] << 8) | (dataArray[0]);
    return result;
    //return dataArray[0];
}

static void i2cWriteRegister(uint16_t addr, uint8_t regOffset, uint8_t writeData)
{
    uint8_t cmdArray[1];
    uint8_t dataArray[2];

    cmdArray[0] = regOffset;
    dataArray[0] = writeData;
    I2CTransfer(addr << 1, cmdArray, dataArray, 1, 2, I2C_FLAG_WRITE_WRITE);
}
I2C Communication Function for BQ27441 Battery Gauge using LL Library

原文地址: https://www.cveoy.top/t/topic/nggS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录