继承led,key代码
pwm:(res:自动重装载值,psc:分频值)
步骤:(1)初始化
1.使能PF时钟 RCC_AHB1PeriphClockCmd
2.使能定时器时钟 RCC_APB1PeriphClockCmd
3.设置PF9复用为定时器14 GPIO_PinAFConfig
4.初始化GPIO GPIO_Init
5.初始化定时器14 TIM_TimeBaseInit
6.设置pwm调制 TIM_OC1Init
7.使能预装载寄存器 TIM_OC1PreloadConfig
8.自动装载预装载使能位使能 TIM_ARRPreloadConfig
9.使能定时器 TIM_Cmd
10.编写pwm控制模块,控制led PWM_CtrlLED
pwm.h
#ifndef __PWM_H
#define __PWM_H
#include "stm32f4xx_rcc.h"
void PWM_Init(u32 res,u32 psc );
void PWM_CtrlLED( u16 ledpwm ,u8 chang_flag);
#endif
pwm.c
#include "pwm.h"
#include "delay.h"
#include "key.h "
void PWM_Init(u32 res,u32 psc )
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14,ENABLE);
GPIO_PinAFConfig(GPIOF,GPIO_PinSource9,GPIO_AF_TIM14);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed=GPIO_High_Speed;
GPIO_InitStructure.GPIO_OType=GPIO_OType_PP;
GPIO_Init(GPIOF,&GPIO_InitStructure);
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_Period=res;
TIM_TimeBaseInitStructure.TIM_Prescaler=psc;
TIM_TimeBaseInit(TIM14,&TIM_TimeBaseInitStructure);
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OC1Init(TIM14,&TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM14,TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM14,ENABLE);
TIM_Cmd(TIM14, ENABLE);
}
void PWM_CtrlLED( u16 ledpwm ,u8 chang_flag)
{
PWM_Init(500-1,84-1);
while(1)
{
if(KEY_Scan(1)==KEY2_PRES)
{
delay_ms(10);
if(chang_flag)
{
ledpwm++;
}
else ledpwm--;
if(ledpwm>300)
{
chang_flag=0;
}
if(ledpwm==0)
{
chang_flag=1;
}
TIM_SetCompare1(TIM14,ledpwm);
}
else break;
}
}
main.c
#include "stm32f4xx.h"
#include "usart.h"
#include "delay.h"
#include "led.h"
#include "key.h"
#include "pwm.h"
int main(void)
{
delay_init(168);
LED_Init();
KEY_Init();
u8 key;
u16 ledpwm=0;
u8 chang_flag=1;
LED0(OFF);
LED1(OFF);
while(1)
{
key=KEY_Scan(1);
if(key)
{
switch(key)
{
case KEY0_PRES:
LED0(ON);
LED1(OFF);
break;
case KEY1_PRES:
LED0(OFF);
LED1(ON);
break;
case KEY2_PRES:
PWM_Init(500,84);
PWM_CtrlLED(ledpwm ,chang_flag);
break;
case WKUP_PRES:
LED0(OFF);
LED1(OFF);
break;
}
key=0;
LED_Init();
}
else delay_ms(10);
}
}
|