Tim.c文件
#include “stm32f10x_tim.h”
#include “stm32f10x_gpio.h”
#include
void time_ini(void);
extern unsigned int CCR3_Val;
extern unsigned int CCR4_Val;
TIM_TimeBaseInitTypeDef TIM3_TimeBaseStructure;
TIM_OCInitTypeDef TIM3_OCInitStructure;
TIM_BDTRInitTypeDef TIM3_BDTRInitStructure;
void time_ini(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //定时器3 时钟使能
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1; //PB5复用为TIM3的通道2
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3 , ENABLE);
TIM3_TimeBaseStructure.TIM_Prescaler = 7200; //预分频器TIM3_PSC=63
TIM3_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //计数器向上计数模式 TIM3_CR1[4]=0
TIM3_TimeBaseStructure.TIM_Period =0xffff; //主动重装载寄存器TIM3_APR
TIM3_TimeBaseStructure.TIM_ClockDivision = 0x0; //时钟分频因子 TIM3_CR1[9:8]=00
TIM_TimeBaseInit(TIM3,&TIM3_TimeBaseStructure); //写TIM3各寄存器参数
TIM3_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle ; //TIM3_CCMR1[14:12]=011 翻转当TIM3_CCR2=TIM3_CNT时,翻转OC2REF的电平
TIM3_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性 低电平有用 TIM3_CCER[5]=1;
TIM3_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //输入/捕获2输出答应 OC2信号输出到对应的输出引脚PB5
TIM3_OCInitStructure.TIM_Pulse =CCR3_Val; //若CC1通道装备为输出:CCR2是装入当时捕获/比较2 TIM3_CCR2寄存器的值(预装载值)。
TIM_OC3Init(TIM3, &TIM3_OCInitStructure);
TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Disable);
TIM3_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //输入/捕获2输出答应 OC2信号输出到对应的输出引脚PB5
TIM3_OCInitStructure.TIM_Pulse =CCR4_Val; //若CC1通道装备为输出:CCR2是装入当时捕获/比较2 TIM3_CCR2寄存器的值(预装载值)。
TIM_OC4Init(TIM3, &TIM3_OCInitStructure);
TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Disable); //TIM3_CCMR1[1]=0 制止TIM3_CCR2寄存器的预装载功用,可随时写入TIM3_CCR2
TIM_Cmd(TIM3,ENABLE); //发动定时器3 TIM3_CR1[0]=1;
TIM_ITConfig(TIM3,TIM_IT_CC3|TIM_IT_CC4,ENABLE); //TIM3_DIER[2]=1 答应捕获/比较2中止
}
stm32f10x_it.c文件
#include “stm32f10x.h”
#include “stm32f10x_tim.h”
unsigned int capture1=0;
extern unsigned int CCR3_Val;
extern unsigned int CCR4_Val;
extern TIM_OCInitTypeDef TIM3_OCInitStructure;
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_CC3) != RESET) //判别状况寄存器 TIM3_SR[2] 是否发生了捕获/比较2 中止
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC3); //软件铲除状况寄存器 TIM3_SR[2] 捕获/比较2 中止中止标志
capture1 = TIM_GetCapture3(TIM3); //获取TIM3_CCR2的预装值
TIM_SetCompare3(TIM3, capture1+ CCR3_Val); //和CCR2_Val累加后装入TIM3_CCR2 这是为了合作计数器值的递加。以鄙人一次作出比较。
}
if (TIM_GetITStatus(TIM3, TIM_IT_CC4) != RESET) //判别状况寄存器 TIM3_SR[2] 是否发生了捕获/比较2 中止
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC4); //软件铲除状况寄存器 TIM3_SR[2] 捕获/比较2 中止中止标志
capture1 = TIM_GetCapture4(TIM3); //获取TIM3_CCR2的预装值
TIM_SetCompare4(TIM3, capture1+ CCR4_Val); //和CCR2_Val累加后装入TIM3_CCR2 这是为了合作计数器值的递加。以鄙人一次作出比较。
}
}