STM32庞大的库函数让初学者摸不到头脑,想要直接操作寄存器也存在一定难度,比如想要动态改变PWM占空比这样一个简单的问题,查找了很多帖子和书籍依旧没有找到答案(可能是因为太简单了吧),最后终于发现这的确很简单,具体操作如下:1.首先要包含头文件#include "stm32f10x_
tim.h",因为这里面包含了定时器相关寄存器的定义
2.编写TIMx->CCRx = 800,其中TIMx(x=1~7)是你用的哪一个定时器,CCRx(x=1~4)是定时器的哪一个通道,CCRx就是改变定时器的寄存器,直接改变它的值这样想要编写一个呼吸灯程序就再简单不过了,比如:
//初始化定时器TIM3
static void TIM3_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}
static void TIM3_Mode_Config(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseStructure.TIM_Period = 999; //定时周期1000
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1 ;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = CCR1_Val; //占空比
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure); //使能通道1
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_Cmd(TIM3, ENABLE);
}
//主函数里这样写
while(1)
{
uint32_t i;
TIM3->CCR1 -= 100;
for(i=0xffffff;i!=0;i--);
if(TIM3->CCR1 < 1)
{
for(i=0xffffff;i!=0;i--);
TIM3->CCR1 = 800;
}
}
}
这样一个简单的呼吸灯程序就完成了
4