|
#include "pbdata.h"
u16 fre;
void RCC_Configuration(void);
void GPIO_Configuration(void);
void TIM8_Configuration();
void Delay (uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
int main(void)
{
u16 arr=42000;
u16 led_dt = arr/2;
RCC_Configuration(); //系统时钟初始化
GPIO_Configuration();//端口初始化
TIM8_Configuration(arr);//定时器和pwm配置
while(1)
{
TIM_SetCompare3(TIM8,led_dt); //用的是TIM3的通道2,输出PWM 送到相应的寄存器中 //满占空比为900
TIM_SetCompare3(TIM8, 20);
GPIO_SetBits(GPIOB,GPIO_Pin_5); //LED 发光
Delay(0x2ffff);
GPIO_ResetBits(GPIOB,GPIO_Pin_5);//LED 熄灭
Delay(0x2ffff);
}
}
void RCC_Configuration(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM8,ENABLE);//这个是必须的,仿真软件必须的
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//端口复用,一定在APB2的时钟线
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
}
void GPIO_Configuration(void)
{
}
void TIM8_Configuration(arr)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct;
TIM_OCInitTypeDef TIM_OCInitStructure; //PWM的结构体
GPIO_InitTypeDef GPIO_InitStructure;
//PWM
GPIO_InitStructure.GPIO_Pin= GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //通过PWM控制,端口为复用方式输出
GPIO_Init(GPIOC,&GPIO_InitStructure);
//GPIO_PinRemapConfig(GPIO_PartialRemap_TIM1,ENABLE);//TIM3 复用功能部分映射,可以此找到对应的管脚
//关于部分映射可以参考“STM32参考手册”119面
//定时器初始化
TIM_TimeBaseStruct.TIM_Period=arr;//初值
TIM_TimeBaseStruct.TIM_Prescaler=2;//预分频
//不分频,在晶振为72MHz的情况下,定时器执行到899后即会溢出,表示计数满
TIM_TimeBaseStruct.TIM_ClockDivision=0;
TIM_TimeBaseStruct.TIM_CounterMode=TIM_CounterMode_Up;//向上
TIM_TimeBaseInit(TIM8,&TIM_TimeBaseStruct);
//TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
//pwm初始化
//TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1; //使用模式1
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; //使能位
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Disable;
//设置输出极性,一定注意
//TIM_OCInitStructure.TIM_Pulse = 20;
TIM_OC2Init(TIM8,&TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM8,TIM_OCPreload_Enable); //与装载使能,不会说执行一次后就不执行了
TIM_CtrlPWMOutputs(TIM8,ENABLE); //MOE 主输出使能
TIM_ARRPreloadConfig(TIM8, ENABLE);
TIM_Cmd(TIM8,ENABLE);
}
/*PWM不是中断,所以不需要设置中断优先级 */
|
|