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:

#include "main.h"
#include "stm32f3xx_hal.h"

/* Private variables-----*/
I2C_HandleTypeDef hi2c1;
uint8_t i;
uint8_t i2cBuff[8];
uint16_t ax,ay,az;
float Xaccel,Yaccel,Zaccel;

#define mpu6050Address 0xD0

int main(void)
   /* Configure the system clock */

   /* USER CODE BEGIN 2 */
   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);

    /* USER CODE END 2 */

    /* Infinite loop */
    while (1)

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

       ax = -(i2cBuff[1]<<8 | i2cBuff[2]);
       ay = -(i2cBuff[3]<<8 | i2cBuff[4]);
       az = -(i2cBuff[5]<<8 | i2cBuff[6]);

       Xaccel = ax/8192.0;
       Yaccel = ay/8192.0;
       Zaccel = az/8192.0;

      /* USER CODE BEGIN 3 */

      /* USER CODE END 3 */


I had the same problem and I just fix it by increasing the timeout in Read() operations. Try with this:

HAL_I2C_Mem_Read(&hi2c1, mpu6050Address, 0x3B, I2C_MEMADD_SIZE_8BIT, &i2cBuff[1], 6, 100);
| improve this answer | |

Reading examples elsewhere this program appears to be missing the initial "wake up" signal.

There's an example at https://playground.arduino.cc/Main/MPU-6050#short

This starts by setting register 0x6B to zero. Apparently this is the power management register, and since the device starts up in sleep mode it is required before the device will return results.

| improve this answer | |
  • \$\begingroup\$ thanks for your answer , but even when i did it the variables don't whants to changes. \$\endgroup\$ – Abdelkader Ben May 25 '18 at 10:17
  • \$\begingroup\$ I'm starting from the assumption that the devices are communicating, but I see that you aren't testing the return value for HAL_I2C_Mem_Read, and it is possible that the device simply isn't responding. One test would be to just send the sequence start-address_byte-stop and see if it acknowledges it. If it turns out to be returning NAK all the time then you have a hardware problem such as a different hardwired device address. Having said that I also find that the STM HAL functions are a bit "opaque", and I can't see how to perform such a basic test. \$\endgroup\$ – Oliver Broad May 26 '18 at 10:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.