專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> STM32 >> 瀏覽文章

STM32 四路PWM輸出

作者:huqin   來(lái)源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2014年05月06日   【字體:

PWM,脈寬調(diào)制,首先明確它不是STM32的標(biāo)準(zhǔn)外設(shè),也沒(méi)有對(duì)應(yīng)的庫(kù)函數(shù)和寄存器,不像ADC,SPI,CAN,USART等屬于外設(shè)可以直接調(diào)用.C文件進(jìn)行驅(qū)動(dòng),PWM是一種脈寬調(diào)制機(jī)制,是模擬轉(zhuǎn)數(shù)字或數(shù)字轉(zhuǎn)模擬的一種控制方式,它無(wú)非輸出的就是0和1,只是利用輸出0和1的時(shí)間長(zhǎng)短來(lái)應(yīng)對(duì)模擬量的變化,具體講解還需詳細(xì)了解PWM.那么STM32是利用定時(shí)器產(chǎn)生PWM的,STM32 定時(shí)器非常強(qiáng)大,其中上篇文章提到的SYSTICK也是定時(shí)器的一種,先上一段我編寫的程序與大家分享,有什么不對(duì)的歡迎大家指點(diǎn)迷津。(現(xiàn)在開(kāi)始慢慢都用函數(shù)寫程序了,顯得有層次。)

 

題目:用STM32的 TIM3產(chǎn)生四路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);     
 }



有疑問(wèn)可以給我留言。

關(guān)閉窗口

相關(guān)文章