STM32F411RE:程序冻结,超声波传感器不工作

Posted

技术标签:

【中文标题】STM32F411RE:程序冻结,超声波传感器不工作【英文标题】:STM32F411RE: The program freeze and the ultrasonic sensor doesn't work 【发布时间】:2021-09-11 03:46:19 【问题描述】:

我有一个使用 STM32F411RE 板的 C 语言程序,但我无法启动它,当我调试它时它会卡住,但在我做一些小改动之前它就可以工作了。但是当它工作时,超声波传感器在它应该识别任何物体的时候却没有识别到​​任何物体。问题是代码与其他程序非常相似,做类似的事情并且完美地工作,但我没有,我找不到解决方案。

该程序包含一个信号量,当传感器检测到 200 毫米处的物体时,该信号量会激活一个序列。顺序不太重要,关键是传感器,它计算是否有任何具有功能 ultrasonidos 的对象,但我什至无法到达这一行,因为程序冻结或什么,即使当我调试它。它应该用这两条线打开两个 LED:

HAL_Delay(1000);
GPIOB->ODR |= GPIO_ODR_OD6_Msk;
GPIOA->ODR |= GPIO_ODR_OD7_Msk;

但不是这样。完整代码如下:

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include <stdio.h>

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* 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 ---------------------------------------------------------*/
TIM_HandleTypeDef htim11;
int pulsado = 0;
int contador = 0;
int volatile times = 0;
int cercanos = 0;
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_TIM11_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)

  /* USER CODE BEGIN 1 */
  int modo = 0;
  int control = 0;
  int counter_parpadeo = 0;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
  void ultrasonidos();
  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  MX_TIM11_Init();
  /* USER CODE BEGIN 2 */

  HAL_TIM_Base_Start_IT(&htim11);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  
    /* USER CODE END WHILE */
    HAL_Delay(1000);
    GPIOB->ODR |= GPIO_ODR_OD6_Msk; //Encender Verde Coches
    GPIOA->ODR |= GPIO_ODR_OD7_Msk; //Encender Rojo Peatones
    printf("SE INICIA Y SE PONEN EL VERDE DE COCHES Y EL ROJO DE PEATONES");
    printf("VA A ACTIVAR EL ULTRASONIDOS");
    ultrasonidos();
    printf("SE HA ACTIVADO EL ULTRASONIDOS");
    if (cercanos == 1)
    
      printf("SE HAN DETECTADO OBJETOS CERCANOS");
      modo = 1;
      control = 1;
      counter_parpadeo = 0;
      while (control == 1)
      
        switch (modo)
        
        case 1:
          printf("SE INICIA EL CICLO");
          counter_parpadeo = 0;
          GPIOB->ODR &= ~GPIO_ODR_OD6_Msk; //Apagar verde coches
          GPIOC->ODR |= GPIO_ODR_OD7_Msk;  //Encender amarillo coches
          printf("AMARILLO COCHES");
          HAL_Delay(5000);
          modo = 2;
          break;
        case 2:
          printf("SEGUNDO FASE");
          GPIOC->ODR &= ~GPIO_ODR_OD7_Msk; //Apagar amarillo coches
          GPIOA->ODR |= GPIO_ODR_OD9_Msk;  //Encender rojo coches
          GPIOA->ODR &= ~GPIO_ODR_OD7_Msk; //Apagamos rojo peatones
          GPIOA->ODR |= GPIO_ODR_OD6_Msk;  //Encender verde peatones
          printf("VERDE PEATONES");
          HAL_Delay(5000);
          modo = 3;
          break;
        case 3:
        printf("TERCERA FASE");
          while (counter_parpadeo < 3)
          
            GPIOA->ODR &= ~GPIO_ODR_OD6_Msk; //Apagar verde peatones
            HAL_Delay(100);
            GPIOA->ODR |= GPIO_ODR_OD6_Msk; //Encender verde peatones
            HAL_Delay(100);
            counter_parpadeo++;
          
          printf("PARPADEO");
          HAL_Delay(5000);
          modo = 4;
          break;
        case 4:
          printf("CUARTA FASE");
          GPIOA->ODR &= ~GPIO_ODR_OD6_Msk; //Apagar verde peatones
          GPIOA->ODR &= ~GPIO_ODR_OD9_Msk; //Apagar rojo coches
          GPIOB->ODR |= GPIO_ODR_OD6_Msk;  //Encendemos verde coches
          GPIOA->ODR |= GPIO_ODR_OD7_Msk;  //Encendemos rojo peatones
          printf("VERDE COCHES");
          HAL_Delay(5000);
          modo = 1;
          control = 0;
          pulsado = 0;
          cercanos = 0;
          times = 0;
          break;
        
      
      /* USER CODE BEGIN 3 */
    
    HAL_Delay(5000);
    /* 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_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 16;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  
    Error_Handler();
  
  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  
    Error_Handler();
  


/**
  * @brief TIM11 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM11_Init(void)


  /* USER CODE BEGIN TIM11_Init 0 */

  /* USER CODE END TIM11_Init 0 */

  /* USER CODE BEGIN TIM11_Init 1 */

  /* USER CODE END TIM11_Init 1 */
  htim11.Instance = TIM11;
  htim11.Init.Prescaler = 83;
  htim11.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim11.Init.Period = 9;
  htim11.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  //htim11.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim11) != HAL_OK)
  
    Error_Handler();
  
  /* USER CODE BEGIN TIM11_Init 2 */

  /* USER CODE END TIM11_Init 2 */


/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)


  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  
    Error_Handler();
  
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */


/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)

  GPIO_InitTypeDef GPIO_InitStruct = 0;

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, LD2_Pin | VerdeP_Pin | RojoP_Pin | RojoC_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(AmarilloC_GPIO_Port, AmarilloC_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(VerdeC_GPIO_Port, VerdeC_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : B1_Pin */
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : LD2_Pin VerdeP_Pin RojoP_Pin RojoC_Pin */
  GPIO_InitStruct.Pin = LD2_Pin | VerdeP_Pin | RojoP_Pin | RojoC_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pin : AmarilloC_Pin */
  GPIO_InitStruct.Pin = AmarilloC_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(AmarilloC_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : PA8 */
  GPIO_InitStruct.Pin = GPIO_PIN_8;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pin : Boton_Pin */
  GPIO_InitStruct.Pin = Boton_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(Boton_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : VerdeC_Pin */
  GPIO_InitStruct.Pin = VerdeC_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(VerdeC_GPIO_Port, &GPIO_InitStruct);

  /* EXTI interrupt init*/
  HAL_NVIC_SetPriority(EXTI15_10_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(EXTI15_10_IRQn);


/* USER CODE BEGIN 4 */
/*void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)

  __disable_irq();
  if (GPIO_Pin == GPIO_PIN_10)
    pulsado = 1;
  __enable_irq();
*/

void cambiarModoPin(int modo)

  GPIO_InitTypeDef GPIO_InitStruct = 0;
  if (modo == 0) //Output
  
    GPIO_InitStruct.Pin = GPIO_PIN_8;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  
  else if (modo == 1) //Input
  
    GPIO_InitStruct.Pin = GPIO_PIN_8;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
  


int __io_putchar(int ch)

  uint8_t c[1];
  c[0] = ch & 0x00FF;
  HAL_UART_Transmit(&huart2, &*c, 1, 100);
  return ch;


int _write(int file, char *ptr, int len)

  int DataIdx;
  for (DataIdx = 0; DataIdx < len; DataIdx++)
  
    __io_putchar(*ptr++);
  
  return len;


int calcularDistanciaCm(int veces)

  int distancia = 0;
  distancia = (veces * 10) / 58;
  printf("CALCULA DISTANCIA:");
  printf("%d", distancia);
  return distancia;


void ultrasonidos()

  int times2 = 0;
  int times3 = 0;
  cambiarModoPin(0); //Modo output
  times = 0;
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
  printf("SE METE EN EL ULTRASONIDO");

  while(times >= 1)
    printf("DENTRO DEL WHILE DEL TIMES:");
    printf("%d", times);
  
  printf("TIMES 1:");
  printf("%d", times);
  cambiarModoPin(1); //Modo Input

  while(!(GPIOA->IDR & GPIO_IDR_ID8_Msk))

  
  times2 = times;
  printf("TIMES 2:");
  printf("%d", times2);
  while((GPIOA->IDR & GPIO_IDR_ID8_Msk)) 

  
  times3 = times;
  printf("TIMES 3:");
  printf("%d", times3);
    if (calcularDistanciaCm(times3-times2) < 20) 
        printf("HAY OBJETOS CERCA");
        cercanos = 1;
    
  


void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)

  if (htim->Instance == TIM11)
  
    printf("SALTA LA EXCEPCION PARA SUMAR LOS TIMES");
    times++;
  


/* 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 */

  /* 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.
  * @param  file: pointer to the source file name
  * @param  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 his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */

#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

【问题讨论】:

我建议备份您的代码,然后将您所拥有的内容分解为一个较小的程序,以重现您正在寻找的错误。您会发现这里很少有人对挖掘 500 行代码感兴趣,如果您将错误隔离到人们会有所帮助的程度,那么您很有可能已经找到并修复了该错误。如果没有,你要么遗漏了一点信息,要么有一个真正的偷偷摸摸的问题值得被解决和记录,以供未来的程序员学习。 【参考方案1】:

对于程序冻结问题,如果在 HAL_Delay(100) 处发生冻结,则表示未启用 Systick 中断,导致 HAL_Delay 内部出现无限循环。

在 SystemClock_Config() 之后添加此语句以启用 Systick 中断。

SET_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk);

至于超声波传感器,我不确定您使用的是哪个传感器,HC SR04 有两个引脚,一个用于触发(输出引脚),一个用于回波(输入引脚)。即使您需要单个 GPIO,也无需更改引脚类型以输入将 GPIO 配置为开漏,这样您就可以设置触发并在读取回波响应时读取。 让我知道结果。

【讨论】:

使用 SET_BIT 可以调试,我现在已经评论了超声波传感器功能,看看会发生什么,但它再次卡在这些行中:` GPIOB->ODR |= GPIO_ODR_OD6_Msk; GPIOA->ODR |= GPIO_ODR_OD7_Msk;` 当 while 开始时,在 HAL_Delay(1000) 之后;传感器类似于 HC-SR04,但没有触发器和回波,它只有一个信号引脚。 调试时,您可以从 SFR 窗口检查 GPIOB 的更改,确保 LED 已正确配置为输出,您也可以尝试使用 HAL_GPIO_TogglePin 函数来切换输出引脚。如需进一步参考,请查看参考手册st.com/resource/en/reference_manual/…。对于超声波传感器,请尝试查找您购买它的部件号或来源。在任何情况下,改变 I/O 模式都不是一个好主意,最好使用开漏模式,否则最终会损坏引脚 我找不到部件号,但这是我正在使用的传感器:seeedstudio.com/Ultra-Sonic-range-measurement-module-p-626.html 显然它通过在 if (cercanos == 1) 中采用 de HAL_DELAY(1000) 并删除:HAL_Delay(1000); GPIOB->ODR |= GPIO_ODR_OD6_Msk; GPIOA->ODR |= GPIO_ODR_OD7_Msk;但现在,它只能工作特定的次数,然后它将永远执行循环,而传感器不会捕捉到任何东西。

以上是关于STM32F411RE:程序冻结,超声波传感器不工作的主要内容,如果未能解决你的问题,请参考以下文章

使用超声波传感器HY-SRF05时,VCC端接在STM32F103C8T6单片机的5V引脚?

基于STM32F103C8T6(HAL库)的HC-SR501红外人体传感及HC-SR04超声波测距

基于STM32F103C8T6(HAL库)的HC-SR501红外人体传感及HC-SR04超声波测距

基于STM32F103C8T6(HAL库)的HC-SR501红外人体传感及HC-SR04超声波测距

基于STM32F103C8T6(HAL库)的HC-SR501红外人体传感及HC-SR04超声波测距

stm32f411ceu6怎么用Micropythor烧录固件