程序1:
tiM2输出比较,产生频率为366.2Hz的方波
#include "
STM32f10x.h"
void RCC_configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,ENABLE); //开启GPIO的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
}
void Led_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct; //定义GPIO初始化的结构体
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3; //选中管脚1 TIM2的通道2
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; // 选择速度50MHZ
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOA,&GPIO_InitStruct); //初始化IO口A
}
void NVIC_Configuration(void) //NVIC配置
{
NVIC_InitTypeDef NVIC_InitStruct;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); //中断组0
NVIC_SetVectorTable(NVIC_VectTab_FLASH,0x0); //中断向量FLASH
NVIC_InitStruct.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级0
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0; //从优先级0
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE; //中断向量使能
NVIC_Init(&NVIC_InitStruct);
}
void TIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_BaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
TIM_BaseInitStruct.TIM_Period = 65535; //重载值
TIM_BaseInitStruct.TIM_Prescaler = 2; //预分频值
TIM_BaseInitStruct.TIM_ClockDivision = 0;
TIM_BaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数0 ~ Period
TIM_TimeBaseInit(TIM2,&TIM_BaseInitStruct); //定时器寄存器初始化
/*********************通道1,产生频率为366HZ************/
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_Toggle; //选择定时器模式:TIM脉冲宽度调制模式2
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStruct.TIM_Pulse = 32768; //设置待装入捕获比较寄存器的脉冲值
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性:TIM输出比较极性高
TIM_OC1Init(TIM2, &TIM_OCInitStruct); //根据TIM_OCInitStruct中指定的参数初始化外设TIMx
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable); //使能TIMx在CCR2上的预装载寄存器
TIM_ITConfig(TIM2,TIM_IT_CC1,ENABLE); //TIM中断使能
TIM_ARRPreloadConfig(TIM2, ENABLE); //使能TIMx在ARR上的预装载寄存器
TIM_Cmd(TIM2,ENABLE); //定时器使能
}
int main(void)
{
/* Setup STM32 system (clock, PLL and Flash configuration) */
SystemInit();
RCC_configuration();
Led_Init();
NVIC_Configuration();
TIM2_Configuration();
while (1)
{
}
}
/********************中断函数*************************/
void TIM2_IRQHandler(void)
{
uint16_t capture = 0;
/**************通道1,366.2HZ*******************/
if(TIM_GetITStatus(TIM2,TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM2,TIM_IT_CC1);
capture = TIM_GetCapture1(TIM2);
TIM_SetCompare1(TIM2,capture + 32767);
}
}
问题1:为什么我的输出结果不是1:1的方波,是占空比为1:3的方波?
问题2:为什么我的输出频率是183.1,也就是说TIM2CLK = 36M,但是我改成PWM模式时,测的TIM2CLK = 72M,难道是输出比较模式时TIM的倍频器不工作?