使用TIM2在PA0口控制发光二极管的亮度,用接在PA3和PA8脚的按键控制PWM宽度
在网上找了一些例程,对我的帮助很大,弄了一上午,当看到发光二极管的亮度随着按键改变时,这种喜悦感是做其他事情感受不到的,这就是我玩单片机的乐趣所在!
不说废话了,先初始化I/O
void
GPIO_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_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_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);
}
要想在程序执行中改变PWM宽度 就要使用
TIM_SetCompare1(TIM2, TIMCompare1);
我个人理解 TIMCompare1相当于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得值显示到液晶屏上了,按住按键
屏幕上的数值会飞快的增加(减少),亮度也会改变,很有意思!!
发张照片:
TIMCompare1为26时的亮度: