运用TIM2在PA0口操控发光二极管的亮度,用接在PA3和PA8脚的按键操控PWM宽度
在网上找了一些例程,对我的协助很大,弄了一上午,当看到发光二极管的亮度跟着按键改动时,这种高兴感是做其他工作感触不到的,这便是我玩单片机的趣味地点!
不说废话了,先初始化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);
}
要想在程序履行中改动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得值显现到液晶屏上了,按住按键 屏幕上的数值会飞快的添加(削减),亮度也会改动,很有意思!!
声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/xinpin/jishu/256552.html