本帖最后由 shiinakaze 于 2024-10-1 21:05 编辑
在 FreeRTOS 中,SysTick 被用于作为调度器的一部分进行任务调度,那么如果我需要使用软件模拟通信,例如软件 I2C,需要使用 delay,就无法使用 SysTick 实现的 delay
[C] 纯文本查看 复制代码
void Delay_us(uint32_t usec)
{
if (usec > 0)
{
SysTick->LOAD = SYSTICK_LOAD * usec; // Set systick reload value
SysTick->VAL = 0x00; // Set SysTick Current Value to 0
SysTick->CTRL = 0x00000005; // Set SysTick clock source to use processor clock and enable timer
while (!(SysTick->CTRL & 0x00010000)) // Wait for the timer to count to 0
{
}
// SysTick->CTRL = 0x00000004; // Disable timer
}
}
我的方法是另外开一个定时器 TIM2,来帮忙实现 delay 函数,那么是否有更好的办法呢?
[C] 纯文本查看 复制代码
void Delay_us(uint32_t usec)
{
if (usec > 0)
{
TIM2->CNT = usec - 1; // Load the counter with the number to decrement. When it is reduced to 0, the TIM_FLAG_UpDate flag of the timer is triggered
TIM2->CR1 |= TIM_CR1_CEN; // Enable counter
while ((TIM2->SR & TIM_FLAG_Update) != SET)
{
// Wait until the counter goes down to 0
}
TIM2->CR1 &= ~TIM_CR1_CEN; // Disable counter
TIM2->SR &= ~TIM_FLAG_Update; // Clear TIM_FLAG_UpDate
}
}
|