STM32是利用定时器产生PWM的,STM32 定时器非常强大,其中上篇文章提到的SYSTICK也是定时器的一种,先上一段我编写的程序与大家分享,有什么不对的欢迎大家指点迷津。(现在开始慢慢都用函数写程序了,显得有层次。)
题目:用STM32的 TIM3产生四路PWM输出,占空比任意即可。
#include "stm32f10x_conf.h"
void GPIO_CFG(void);
void RCC_CFG(void);
void TIM_CFG(void);
int main (void)
{
RCC_CFG();
GPIO_CFG();
TIM_CFG();
TIM_Cmd(TIM3,ENABLE);
TIM_CtrlPWMOutputs(TIM3,ENABLE);
while(1);
}
void RCC_CFG(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOB,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
}
void GPIO_CFG(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6|GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_0|GPIO_Pin_1;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
void TIM_CFG(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseStructure.TIM_Period=2000;
TIM_TimeBaseStructure.TIM_Prescaler=35999;
TIM_TimeBaseStructure.TIM_ClockDivision=0x00;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter=0x00;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_Pulse=1000;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OC1Init(TIM3,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=400;
TIM_OC2Init(TIM3,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=1000;
TIM_OC3Init(TIM3,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=550;
TIM_OC4Init(TIM3,&TIM_OCInitStructure);
}