I'm using an STM326050 MCU and I'm trying to get gyroscope and accelerometer data using an MPU6050(MPU6050 Registers, MPU6050 Datasheet. I've made sure the MPU6050 is properly initialized and ready using the following code:
HAL_StatusTypeDef initMPU6050(void) {
uint8_t check;
HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, MPU6050_WHO_AM_I_REG, 1, &check, 1, 1000);
if (check == 0x68) {
for (int i = 0; i < 20; i++) {
HAL_GPIO_TogglePin(GPIOA, LD2_Pin);
HAL_Delay(200);
}
// the regSet variables set the gyro and accel to 500deg/s and 4g respectively
uint8_t gyroRegSet = 0x08;
uint8_t accelRegSet = 0x08;
uint8_t pwrMgmtSet = 0;
HAL_StatusTypeDef ret;
ret = HAL_I2C_Mem_Write(&hi2c1, MPU6050_ADDR, MPU6050_GYRO_REG, 1, &gyroRegSet, 1, 100);
if (ret != HAL_OK) {return HAL_ERROR;}
HAL_Delay(50);
ret = HAL_I2C_Mem_Write(&hi2c1, MPU6050_ADDR, MPU6050_ACCEL_REG, 1, &accelRegSet, 1, 100);
if (ret != HAL_OK) {return HAL_ERROR;}
HAL_Delay(50);
ret = HAL_I2C_Mem_Write(&hi2c1, MPU6050_ADDR, MPU6050_PWE_MGMT_REG, 1, &pwrMgmtSet, 1, 100);
if (ret != HAL_OK) {return HAL_ERROR;}
return HAL_OK;
}
return HAL_ERROR;
Afterwords, I tried to gather Gyroscope data in the X direction (making sure one axis works before expanding to all 6-axises) using the following code:
HAL_StatusTypeDef readGyroGx(uint16_t* Gx, HAL_StatusTypeDef init) {
if (init != HAL_OK) {return HAL_ERROR;}
uint8_t gxh;`
uint8_t gxl;
HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, 0x43, 1, &gxh, 1, 1000);
HAL_I2C_Mem_Read(&hi2c1, MPU6050_ADDR, 0x44, 1, &gxl, 1, 1000);
Gx = (gxh<<8) | gxl;
}
And displaying it to a screen using:
uint16_t buf[20];
HAL_StatusTypeDef init = initMPU6050();
uint16_t gx;
while (1)
{
readGyroGx(&gx, init);
sprintf((char*)buf, "%u \r\n", gx);
HAL_UART_Transmit(&huart2, buf, strlen((char*)buf), 1000);
HAL_GPIO_TogglePin(GPIOA, LD2_Pin);
HAL_Delay(100);
}
I've tried rotating and moving the MPU6050 around but no matter how I moved it the Gx value seems to be stuck at the value 60254. Any help would be much appreciated. Thanks.
I found the issue, turns out with my
Gx = (gxh<<8) | gxl;
line I needed to use *Gx not Gx. And for outputting data, I was supposed to use%hu
no %u.