You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

STM32 CubeIDE下BNO086 I²C中断与复位异常问题求助

问题:STM32 CubeIDE下BNO086 IMU初始化异常、ROTATION_VECTOR无法启用

环境与背景

在STM32微控制器(CubeIDE环境)中,使用BNO08x的STM32 I2C库读取BNO086的角度值。I2C通信能正常响应,但存在两个核心问题:

  • 中断触发但无有效数据,ROTATION_VECTOR始终未成功启用
  • 初始化后传感器反复复位,无法稳定输出有效数据

手动逐行调试时能收到正确数据包,但ROTATION_VECTOR的启用条件始终不成立。Arduino平台的SparkFun BNO08x库可正常运行,但STM32 HAL驱动下传感器无法维持初始化状态。已确认I2C地址正确,INT引脚配置为EXTI,Reset引脚为GPIO_Output,BOOT引脚未接线。

附上main.c代码:

/* USER CODE BEGIN Header */
/*******************************************************************************
* @file : main.c
* @brief : Main program body
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
*/

/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "usart.h"
#include "tim.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include <stdio.h>
#include "BNO_08x_I2C.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
volatile uint8_t BNO_Ready = 0;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void PeriphCommonClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void I2C_Scan_Bus(void)
{
    HAL_StatusTypeDef result;
    uint8_t i;
    printf("Scanning I2C bus...\r\n");
    for (i = 1; i < 128; i++)
    {
        /*
        * HAL_I2C_IsDeviceReady returns HAL_OK if the device responds,
        * else HAL_ERROR or HAL_BUSY or HAL_TIMEOUT
        */
        result = HAL_I2C_IsDeviceReady(&hi2c1, (i << 1), 1, 10);
        if (result == HAL_OK)
        {
            printf("Found device at address 0x%02X\r\n", i);
        }
    }
    printf("Scan complete.\r\n\n");
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
    /* USER CODE BEGIN 1 */
    /* USER CODE END 1 */
    /* MCU Configuration--------------------------------------------------------*/
    /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
    HAL_Init();
    /* USER CODE BEGIN Init */
    /* USER CODE END Init */
    /* Configure the system clock */
    SystemClock_Config();
    /* Configure the peripherals common clocks */
    PeriphCommonClock_Config();
    /* USER CODE BEGIN SysInit */
    /* USER CODE END SysInit */
    /* Initialize all configured peripherals */
    MX_GPIO_Init();
    MX_I2C1_Init();
    MX_LPUART1_UART_Init();
    MX_TIM2_Init();
    /* USER CODE BEGIN 2 */
    ///* -----------------------------------------------------------------------------------------------
    BNO_RST_On;
    // BNO_BOOT_On;
    // Initialisation du capteur BNO08x
    if (BNO_Init() == HAL_OK)
    {
        BNO_setHighAccuracyMode();
        printf("BNO init OK\r\n");
    }
    else
    {
        // Si erreur
        printf("Erreur d'initialisation BNO08x !\n");
        while (1);
    }
    /* USER CODE END 2 */
    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1)
    {
        if (BNO_Ready)
        {
            if (isResetOccurred())
            { // Fonction modifiée en bool au lieu de uint8_t, à changer si pas concluant ::::::::::::::::::::::::::::::::::::::::::::::::::
                // Réactive le feature si reset
                // printf("rotation vector = %02X\n", ROTATION_VECTOR);
                if (BNO_setFeature(ROTATION_VECTOR, 100000, 0) == HAL_OK)
                {
                    // printf("%d\n", BNO_getFeature(ROTATION_VECTOR));
                    printf("Reset Occurred. Set feature OK!\r\n");
                    // printf("SensorId = %d\n", sensorData.sensorId);
                }
            }
            // BNO_setFeature(ROTATION_VECTOR, 100000, 0);
            if (BNO_dataAvailable() == HAL_OK)
            {
                BNO_setFeature(ROTATION_VECTOR, 100000, 0);
                printf("ReportID = 0x%02X\r\n", sensorData.sensorId);
            }
            if ((BNO_dataAvailable() == HAL_OK) && (sensorData.sensorId == ROTATION_VECTOR))
            {
                /*if (sensorData.sensorId == ROTATION_VECTOR) {*/
                sensorData.sensorId = 0; // Reset l'ID pour la prochaine frame
                rpy = BNO_getRollPitchYaw();
                printf("Roll: %.2f, Pitch: %.2f, Yaw: %.2f\r\n", rpy.Roll, rpy.Pitch, rpy.Yaw);
                // BNO_RotationVectorWAcc_t rot = getRotationVector();
                // printf("I: %.3f, J: %.3f, K: %.3f\n", rot.I, rot.J, rot.K);
                // BNO_Gyroscope_t gyro = getGyroscope();
                // printf("X: %.3f, Y: %.3f, Z: %.3f\n", gyro.X, gyro.Y, gyro.Z);
                /*} else {
                printf("SensorId reçu = %d\n", sensorData.sensorId);
                }*/
            }
        }
        /* USER CODE END WHILE */
        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    /** Configure the main internal regulator output voltage
    */
    __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
    /** Initializes the RCC Oscillators according to the specified parameters
    * in the RCC_OscInitTypeDef structure.
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE
                                       | RCC_OSCILLATORTYPE_MSI;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.MSIState = RCC_MSI_ON;
    RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
    RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
    /** Configure the SYSCLKSource, HCLK, PCLK1 and PCLK2 clocks dividers
    */
    RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK4 | RCC_CLOCKTYPE_HCLK2
                                  | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
                                  | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
    RCC_ClkInitStruct.AHBCLK2Divider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.AHBCLK4Divider = RCC_SYSCLK_DIV1;
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
    {
        Error_Handler();
    }
}
/**
* @brief Peripherals Common Clock Configuration
* @retval None
*/
void PeriphCommonClock_Config(void)
{
    RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
    /** Initializes the peripherals clock
    */

    PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SMPS;
    PeriphClkInitStruct.SmpsClockSelection = RCC_SMPSCLKSOURCE_HSI;
    PeriphClkInitStruct.SmpsDivSelection = RCC_SMPSCLKDIV_RANGE1;
    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
    {
        Error_Handler();
    }
    /* USER CODE BEGIN Smps */
    /* USER CODE END Smps */
}
/* USER CODE BEGIN 4 */
/* Callback interruption GPIO */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if (GPIO_Pin == GPIO_PIN_0)
    {
        BNO_Ready = 1;
        // printf("IRQ reçu, ready!\n");
    }
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
    /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
    /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
*  file: pointer to the source file name
*  line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN 6 */
    /* User can add their own implementation to report the file name and line number,
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

解决方案建议

1. 修正复位时序

BNO086的复位引脚需严格遵循时序要求,当前代码缺少必要延迟:

BNO_RST_On;
HAL_Delay(10);  // 保持复位至少10ms
BNO_RST_Off;
HAL_Delay(20);  // 等待传感器完成启动

同时确保复位引脚配置为推挽输出,初始电平符合传感器要求(高电平复位,低电平正常工作)。

2. 优化ROTATION_VECTOR启用逻辑

  • 初始化完成后仅调用一次BNO_setFeature启用ROTATION_VECTOR,不要在中断循环中反复调用,避免干扰传感器配置:
    将BNO_setFeature(ROTATION_VECTOR, 100000, 0)移到BNO_Init()成功后的代码块中,与BNO_setHighAccuracyMode()放在一起。
  • 检查第三方库中BNO_setFeature的实现,确认是否正确等待传感器的配置响应,部分库可能遗漏了ACK等待逻辑。

3. 修复中断与数据读取的同步问题

  • 当前BNO_Ready被设为1后未复位,会导致循环中重复执行读取逻辑,干扰传感器状态:
    在主循环处理完数据后添加BNO_Ready = 0;,确保每次中断仅处理一次数据。
  • 中断回调中可立即触发数据读取,避免延迟:
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    if (GPIO_Pin == GPIO_PIN_0)
    {
        BNO_Ready = 1;
        BNO_readData();  // 若库提供此函数,直接读取数据
    }
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
}

4. 提升I2C通信稳定性

  • 降低I2C时钟速率至100kHz测试,BNO086推荐最高400kHz,但部分STM32 HAL配置的时序可能存在兼容性问题。
  • 确保I2C引脚使用开漏输出并接硬件上拉电阻,避免信号不稳定导致的复位或配置失败。

5. 对比官方库流程排查差异

  • 对照SparkFun Arduino库的初始化流程,检查第三方STM32库是否遗漏了关键步骤(如NVM配置、电源模式设置)。
  • 在BNO_Init()后添加传感器状态读取,确认传感器真的完成初始化,而非仅返回HAL_OK。

内容的提问来源于stack exchange,提问作者Mathias_R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 06:44:52