第一次实验-作业1:把微秒级延迟放到main里,用for循环产生10微秒。

This commit is contained in:
423A35C7 2024-10-08 21:36:32 +08:00
parent b0ebd03d19
commit 560343cced
2 changed files with 27 additions and 6 deletions

View File

@ -46,14 +46,14 @@ extern "C" {
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
#define SYSTICKCLK 170 // Systick Frequency 170MHz
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
void delay_us(uint32_t nus);
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/

View File

@ -56,7 +56,24 @@ void SystemClock_Config(void);
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void delay_us(uint32_t nus) {
uint32_t ticks;
uint32_t told, tnow, tcnt=0;
uint32_t reload = SysTick->LOAD; // LOAD的值
ticks = nus * SYSTICKCLK; // 需要的节拍数
told = SysTick->VAL; // 刚进入时的计数器值
while (1) {
tnow = SysTick->VAL;
if (tnow != told) {
if (tnow < told)
tcnt += told - tnow; // SYSTICK是一个递减的计数器就可以了
else
tcnt += reload - tnow + told;
told = tnow;
if (tcnt >= ticks) break; // 事件超过/等于要延迟的时间,则退出
}
}
}
/* USER CODE END 0 */
/**
@ -104,10 +121,14 @@ int main(void)
}
if (sSysTickTimer.bTimeOk) {
sSysTickTimer.bTimeOk = 0;
HAL_GPIO_TogglePin(TickClock_LED_GPIO_Port, TickClock_LED_Pin);
// HAL_GPIO_TogglePin(TickClock_LED_GPIO_Port, TickClock_LED_Pin);
}
// HAL_GPIO_TogglePin(TickClock_LED_GPIO_Port, TickClock_LED_Pin);
// HAL_Delay(100);
HAL_GPIO_TogglePin(TickClock_LED_GPIO_Port, TickClock_LED_Pin);
// HAL_Delay(500);
for (int i = 0; i < 50000; i++) {
delay_us(10); // 用for循环产生10微秒
}
// delay_us(500000);
}
/* USER CODE END 3 */
}