我无法从STM32F103上的mpu6050用I2C获取数据

时间:2019-12-19 05:11:40

标签: stm32 i2c mpu6050

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

November 19,2019 4
November 20,2019 2

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

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
}

1 个答案:

答案 0 :(得分: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总线上的错误,并进行一些枚举以从函数返回错误/状态。