找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 2360|回复: 1
收起左侧

stm32超声波测距源码(测量范围为2cm至400cm)

[复制链接]
ID:331083 发表于 2018-5-16 10:38 | 显示全部楼层 |阅读模式
最近做的超声波测距,使用的是stm32,测量范围为2cm至400cm。欢迎指正

单片机源程序如下:

  1. /**
  2.   ******************************************************************************
  3.   * @file           : main.c
  4.   * @brief          : Main program body
  5.   ******************************************************************************
  6.   ** This notice applies to any and all portions of this file
  7.   * that are not between comment pairs USER CODE BEGIN and
  8.   * USER CODE END. Other portions of this file, whether
  9.   * inserted by the user or by software development tools
  10.   * are owned by their respective copyright owners.
  11.   *
  12.   * COPYRIGHT(c) 2018 STMicroelectronics
  13.   *
  14.   * Redistribution and use in source and binary forms, with or without modification,
  15.   * are permitted provided that the following conditions are met:
  16.   *   1. Redistributions of source code must retain the above copyright notice,
  17.   *      this list of conditions and the following disclaimer.
  18.   *   2. Redistributions in binary form must reproduce the above copyright notice,
  19.   *      this list of conditions and the following disclaimer in the documentation
  20.   *      and/or other materials provided with the distribution.
  21.   *   3. Neither the name of STMicroelectronics nor the names of its contributors
  22.   *      may be used to endorse or promote products derived from this software
  23.   *      without specific prior written permission.
  24.   *
  25.   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26.   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27.   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28.   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  29.   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  30.   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31.   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32.   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  33.   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34.   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35.   *
  36.   ******************************************************************************
  37.   */
  38. /* Includes ------------------------------------------------------------------*/
  39. #include "main.h"
  40. #include "stm32f1xx_hal.h"

  41. /* USER CODE BEGIN Includes */
  42. #include "lcd.h"
  43. /* USER CODE END Includes */

  44. /* Private variables ---------------------------------------------------------*/
  45. TIM_HandleTypeDef htim1;

  46. SRAM_HandleTypeDef hsram1;

  47. /* USER CODE BEGIN PV */
  48. /* Private variables ---------------------------------------------------------*/

  49. /* USER CODE END PV */

  50. /* Private function prototypes -----------------------------------------------*/
  51. void SystemClock_Config(void);
  52. static void MX_GPIO_Init(void);
  53. static void MX_TIM1_Init(void);
  54. static void MX_FSMC_Init(void);
  55. static void MX_NVIC_Init(void);

  56. /* USER CODE BEGIN PFP */
  57. /* Private function prototypes -----------------------------------------------*/

  58. /* USER CODE END PFP */

  59. /* USER CODE BEGIN 0 */
  60. uint16_t  over;
  61. uint16_t  a;
  62. uint16_t  b;
  63. uint16_t  c;
  64. uint16_t  d;



  65. //uint16_t  f;
  66. //uint16_t  g;
  67. //uint16_t  h;
  68. //uint16_t  j;
  69. //uint16_t  k;
  70. //uint8_t i[8];

  71. void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
  72. {
  73. if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_6)==0)
  74. {  d=__HAL_TIM_GET_COUNTER(&htim1);
  75. //  uint16_t distance;
  76. //        distance=d*17/1000;
  77.         
  78.         //调试部分
  79.         
  80. //        sprintf((char*)i,"%d",distance);
  81. //        LCD_ShowString(30,60,200,16,16,(uint8_t*)i);
  82.         //
  83. }

  84. if(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_6)==1)
  85. {
  86.   __HAL_TIM_SET_COUNTER(&htim1,0x00);
  87.                         //调试部分
  88. //        g=__HAL_TIM_GET_COUNTER(&htim1);        
  89. //        sprintf((char*)i,"%d",g);
  90. //        LCD_ShowString(30,30,200,16,16,(uint8_t*)i);        

  91. }

  92.         
  93. }
  94. /* USER CODE END 0 */

  95. /**
  96.   * @brief  The application entry point.
  97.   *
  98.   * @retval None
  99.   */
  100. int main(void)
  101. {
  102.   /* USER CODE BEGIN 1 */

  103.   /* USER CODE END 1 */

  104.   /* MCU Configuration----------------------------------------------------------*/

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

  107.   /* USER CODE BEGIN Init */

  108.   /* USER CODE END Init */

  109.   /* Configure the system clock */
  110.   SystemClock_Config();

  111.   /* USER CODE BEGIN SysInit */
  112.    uint16_t distance;
  113.   /* USER CODE END SysInit */

  114.   /* Initialize all configured peripherals */
  115.   MX_GPIO_Init();
  116.   MX_TIM1_Init();
  117.   MX_FSMC_Init();

  118.   /* Initialize interrupts */
  119.   MX_NVIC_Init();
  120.   /* USER CODE BEGIN 2 */
  121.       HAL_TIM_Base_Start_IT(&htim1);
  122.       LCD_Init();
  123.             POINT_COLOR=RED;
  124.       uint8_t i[8];

  125.   /* USER CODE END 2 */

  126.   /* Infinite loop */
  127.   /* USER CODE BEGIN WHILE */
  128.   while (1)
  129.   {

  130.   /* USER CODE END WHILE */

  131.   /* USER CODE BEGIN 3 */
  132. //                  LCD_Clear(WHITE);
  133.                
  134.                   HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,1);
  135.       HAL_Delay(50);
  136.       HAL_GPIO_WritePin(GPIOA,GPIO_PIN_5,0);
  137.                   HAL_Delay(500);
  138.             distance=d*17/1000;
  139.                 if(distance<100)
  140.                 {
  141.                 LCD_Clear(WHITE);
  142.                 }
  143.             sprintf((char*)i,"%d",distance);
  144.            LCD_ShowString(30,60,200,16,16,(uint8_t*)i);
  145. //            LCD_ShowNum(30,90,distance,200,8);
  146.   }
  147.   /* USER CODE END 3 */

  148. }

  149. /**
  150.   * @brief System Clock Configuration
  151.   * @retval None
  152.   */
  153. void SystemClock_Config(void)
  154. {

  155.   RCC_OscInitTypeDef RCC_OscInitStruct;
  156.   RCC_ClkInitTypeDef RCC_ClkInitStruct;

  157.     /**Initializes the CPU, AHB and APB busses clocks
  158.     */
  159.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  160.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  161.   RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  162.   RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  163.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  164.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  165.   RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  166.   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  167.   {
  168.     _Error_Handler(__FILE__, __LINE__);
  169.   }

  170.     /**Initializes the CPU, AHB and APB busses clocks
  171.     */
  172.   RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  173.                               |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  174.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  175.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  176.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  177.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  178.   if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  179.   {
  180.     _Error_Handler(__FILE__, __LINE__);
  181.   }

  182.     /**Configure the Systick interrupt time
  183.     */
  184.   HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

  185.     /**Configure the Systick
  186.     */
  187.   HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  188.   /* SysTick_IRQn interrupt configuration */
  189.   HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
  190. }

  191. /**
  192.   * @brief NVIC Configuration.
  193.   * @retval None
  194.   */
  195. static void MX_NVIC_Init(void)
  196. {
  197.   /* EXTI9_5_IRQn interrupt configuration */
  198.   HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0);
  199.   HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
  200.   /* TIM1_UP_IRQn interrupt configuration */
  201.   HAL_NVIC_SetPriority(TIM1_UP_IRQn, 0, 0);
  202.   HAL_NVIC_EnableIRQ(TIM1_UP_IRQn);
  203. }

  204. /* TIM1 init function */
  205. static void MX_TIM1_Init(void)
  206. {

  207.   TIM_ClockConfigTypeDef sClockSourceConfig;
  208.   TIM_MasterConfigTypeDef sMasterConfig;

  209.   htim1.Instance = TIM1;
  210.   htim1.Init.Prescaler = 71;
  211.   htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
  212.   htim1.Init.Period = 49999;
  213.   htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  214.   htim1.Init.RepetitionCounter = 0;
  215.   htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  216.   if (HAL_TIM_Base_Init(&htim1) != HAL_OK)
  217.   {
  218.     _Error_Handler(__FILE__, __LINE__);
  219.   }

  220.   sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  221.   if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK)
  222.   {
  223.     _Error_Handler(__FILE__, __LINE__);
  224.   }

  225.   sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  226.   sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  227.   if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
  228.   {
  229.     _Error_Handler(__FILE__, __LINE__);
  230.   }

  231. }

  232. /** Configure pins as
  233.         * Analog
  234.         * Input
  235.         * Output
  236.         * EVENT_OUT
  237.         * EXTI
  238. */
  239. static void MX_GPIO_Init(void)
  240. {

  241.   GPIO_InitTypeDef GPIO_InitStruct;

  242.   /* GPIO Ports Clock Enable */
  243.   __HAL_RCC_GPIOE_CLK_ENABLE();
  244.   __HAL_RCC_GPIOA_CLK_ENABLE();
  245.   __HAL_RCC_GPIOB_CLK_ENABLE();
  246.   __HAL_RCC_GPIOG_CLK_ENABLE();
  247.   __HAL_RCC_GPIOD_CLK_ENABLE();

  248.   /*Configure GPIO pin Output Level */
  249.   HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);

  250.   /*Configure GPIO pin Output Level */
  251.   HAL_GPIO_WritePin(GPIOB, GPIO_PIN_0, GPIO_PIN_RESET);

  252.   /*Configure GPIO pin : PE4 */
  253.   GPIO_InitStruct.Pin = GPIO_PIN_4;
  254.   GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  255.   GPIO_InitStruct.Pull = GPIO_PULLUP;
  256.   HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);

  257.   /*Configure GPIO pin : PA5 */
  258.   GPIO_InitStruct.Pin = GPIO_PIN_5;
  259.   GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  260.   GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  261.   HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  262.   /*Configure GPIO pin : PA6 */
  263.   GPIO_InitStruct.Pin = GPIO_PIN_6;
  264.   GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
  265.   GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  266.   HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  267.   /*Configure GPIO pin : PB0 */
  268.   GPIO_InitStruct.Pin = GPIO_PIN_0;
  269.   GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  270.   GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  271.   HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  272. }

  273. /* FSMC initialization function */
  274. static void MX_FSMC_Init(void)
  275. {
  276.   FSMC_NORSRAM_TimingTypeDef Timing;

  277.   /** Perform the SRAM1 memory initialization sequence
  278.   */
  279.   hsram1.Instance = FSMC_NORSRAM_DEVICE;
  280.   hsram1.Extended = FSMC_NORSRAM_EXTENDED_DEVICE;
  281.   /* hsram1.Init */
  282.   hsram1.Init.NSBank = FSMC_NORSRAM_BANK4;
  283.   hsram1.Init.DataAddressMux = FSMC_DATA_ADDRESS_MUX_DISABLE;
  284.   hsram1.Init.MemoryType = FSMC_MEMORY_TYPE_SRAM;
  285.   hsram1.Init.MemoryDataWidth = FSMC_NORSRAM_MEM_BUS_WIDTH_16;
  286.   hsram1.Init.BurstAccessMode = FSMC_BURST_ACCESS_MODE_DISABLE;
  287.   hsram1.Init.WaitSignalPolarity = FSMC_WAIT_SIGNAL_POLARITY_LOW;
  288.   hsram1.Init.WrapMode = FSMC_WRAP_MODE_DISABLE;
  289.   hsram1.Init.WaitSignalActive = FSMC_WAIT_TIMING_BEFORE_WS;
  290.   hsram1.Init.WriteOperation = FSMC_WRITE_OPERATION_ENABLE;
  291.   hsram1.Init.WaitSignal = FSMC_WAIT_SIGNAL_DISABLE;
  292.   hsram1.Init.ExtendedMode = FSMC_EXTENDED_MODE_DISABLE;
  293.   hsram1.Init.AsynchronousWait = FSMC_ASYNCHRONOUS_WAIT_DISABLE;
  294.   hsram1.Init.WriteBurst = FSMC_WRITE_BURST_DISABLE;
  295.   /* Timing */
  296.   Timing.AddressSetupTime = 15;
  297.   Timing.AddressHoldTime = 15;
  298.   Timing.DataSetupTime = 255;
  299.   Timing.BusTurnAroundDuration = 15;
  300.   Timing.CLKDivision = 16;
  301.   Timing.DataLatency = 17;
  302.   Timing.AccessMode = FSMC_ACCESS_MODE_A;
  303.   /* ExtTiming */

  304.   if (HAL_SRAM_Init(&hsram1, &Timing, NULL) != HAL_OK)
  305.   {
  306.     _Error_Handler(__FILE__, __LINE__);
  307.   }

  308.   /** Disconnect NADV
  309.   */

  310.   __HAL_AFIO_FSMCNADV_DISCONNECTED();

  311. }

  312. /* USER CODE BEGIN 4 */

  313. /* USER CODE END 4 */

  314. /**
  315.   * @brief  This function is executed in case of error occurrence.
  316.   * @param  file: The file name as string.
  317.   * @param  line: The line in file as a number.
  318.   * @retval None
  319.   */
  320. void _Error_Handler(char *file, int line)
  321. {
  322.   /* USER CODE BEGIN Error_Handler_Debug */
  323.   /* User can add his own implementation to report the HAL error return state */
  324.   while(1)
  325.   {
  326.   }
  327.   /* USER CODE END Error_Handler_Debug */
  328. }

  329. #ifdef  USE_FULL_ASSERT
  330. /**
  331.   * @brief  Reports the name of the source file and the source line number
  332.   *         where the assert_param error has occurred.
  333.   * @param  file: pointer to the source file name
  334.   * @param  line: assert_param error line source number
  335.   * @retval None
  336.   */
  337. void assert_failed(uint8_t* file, uint32_t line)
  338. {
  339.   /* USER CODE BEGIN 6 */
  340.   /* User can add his own implementation to report the file name and line number,
  341.      tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  342.   /* USER CODE END 6 */
  343. }
  344. #endif /* USE_FULL_ASSERT */

  345. /**
  346.   * @}
  347.   */

  348. /**
  349.   * @}
  350.   */

  351. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
复制代码

所有资料51hei提供下载:
hal代码.7z (2.89 MB, 下载次数: 70)
回复

使用道具 举报

ID:342911 发表于 2019-6-21 17:02 | 显示全部楼层
十分感谢 资料很有用
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表