#include "PWM.h"
#define EN_EXT_OSC 0
#define COMPLEMENT_MODE 0x00000020
#define DEAD_ZONE_INTERVAL 0xC8FF0000
#define PWM_ENABLE 0x01010101
#if EN_EXT_OSC
#define PWM_CLOCK_SOURCE 0x00000000 //使用外部振荡12MHz
#else
#define PWM_CLOCK_SOURCE 0xF0000000 //使用内部RC振荡22.1184MHz
#endif
#define PWM_PRESCALAE 0x0000C731 //PWM01预分频0x31(49),PWM23预分频0xC7(199)
#define PWM_CLOCK_DIVIDER 0x00004444 //输入时钟分频1
#define PWM_OUTPUT_INVERT 0x00040000
#define PWM_OUTPUT_ENABLE 0x0000000F //PWM0、1、2、3输出使能
#define PWM_CMR_VALUE 0x0
#define PWM_CNR_VALUE 0x1000 //4096
/*
PWM频率=PWMxy_CLK/(prescale+1)*(clock divider)/(CNR+1)
(1)使用外部晶振12MHz
PWM频率=12000000/(49+1)*4097 =58.57Hz
(2)使用内部RC振荡22.1184MHz
PWM频率=22118400/(49+1)*4097 =107.97Hz
*/
#define LED_DARKING 0
#define LED_BRIGHTING 1
STATIC UINT32 g_unPWMCMRValue=PWM_CNR_VALUE;
STATIC UINT32 g_unLedStat=LED_DARKING;
/****************************************
*函数名称:PWMInit
*输 入:无
*输 出:无
*功 能:PWM初始化
******************************************/
VOID PWMInit(VOID)
{
P2_MFP |= ~(P20_AD8_PWM0 | P21_AD9_PWM1 | P22_AD10_PWM2 | P23_AD11_PWM3);
P2_MFP |= (PWM0 | PWM1 | PWM2 | PWM3); //使能P2.0~P2.3为PWM输出
P2_PMD &= ~Px0_PMD; //配置P2.0~P2.3为推挽输出
P2_PMD |= Px0_OUT;
P2_PMD &= ~Px1_PMD;
P2_PMD |= Px1_OUT;
P2_PMD &= ~Px2_PMD;
P2_PMD |= Px2_OUT;
P2_PMD &= ~Px3_PMD;
P2_PMD |= Px3_OUT;
APBCLK |= PWM01_CLKEN | PWM23_CLKEN; //使能PWM0~3时钟
CLKSEL1 = PWM_CLOCK_SOURCE; //选择PWM0~3时钟源
PPRA = PWM_PRESCALAE | DEAD_ZONE_INTERVAL; //选择PWM0~3时钟预分频和死区间隔
CSRA = PWM_CLOCK_DIVIDER; //选择PWM0~3时钟分频
PCRA = 0x08080808 | PWM_OUTPUT_INVERT | COMPLEMENT_MODE; //PWM0~3自动重装载
CNR0A = CNR1A = CNR2A = CNR3A = PWM_CNR_VALUE; //PWM0~3计数值
CMR0A = CMR1A = CMR2A = CMR3A = PWM_CMR_VALUE; //PWM0~3比较值
PIERA |= PWMIE3 | PWMIE2 | PWMIE1 | PWMIE0 ; //使能PWM0~3中断
NVIC_ISER |= PWMA_INT; //使能PWM0~3中断
POEA = PWM_OUTPUT_ENABLE; //PWM输出使能
PCRA |= PWM_ENABLE; //PWM使能,启动
}
/****************************************
*函数名称:PWMA_IRQHandler
*输 入:无
*输 出:无
*功 能:中断服务函数-PWMA
******************************************/
VOID PWMA_IRQHandler(VOID)
{
switch(g_unLedStat) //检查LED状态
{
case LED_DARKING: //LED状态渐暗
{
if(g_unPWMCMRValue < PWM_CNR_VALUE)
{
g_unPWMCMRValue+=50;
}
else
{
g_unLedStat = LED_BRIGHTING;
g_unPWMCMRValue=PWM_CNR_VALUE;
}
}break;
case LED_BRIGHTING: //LED状态渐亮
{
if(g_unPWMCMRValue>=50)
{
g_unPWMCMRValue-=50;
}
else
{
g_unLedStat = LED_DARKING;
g_unPWMCMRValue=PWM_CMR_VALUE;
}
}break;
default:break;
}
CMR0A = CMR1A = CMR2A = CMR3A = g_unPWMCMRValue; //设置PWM0~3比较值
PIIRA = PIIRA;
}
/****************************************
*函数名称:main
*输 入:无
*输 出:无
*功 能:函数主体
******************************************/
INT32 main(VOID)
{
PROTECT_REG //ISP下载时保护FLASH存储器
(
PWRCON |= XTL12M_EN; //默认时钟源为外部晶振
while((CLKSTATUS & XTL12M_STB) == 0); //等待12MHz时钟稳定
CLKSEL0 = (CLKSEL0 & (~HCLK)) | HCLK_12M; //设置外部晶振为系统时钟
PWMInit(); //PWM初始化
)
while(1);
}
|