#include"My_Delay.h"// 微秒级延时函数voidmy_delay_us(uint32_t us){uint32_t start =HAL_GetTick();// 获取当前毫秒计数// 计算所需的毫秒延时次数uint32_t delay_ms = us /1000;// 计算余数,用于微秒级精确延时uint32_t remaining_us = us %1000;// 执行毫秒级延时HAL_Delay(delay_ms);// 延时剩余的微秒if(remaining_us){uint32_t end = start + delay_ms;// 结束毫秒计数while(HAL_GetTick()< end);// 等待毫秒计数达到结束值uint32_t now =HAL_GetTick();// 获取当前毫秒计数while(HAL_GetTick()== now);// 等待下一个毫秒的开始while(HAL_GetTick()<(now +1));// 等待进入下一个毫秒// 微秒级精确延时while(HAL_GetTick()<(now +1+ remaining_us /1000));// 等待进入下一个微秒级时刻}}// 毫秒级延时函数voidmy_delay_ms(uint32_t ms){HAL_Delay(ms);}
main函数
intmain(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_TIM6_Init();MX_USART2_UART_Init();/* USER CODE BEGIN 2 *//* USER CODE END 2 *//* Infinite loop *//* USER CODE BEGIN WHILE */while(1){my_delay_us(100000);printf("delay ok\n");/* USER CODE END WHILE *//* USER CODE BEGIN 3 */}/* USER CODE END 3 */}