//精英板-PWM实验LED0的亮度不会变化,谢谢
//pwm.h
#include "stm32f10x.h"
#ifndef __PWM_H
#define __PWM_H
void PWM_Init(u16 arr,u16 psc);
#endif
//pwm.c
#include "stm32f10x.h"
#include "pwm.h"
void PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE); //ê1ÄüGPIOBμÄê±Öó
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //ê1ÄüAFIO¸′óÃ1|ÄüÄ£¿éê±Öó
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE); //Timer32¿·ÖÖØó3éä TIM3_CH2->PB5
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //PB5Îa¸′óÃíÆíìêä3öÄ£ê½
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //TIMÏòéϼÆêyÄ£ê½
TIM_TimeBaseInitStructure.TIM_ClockDivision=0; //éèÖÃê±Öó·Ö¸î:TDTS = Tck_tim
TIM_TimeBaseInitStructure.TIM_Period=arr*10-1; //×Ô¶ˉÖØ×°ÔؼÄ′æÆ÷ÖüÆúμÄÖμ
TIM_TimeBaseInitStructure.TIM_Prescaler=psc-0; //éèÖÃóÃà′×÷ÎaTIMxê±ÖóÆμÂê3yêyμÄÔ¤·ÖÆμÖμ
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2; //Ñ¡Ôñ¶¨ê±Æ÷Ä£ê½:TIMÂö3å¿í¶èμ÷ÖÆÄ£ê½2
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High; //êä3ö¼«DÔ:TIMêä3ö±è½Ï¼«DÔ¸ß
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; //±è½Ïêä3öê1Äü
TIM_OC2Init(TIM3,&TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable); //ê1ÄüԤװÔؼÄ′æÆ÷
TIM_Cmd(TIM3,ENABLE); //ê1ÄüTIM3
}
//main.c
#include "stm32f10x.h"
#include "pwm.h"
int main(void)
{
u32 ccr2=899; //éèÖÃÕ¼¿Õ±è
u8 a=0;
PWM_Init(900,0); //2»·ÖÆμ¡£PWMÆμÂê=72000000/900=80Khz
while(1)
{
if(ccr2==899) a=1;
if(a==1)
{
ccr2--;
TIM_SetCompare2(TIM3,ccr2);
}
if(ccr2==0) a=2;
if(a==2)
{
ccr2++;
TIM_SetCompare2(TIM3,ccr2);
}
}
}
友情提示: 此问题已得到解决,问题已经关闭,关闭后问题禁止继续编辑,回答。
一周热门 更多>