虽然STM32具有许多硬件定时器,但所有 Cortex-M器件都有一个通用的SYSTICK定时器,因此最简单,最便携的方法就是使用它.
以下内容创建了一个1毫秒的自由运行计数器msTicks:
#include "stm32f4xx.h"
#include <stdint.h>
static volatile uint32_t msTicks = 0; // Milliseconds
int main(void)
{
SysTick_Config(SystemCoreClock / 1000) ; // 1ms interrupt
for(;;)
{
... // your code here
}
}
// SYSTICK interrupt handler
void SysTick_Handler(void)
{
msTicks++ ;
}
Run Code Online (Sandbox Code Playgroud)
然后你的秒表可以实现两个功能:
static uint32_t start_time ;
void start( void )
{
start_time = msTicks ;
}
uint32_t getMillisecondsSinceStart( void )
{
return msTicks - start_time ;
}
Run Code Online (Sandbox Code Playgroud)
例如:
bool running = false ; // needs <stdbool.h> included
uint32_t time_millisec = 0 ;
for(;;)
{
if( startButtonPressed() )
{
running = true ;
start() ;
}
if( stopButtonPressed() )
{
running = false ;
}
if( running )
{
time_millisec = getMillisecondsSinceStart() ;
}
displayTime( time_millisec ) ;
}
Run Code Online (Sandbox Code Playgroud)
精度将完全取决于驱动核心时钟的任何因素 - 通常是外部晶振或振荡器.内部RC振荡器不太精确 - 工厂调整为+/- 1%.您的特定部件还具有32KHz RC振荡器,用于驱动可校准的RTC,但不能用于驱动核心时钟(systick),并且与上述方法相比,便携性更低,精度更低,更复杂.