cancel
Showing results for 
Search instead for 
Did you mean: 

MPU6050 with STM32F3 reading axes X,Y,Z accelerometer values problems

toufik chatour
Associate
Posted on May 28, 2018 at 14:39

I have an STM32F303 Discovery and I want to use the I2C bus to receive the x,y,z data from an accelerometer MPU6050. Does anyone have source code for this? The problem is that the address of the buffers (i2cBuff) are 0, and the Xaccel, Yaccel, Zaccel too.

Here is my code:

&sharpinclude 'main.h'

&sharpinclude 'stm32f3xx_hal.h'

I2C_HandleTypeDef hi2c1;

&sharpdefine mpu6050Address 0xD0 

uint8_t i2cBuf[8];

uint16_t ax,ay,az;

float Xaccel,Yaccel,Zaccel;

int main(void)

{      

  //HAL Initialise      

  HAL_Init();      

  //Config functions      

  GPIO_Config();      

  I2C_Config();      

  //1. Scan the I2C addresses      

  for(uint8_t i=0; i<255; i++)      

      {           

        if(HAL_I2C_IsDeviceReady(&hi2c1, i, 1, 10) == HAL_OK)           

             {   HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_12);                

                 break;          

             }      

       }      

//2. I2C Write example      

//a) Set accelerometer range (reg28)      

i2cBuf[0] = 28;            //Register address: Accelerometer config 1      

i2cBuf[1] = 0x08;          //Data to write, +-8g range      

HAL_I2C_Master_Transmit(&hi2c1, mpu6050Address, i2cBuf, 2, 10);

           

//3. I2C Read example      

//Request to read from a register (reg28)      

i2cBuf[0] = 28;             //Register address: Accelerometer config 1      

HAL_I2C_Master_Transmit(&hi2c1, mpu6050Address, i2cBuf, 1, 10);      

//Read data      

i2cBuf[1] = 0x00;      

HAL_I2C_Master_Receive(&hi2c1, mpu6050Address|0x01, &i2cBuf[1], 1, 10);   

         

while(1)      

{           

//4. Read accelerometer data     

HAL_I2C_Mem_Read(&hi2c1, mpu6050Address, 0x3B, I2C_MEMADD_SIZE_8BIT, &i2cBuf[1], 6, 10);

                  ax = -(i2cBuf[1]<<8 | i2cBuf[2]);           

                  ay = -(i2cBuf[3]<<8 | i2cBuf[4]);           

                  az =  (i2cBuf[5]<<8 | i2cBuf[6]);            

                  Xaccel = ax/8192.0;           

                  Yaccel = ay/8192.0;           

                  Zaccel = az/8192.0;           

        HAL_Delay(50);      

}

}

#accelerometer #i2c #mpu6050 #stm32f3
1 REPLY 1
Alex Angulo
Associate II
Posted on June 26, 2018 at 16:54

Hello toufik!

I had the same problem and I fix it by putting a greater value in the timeout of the read() and write() operations because 10ms could be very fast for a I2C communication.

I hope it could help