重写主函数
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();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_TIM1_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start(&htim1);//开启定时器
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* 定时器1,通道1,模式随便,主要用于计数,没有使用边沿捕获 */
Start();//开启超声波模块
HAL_TIM_Base_Start(&htim1);//开启定时器
//对超声波输入端口操作
while( HAL_GPIO_ReadPin (Echo_GPIO_Port ,Echo_Pin) == GPIO_PIN_RESET);//等待输入电平拉高
__HAL_TIM_SetCounter(&htim1,0);
//对超声波输入端口操作
while( HAL_GPIO_ReadPin (Echo_GPIO_Port ,Echo_Pin) == GPIO_PIN_SET);//等待输入电平变低
Cnt = __HAL_TIM_GetCounter(&htim1);
HAL_TIM_Base_Stop(&htim1);
Distance = Cnt*340/2*0.000001*100 ;
printf("Distance=%.1fcm\n",Distance);
HAL_Delay(500);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
|