2017-03-02 109 views
0

我正在使用定时器使LED每1秒开启/关闭(而不是使用延迟功能)。但是,当我在IAR IDE上执行此代码时,LED灯会在2.5-3秒左右开启/关闭,而不是像我想要的那样1秒。我想知道代码中是否有任何错误,或者我需要修改某处以获得正确的时钟速度?STM32F4中的我的定时器不能正确执行延迟

我使用的是标准外设库,而我使用的IDE是IAR。

#include "stm32f4xx.h" 

GPIO_InitTypeDef GPIO_InitStructure; 
TIM_TimeBaseInitTypeDef TIM_BaseStruct; 

void GPIO_Configuration(void); 
void TIM_Configuration(void); 
void Delay(__IO uint32_t nCount); 

int main(void) 
{ 
    GPIO_Configuration(); 
    TIM_Configuration(); 
    while(1) 
    { 
    if(TIM_GetFlagStatus(TIM2,TIM_FLAG_Update) != RESET) 
    { 
     TIM_ClearFlag(TIM2,TIM_IT_Update); 
     GPIO_ToggleBits(GPIOD,GPIO_Pin_14); 
    } 
    } 
} 

void GPIO_Configuration(void) 
{ 
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); 

    /* Configure PB0 PB1 in output pushpull mode */ 
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; 
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; 
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; 
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz; 
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; 
    GPIO_Init(GPIOD, &GPIO_InitStructure); 
} 

void TIM_Configuration(void) 
{ 
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE); 

    TIM_BaseStruct.TIM_Prescaler = 42000-1; 
    TIM_BaseStruct.TIM_CounterMode = TIM_CounterMode_Up; 
    TIM_BaseStruct.TIM_Period = 2000-1; 
    TIM_BaseStruct.TIM_ClockDivision = 0; 
    TIM_BaseStruct.TIM_RepetitionCounter = 0; 

    TIM_TimeBaseInit(TIM2,&TIM_BaseStruct); 

    TIM_Cmd(TIM2,ENABLE); 
} 


void Delay(__IO uint32_t nCount) 
{ 
    while(nCount--) 
    { 
    } 
} 

#ifdef USE_FULL_ASSERT 
void assert_failed(uint8_t* file, uint32_t line) 
{ 
    /* User can add his own implementation to report the file name and line number, 
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ 

    /* Infinite loop */ 
    while (1) 
    { 
    } 
} 
#endif 
+1

该计时器只计算时钟周期,所以预分频器/周期值的含义完全取决于您的时钟频率 - 您没有指定。 – jasonharper

+0

请您详细说明我可以在哪里看到并修改IAR中的时钟频率? (不在Keil C中) –

+0

代码中没有地方可以直接指定时钟频率。选择计时器参数时只需考虑它。 – jasonharper

回答

0

我打算假设你的时钟频率是168Mhz。用你目前的预分频器和周期值,这会让你的计时器在2秒。

(CLK_FREQ/(PRESCALER * PERIOD)) = (168MHZ/(42000 * 2000)) = 2 seconds 

尝试改变期间1000,使其在1秒运行。这也是假设你的时钟频率是168Mhz。如果您的时钟频率不同,您可以轻松计算出PRESCALERPERIOD的值(如上所示)以达到1。