专注电子技术学习与研究
当前位置:单片机教程网 >> STM32 >> 浏览文章

STM32 四路PWM输出

作者:huqin   来源:本站原创   点击数:  更新时间:2014年05月06日   【字体:

PWM,脉宽调制,首先明确它不是STM32的标准外设,也没有对应的库函数和寄存器,不像ADC,SPI,CAN,USART等属于外设可以直接调用.C文件进行驱动,PWM是一种脉宽调制机制,是模拟转数字或数字转模拟的一种控制方式,它无非输出的就是0和1,只是利用输出0和1的时间长短来应对模拟量的变化,具体讲解还需详细了解PWM.那么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);     
 }



有疑问可以给我留言。

关闭窗口

相关文章