本帖最后由 赵大鳖 于 2017-2-11 16:21 编辑
自己用的是STM32F103ZET6的系统板,初学PWM,照着原子哥的程序写的。
硬件:LED低电平有效,使用的是TIM3_CH2,没有使用复用功能,即PA.7引脚,但是上电后,LED常亮,求解释。
[mw_shl_code=c,true]void TIM3_PWM_Init(u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //ʹÄܶ¨Ê±Æ÷3ʱÖÓ
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //ʹÄÜGPIOʱÖÓ
//ÉèÖøÃÒý½ÅΪÍÆÍìÊä³ö¹¦ÄÜ£¬Êä³öTIM3_CH1µÄ
WMÂö³å²¨ÐÎ
A.6
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //ÍÆÍìÊä³ö
GPIO_Init(GPIOA,&GPIO_InitStructure);
//³õʼ»¯TIM3
TIM_TimeBaseInitStructure.TIM_Prescaler = psc; //ÉèÖÃ×Ô¶¯×°ÔØÖÜÆÚ
TIM_TimeBaseInitStructure.TIM_Period = arr; //ÉèÖÃÔ¤·ÖƵֵ
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //ÉèÖÃTIMÏòÉϼÆÊý
TIM_TimeBaseInitStructure.TIM_ClockDivision = 0; //ÉèÖÃʱÖÓ·Ö¸î
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);
//
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //Êä³ö
WM2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //Êä³öʹÄÜ
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;//Êä³ö¼«ÐÔµÍ
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);//ʹÄÜԤװÔؼĴæÆ÷
TIM_Cmd(TIM3,ENABLE);//ʹÄÜTIM3
}
[/mw_shl_code]
[mw_shl_code=c,true] int main(void)
{
u16 led0pwmval=0;
u8 dir=1;
delay_init(); //ÑÓʱº¯Êý³õʼ»¯
NVIC_Configuration(); //ÉèÖÃNVICÖжϷÖ×é2:2λÇÀÕ¼ÓÅÏȼ¶£¬2λÏìÓ¦ÓÅÏȼ¶
uart_init(9600); //´®¿Ú³õʼ»¯Îª9600
LED_Init(); //LED¶Ë¿Ú³õʼ»¯
TIM3_PWM_Init(899,0); //²»·ÖƵ¡£
WMƵÂÊ=72000/900=8Khz
while(1)
{
delay_ms(10);
if(dir)led0pwmval++;
else led0pwmval--;
if(led0pwmval>300)dir=0;
if(led0pwmval==0)dir=1;
TIM_SetCompare2(TIM3,led0pwmval);
}
}[/mw_shl_code]
一周热门 更多>