0

我是新的 I2C 通信。我检查了一些正在运行的代码。我使用了他们使用的功能。但我无法获得任何数据。我想知道 I2C 是否必须进行初始配置?问题出在哪里。这是我写的函数:

void GetI2CAccelerometer(uint8_t slaveAddress,uint8_t accelData[6])
{   
    // slaveAddress=0x68 (default address is written in datasheet)  
    HAL_I2C_Master_Transmit(&hi2c1,slaveAddress<<1,1,0x3B,1,200);
    HAL_I2C_Master_Receive(&hi2c1,slaveAddress<<1,accelData,6,200);
    HAL_I2C_Mem_Read(&hi2c1,(slaveAddress<<1)+1,0x3B,1,accelData,1,200);
    // i tried this function too but not working
}

我用 CubeMX 创建了这个项目。这是初始 I2C 配置,并且 GPIO_A 时钟线在另一个我没有写的函数中被激活:

static void MX_I2C1_Init(void) 
{
    hi2c1.Instance = I2C1;
    hi2c1.Init.ClockSpeed = 100000;
    hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
    hi2c1.Init.OwnAddress1 = 208;
    hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
    hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
    hi2c1.Init.OwnAddress2 = 0;
    hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
    hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;

    if (HAL_I2C_Init(&hi2c1) != HAL_OK)
    {
        Error_Handler();
    }
}
4

1 回答 1

0

首先,最好使用DMA或IT数据交换。轮询不好,但可以用于测试。

您必须放置指向数据的指针,而不是数据本身。好的做法是这样的:

void GetI2CAccelerometer(I2C_HandleTypeDef * hi2c, uint8_t slaveAddress, uint8_t * accelData, size_t size) {
    uint8_t request = 0x3B;

    // slaveAddress=0x68 (default address is written in datasheet)
    // HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
    while (HAL_I2C_Master_Transmit(hi2c, slaveAddress << 1, (uint8_t*)request, 1, 200) != HAL_OK) {
        // Use FreeRTOS vTaskDelay(1) and/or check errors here
        // And check timeout or you will hang over here
    }

    //HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
    while (HAL_I2C_Master_Receive(hi2c, slaveAddress << 1, accelData, size, 200) != HAL_OK) {
        // Use FreeRTOS vTaskDelay(1) and/or check errors here
        // And check timeout or you will hang over here
    }

    while (HAL_I2C_GetState(hi2c) != HAL_I2C_STATE_READY) {
        // Use FreeRTOS vTaskDelay(1) and/or check errors here
        // And check timeout or you will hang over here
    }
}

然后通过函数请求数据:

uint8_t accelData[6];

GetI2CAccelerometer(&hi2c1, 0x68, accelData, 6);

这对测试没问题,但对生产不利。获取数据,然后重写以使用 I2C DMA 或 IT。检查 I2C 总线上的错误并进行一些枚举以从函数返回错误/状态。

于 2019-12-19T13:31:37.400 回答