#include "pwm.h"
void pwm_init(u16 psc,u16 arr)
{
GPIO_InitType GPIO_InitStructure;
TIM_TimeBaseInitType TIM_TimeBaseInitStruct;
OCInitType TIM_OCInitStruct;
//开时钟
RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOA);
RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_TIM8);
RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_AFIO);
//TIM8_CH1引脚初始化
GPIO_InitStructure.GPIO_Mode = GPIO_MODE_AF_PP;
GPIO_InitStructure.GPIO_Current = GPIO_DS_4MA;
GPIO_InitStructure.Pin=GPIO_PIN_2;
GPIO_InitStructure.GPIO_Alternate=GPIO_AF9_TIM8;
GPIO_Peripheral_Initialize(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseInitStruct.CntMode=TIM_CNT_MODE_UP;//向上计数
TIM_TimeBaseInitStruct.ClkDiv=0;//不分频
TIM_TimeBaseInitStruct.Period=arr;
TIM_TimeBaseInitStruct.Prescaler=psc;
TIM_Base_Initialize(TIM8,&TIM_TimeBaseInitStruct);
TIM_OCInitStruct.OcMode=TIM_OCMODE_PWM2;//PWM模式2
TIM_OCInitStruct.OutputState=TIM_OUTPUT_STATE_ENABLE;//使能PWM输出
TIM_OCInitStruct.OcPolarity=TIM_OC_POLARITY_HIGH;//高电平有效
TIM_OCInitStruct.Pulse=0;
TIM_Output_Channel1_Initialize(TIM8,&TIM_OCInitStruct);
TIM_On(TIM8);
TIM_PWM_Output_Enable(TIM8);
}
#include "n32g430.h"
#include "delay.h"
#include "pwm.h"
int main()
{
u16 led0pwmval=0;
pwm_init(6399,1000);
while(1)
{
delay_ms(10);
led0pwmval++;
TIM_Compare1_Set(TIM8,led0pwmval);
}
}
|