资源描述:
《stm32日记之tim1模块产生pwm(分别用库函数和寄存器)》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、C语言:TIM1模块产生PWM,带死区//Step1.开启TIM和相应端口时钟//启动GPIORCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA
2、RCC_APB2Periph_GPIOB
3、RCC_APB2Periph_GPIOC
4、RCC_APB2Periph_GPIOD,ENABLE);//启动AFIORCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//启动TIM1RCC_APB2PeriphClockCmd(RCC_APB2Perip
5、h_TIM1,ENABLE);//Step2.GPIO做相应设置,为AF输出//PA.8/9口设置为TIM1的OC1输出口GPIO_InitStructure.GPIO_Pin=GPIO_Pin_8
6、GPIO_Pin_9;GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;GPIO_Init(GPIOA,&GPIO_InitStructure);//PB.13/14口设置为TIM1_CH1N和TIM
7、1_CH2N输出口GPIO_InitStructure.GPIO_Pin=GPIO_Pin_13
8、GPIO_Pin_14;GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;GPIO_Init(GPIOB,&GPIO_InitStructure);//Step3.TIM模块初始化voidTIM_Configuration(void){TIM_TimeBaseInitTypeDefTIM_BaseIn
9、itStructure;TIM_OCInitTypeDefTIM_OCInitStructure;TIM_BDTRInitTypeDefTIM_BDTRInitStructure;//TIM1基本计数器设置(设置PWM频率)//频率=TIM1_CLK/(ARR+1)TIM_BaseInitStructure.TIM_Period=1000-1;TIM_BaseInitStructure.TIM_Prescaler=72-1;TIM_BaseInitStructure.TIM_ClockDivision=0;TIM_BaseIni
10、tStructure.TIM_CounterMode=TIM_CounterMode_Up;TIM_BaseInitStructure.TIM_RepetitionCounter=0;TIM_TimeBaseInit(TIM1,&TIM_BaseInitStructure);//启用ARR的影子寄存器(直到产生更新事件才更改设置)TIM_ARRPreloadConfig(TIM1,ENABLE);//TIM1_OC1模块设置(设置1通道占空比)TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_P
11、WM1;TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;TIM_OCInitStructure.TIM_OutputNState=TIM_OutputNState_Enable;TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;TIM_OCInitStructure.TIM_OCNPolarity=TIM_OCNPolarity_High;TIM_OCInitStructure.TIM_Pulse=1
12、20;//TIM1_Pulse设置了待装入捕获比较寄存器的脉冲值TIM_OC1Init(TIM1,&TIM_OCInitStructure);//启用CCR1寄存器的影子寄存器(直到产生更新事件才更改设置)TIM_OC1PreloadConfig(TIM1,TIM_OCPreload_Enable);//TIM2_OC2模块设置(设置2通道占空比)TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;TIM_OCInitStructure.TIM_OutputNSt
13、ate=TIM_OutputNState_Enable;TIM_OCInitStructure.TIM_Pulse=680;TIM_OC2Init(TIM1,&TIM_OCInitStructure);//启用CCR2寄存器的影子寄存器(直到产生更新事件才更改设