新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > STM32開發(fā)板學(xué)習(xí)筆記--PWM

STM32開發(fā)板學(xué)習(xí)筆記--PWM

作者: 時間:2016-11-28 來源:網(wǎng)絡(luò) 收藏
使用TIM2在PA0口控制發(fā)光二極管的亮度,用接在PA3和PA8腳的按鍵控制PWM寬度

在網(wǎng)上找了一些例程,對我的幫助很大,弄了一上午,當(dāng)看到發(fā)光二極管的亮度隨著按鍵改變時,這種喜悅感是做其他事情感受不到的,這就是我玩單片機的樂趣所在!

不說廢話了,先初始化I/O

voidGPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;

GPIO_InitStructure.GPIO_Pin =GPIO_Pin_0 ;//PWM輸出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3 | GPIO_Pin_8 ;//兩個按鍵
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}


配置TIM2 :

void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;
TIM_OCInitTypeDefTIM_OCInitStructure;
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);


TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 500;//改變這里的值就能改變PWM寬度
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;

TIM_OC1Init(TIM2, &TIM_OCInitStructure);

TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);

TIM_ARRPreloadConfig(TIM2, ENABLE);


TIM_Cmd(TIM2, ENABLE);
}

要想在程序執(zhí)行中改變PWM寬度就要使用
TIM_SetCompare1(TIM2, TIMCompare1);
我個人理解TIMCompare1相當(dāng)于TIM2初始化里的TIM_OCInitStructure.TIM_Pulse,只要改變這個值就能改變PWM的寬度
while(1){
scan_bit1 = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_3);
scan_bit2 = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_8);
if(scan_bit1==0) TIMCompare1+=1;
if(scan_bit2==0) TIMCompare1-=1;
if(TIMCompare1>999) TIMCompare1=999;
if(TIMCompare1<1) TIMCompare1=1;
TIM_SetCompare1(TIM2, TIMCompare1);
}

按鍵程序沒有加延時去抖動,所以按一下亮度會改變很多

我實際用的時候把TIMCompare1得值顯示到液晶屏上了,按住按鍵 屏幕上的數(shù)值會飛快的增加(減少),亮度也會改變,很有意思??!


評論


技術(shù)專區(qū)

關(guān)閉