|||
http://shop66732237.taobao.com/
主程序中调用这么三个函数
TIM_Config();
NVIC_Config();
TIM_Config();
//初始化的工作就完整了。
void NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the TIM4 global Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void RCC_Configuration(void)
{
/* TIM2 and TIM3 TIM4 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2 | RCC_APB1Periph_TIM3 | RCC_APB1Periph_TIM4, ENABLE);
/* GPIOA clock enable */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
}
void TIM_Config(void)
{
TIM_DeInit(TIM4);
/* TIM4 configuration*/
/* Time Base configuration 基本配置 配置定时器的时基单元*/
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = 65535; //自动重装值
TIM_TimeBaseStructure.TIM_Prescaler = 0x0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0x0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//TIM_CounterMode_Down;
TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);
/* Enable the TIM4 update Interrupt */
TIM_ITConfig(TIM4, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM4, ENABLE);
}
//stm32f10x_it.c中断中加这么个函数
void TIM4_IRQHandler(void)
{
static u32 b=0;
u32 fs =0;
if(TIM_GetITStatus(TIM4, TIM_IT_Update) == SET)
{
TIM_ClearITPendingBit(TIM4, TIM_IT_Update);
//EXTI->PR |= 1<<1;//清除中断标志位
TIM4->CR1 &= 0xfffffffe;//关闭定时器
b++;
if(b==1)
{
TIM4->ARR = 300; //开始第一次的ARR
fs = 200000;
}
if(b==2)
{
TIM4->CNT =0;
TIM4->ARR = 0; //第二次设置为小于第一次,必须有前面的TIM4->CNT 也设置小于等于ARR,否则就死糗了。可以试试。
fs = 40000;
}
TIM4->CR1|=0x01;//重新开启定时器4
}
}
//结论:要保证 向上计数时CNT《=ARR(计数停止时改改后再开始计数),向下计数时CNT》=ARR(计数停止时改改后再开始计数)。