二、 实验原理
STM32的定时器有PWM功能,iCore3的三个LED都连接在定时器的输出接口上,可以通过定时器的PWM输出控制LED的亮度,从而实现呼吸灯的功能。硬件连接示意图如下图所示:
三、源代码
1、主函数
/*
* Name : main
* Description : ---
* Author : ysloveivy.
*
* History
* --------------------
* Rev : 0.00
* Date : 11/21/2015
*
* create.
* --------------------
*/
int main(void)
{
int i;
int brightness = 99;
pwm.initialize();
float temp = 0.0;
int data = 0;
//红色LED灯循环由亮变暗,由暗变亮
while(1){
for(i = 0;i < 1000000;i++);
brightness ++;
if(brightness == 100){
brightness = 0;
}
temp = sin(PI / 99.0 * brightness) * 0.5 + 0.5;
temp *= 499;
data = (int)temp;
pwm.set_compare(data);
}
}
/*
* Name : initialize
* Description : ---
* Author : ysloveivy.
*
* History
* -------------------
* Rev : 0.00
* Date : 11/21/2015
*
* create.
* -------------------
*/
static int initialize(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8,ENABLE); //开启TIM8定时器的时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOI, ENABLE); //开启GPIOI的时钟
GPIO_PinAFConfig(GPIOI,GPIO_PinSource5,GPIO_AF_TIM8); //PI5复用为TIM8
//GPIO初始化设置
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //模式设为复用
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //复用推挽输出
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOI,&GPIO_InitStructure);
//TIM8初始化
TIM_TimeBaseStructure.TIM_Prescaler = 83; //设置预分频值
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseStructure.TIM_Period = 499; //自动重装载值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//设置时钟分割
TIM_TimeBaseInit(TIM8,&TIM_TimeBaseStructure);
//TIM8 CH1 LED_RED
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //设置为PWM模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //互补输出使能
TIM_OCInitStructure.TIM_Pulse = 0; //设置待装入捕获比较寄存器的脉冲值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //当定时器的值小于脉冲值时,输出低电平
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;
TIM_OC1Init(TIM8, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM8, TIM_OCPreload_Enable); //使能输出比较预装载
TIM_ARRPreloadConfig(TIM8,ENABLE); //使能TIM8自动重装载的预装载寄存器允许位
TIM_Cmd(TIM8, ENABLE); //TIM8使能
TIM_CtrlPWMOutputs(TIM8, ENABLE); //使能主输出
return 0;
}
static int set_compare(int temp)
{
TIM_SetCompare1(TIM8,temp); //修改占空比
return 0;
}
更多回帖