新手入门
积分 15
金钱 15
注册时间 2018-10-11
在线时间 14 小时
8 金钱
本帖最后由 李赖赖无敌手 于 2020-2-14 13:01 编辑
我的想法是通过主定时器TIM1来控制从定时器TIM2,从而实现LED0每隔一秒翻动一次。程序如下。我的想法是,主定时器TIM1产生一次更新中断(1ms),就给从定时器发送一次触发信号,从而从定时器的计数器值加一。那么从定时器的ARR是999,所以从定时器要产生溢出总共就需要1ms乘以1000,就等于1s。运行结果的确也会翻动,可是时间太长了(大概50秒的样子翻动一次)。我个人的猜测是定时出了问题,其他的诸如主从模式的设置应该是没错的。希望有大佬可以指点我一下,困扰我几天了。不胜感激!//...........................................................................................................//
#include "tim.h"
#include "led.h"
void TIM_Mode_Config(void)
{
//主定时器TIM1初始化
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
//时基初始化结构体
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Prescaler=71;
TIM_TimeBaseInitStruct.TIM_Period=999;
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1,&TIM_TimeBaseInitStruct);
TIM_Cmd(TIM1,ENABLE);//计数器使能
TIM_SetCounter(TIM1,0);
TIM_ARRPreloadConfig(TIM1,ENABLE);//使能自动重转载计数器
TIM_SelectMasterSlaveMode(TIM1,TIM_MasterSlaveMode_Enable);//使能TIM1为主定时器
TIM_SelectOutputTrigger(TIM1,TIM_TRGOSource_Update);//选择TIM1更新中断作为触发输出
//定时器TIM2初始化
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//时基初始化结构体
TIM_TimeBaseInitStruct.TIM_Prescaler=71;
TIM_TimeBaseInitStruct.TIM_Period=999;
TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStruct);
TIM_SetCounter(TIM2,0);
//TIM_ARRPreloadConfig(TIM2,DISABLE);//使能自动重转载计数器
TIM_Cmd(TIM2,ENABLE);//计数器使能
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);//中断使能
//从模式选择
TIM_SelectSlaveMode(TIM2,TIM_SlaveMode_External1);//从模式的选择为外部触发1
TIM_SelectInputTrigger(TIM2,TIM_TS_ITR0);
}
void TIM2_NVIC_Config(void)
{
//中断初始化
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStruct.NVIC_IRQChannel=TIM2_IRQn ;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1;
NVIC_InitStruct.NVIC_IRQChannelSubPriority=2;
NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStruct);
}
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
LED0=!LED0;
}
}
void TIM_Config(void)
{
TIM_Mode_Config();
TIM2_NVIC_Config();
}
//......................................................................................................//
主函数
int main (void)
{
LED_Init();
TIM_Config();
while(1);
}
//......................................................................................................//
我来回答