systick作为时基
用到的相关函数如下:
void SysTick_CLKSourceConfig(uint32_t SysTick_CLKSource)//设置时钟源
uint32_t SysTick_Config(uint32_t ticks) // 设置中断时间
SysTick_CLKSourceConfig函数
可以选用两个参数:
1.SysTick_CLKSource_HCLK_Div8 -AHB 时钟进行8分频后得到的时钟,频率为72M/8 = 9M
2.SysTick_CLKSource_HCLK - AHB时钟 ,频率为72M
函数原型如下:
/*** @brief Configures the SysTick clock source.* @param SysTick_CLKSource: specifies the SysTick clock source.* This parameter can be one of the following values:* @arg SysTick_CLKSource_HCLK_Div8: AHB clock divided by 8 selected as SysTick clock source.* @arg SysTick_CLKSource_HCLK: AHB clock selected as SysTick clock source.* @retval None*/
void SysTick_CLKSourceConfig(uint32_t SysTick_CLKSource)
{/* Check the parameters */assert_param(IS_SYSTICK_CLK_SOURCE(SysTick_CLKSource));if (SysTick_CLKSource == SysTick_CLKSource_HCLK){SysTick->CTRL |= SysTick_CLKSource_HCLK;}else{SysTick->CTRL &= SysTick_CLKSource_HCLK_Div8;}
}
SysTick_Config函数
SysTick_Config函数用来配置中断的时间
函数原型如下:
/*** @brief Initialize and start the SysTick counter and its interrupt.** @param ticks number of ticks between two interrupts* @return 1 = failed, 0 = successful** Initialise the system tick timer and its interrupt and start the* system tick timer / counter in free running mode to generate * periodical interrupts.*/
static __INLINE uint32_t SysTick_Config(uint32_t ticks)
{ if (ticks > SysTick_LOAD_RELOAD_Msk) return (1); /* Reload value impossible */SysTick->LOAD = (ticks & SysTick_LOAD_RELOAD_Msk) - 1; /* set reload register */NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1); /* set Priority for Cortex-M0 System Interrupts */SysTick->VAL = 0; /* Load the SysTick Counter Value */SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | 选择为内核时钟,即AHB时钟—72MSysTick_CTRL_TICKINT_Msk | //开启SYSTICK中断SysTick_CTRL_ENABLE_Msk; //开启SYSTICK /* Enable SysTick IRQ and SysTick Timer */return (0); /* Function successful */
}
在程序里使用这两个函数即可设置sys定时器的中断时间,
例子
设置sys定时器中断时间为1ms
SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK); //选择AHB时钟为sys的时钟源——72M
SysTick_Config(SystemCoreClock /1000); // 设置中断时间为1ms
这里1ms是这样计算的:
首先SystemCoreClock 被设置成72M,SysTick_Config(uint32_t ticks)的ticks表示重装值,那么此时定时时间就为 :(72M/1000/) / 72M = 0.001s = 1ms.
systick做delay函数
delay_us
因为在上面设置了sys时钟源为72M,因为每s计72000000次,每计72次过去1us,
所以SysTick->LOAD=nus*72;
void delay_us(u32 nus)
{ u32 temp; SysTick->LOAD=nus*72; //时间加载 SysTick->VAL=0x00; //清空计数器SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //开始倒数 do{temp=SysTick->CTRL;}while((temp&0x01)&&!(temp&(1<<16))); //等待时间到达 SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //关闭计数器SysTick->VAL =0X00; //清空计数器
}
delay_ms
因为在上面设置了sys时钟源为72M,因为每s计72000000次,每计72000次过去1ms,
所以SysTick->LOAD=nus*72000;
void delay_ms(u16 nms)
{ u32 temp; SysTick->LOAD=(u32)nms*72000; //时间加载(SysTick->LOAD为24bit)SysTick->VAL =0x00; //清空计数器SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk ; //开始倒数 do{temp=SysTick->CTRL;}while((temp&0x01)&&!(temp&(1<<16))); //等待时间到达 SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk; //关闭计数器SysTick->VAL =0X00; //清空计数器
}