详解STM32高级定时器-PWM简单学习案例
扫描二维码
随时随地手机看文章
高级定时器与通用定时器比较类似,下面是一个TIM1 的PWM 程序,TIM1是STM32唯一的高级定时器。共有4个通道有死区有互补。
先是配置IO脚:
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
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_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
void Tim1_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_DeInit(TIM1); //重设为缺省值
TIM_TimeBaseStructure.TIM_Prescaler = 4000; //预分频(时钟分频)72M/4000=18K
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseStructure.TIM_Period = 144; //装载值 18k/144=125hz 就是说向上加的144便满了
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置了时钟分割 不懂得不管
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0x0; //周期计数器值 不懂得不管
TIM_TimeBaseInit(TIM1,&TIM_TimeBaseStructure); //初始化TIMx的时间基数单位
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //PWM模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //正向通道有效 PA8
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //反向通道也有效 PB13
TIM_OCInitStructure.TIM_Pulse = 40; //占空时间 144 中有40的时间为高,互补的输出正好相反
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; //互补端的极性
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; //空闲状态下的非工作状态不管
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; //先不管
TIM_OC1Init(TIM1,&TIM_OCInitStructure); //数初始化外设TIMx通道1这里2.0库为TIM_OCInit
TIM_Cmd(TIM1,ENABLE);
TIM_CtrlPWMOutputs(TIM1,ENABLE);
}
//设置捕获寄存器1
void SetT1Pwm1(u16 pulse)
{
TIM1-》CCR1=pulse;
}
//在MAIN 中加点键盘扫描啥的用来改变占空比
#include “STM32Lib\stm32f10x.h”
#include “hal.h”
extern void SetT1Pwm1(u16 pulse);
int main(void)
{
u16 pulse=40;
ChipHalInit(); //片内硬件初始化
ChipOutHalInit(); //片外硬件初始化
for(;;)
{
if(GET_UP())
{
while(GET_UP());
if(pulse《=144)
{
pulse+=5;
SetT1Pwm1(pulse);
}
}
if(GET_DOWN())
{
while(GET_DOWN());
if(pulse》30)
{
pulse-=5;
SetT1Pwm1(pulse);
}
}
}
}