/*---------------------------------------------------------------------------------------------------------*/
/* */
/* Copyright(c) 2010 Nuvoton Technology Corp. All rights reserved. */
/* */
/*---------------------------------------------------------------------------------------------------------*/
/***************************************************************************************
M051 PWM demo代码,PWM通道0~3(P2.0~3)会输出设定的PWM波形。
****************************************************************************************/
void SystemInit (void) {}
#include "common.h"
#define DEAD_ZONE_INTERVAL 0xC8FF0000
#define PWM_PRESCALAE 0x0000C763
#define PWM0_Period 0x1000 //pwm0周期
#define PWM1_Period 0x1000 //pwm1周期
#define PWM2_Period 0x1000 //pwm2周期
#define PWM3_Period 0x1000 //pwm3周期
#define PWM0_duty 0x800 //pwm0占空比
#define PWM1_duty 0x800 //pwm1占空比
#define PWM2_duty 0x400 //pwm2占空比
#define PWM3_duty 0x400 //pwm3占空比
/***************************************************************************************
描述 : PWM中断处理函数
****************************************************************************************/
void PWMA_IRQHandler(void)
{
PIIRA = PIIRA; //清除PWM中断标志
}
int main(void)
{
Un_Lock_Reg(); //解锁被保护的寄存器位,以便用户访问
PWRCON |= XTL12M_EN; //使能外部12MHz晶振
while((CLKSTATUS & XTL12M_STB) == 0); //等12M晶振时钟稳定
CLKSEL0 = (CLKSEL0 & (~HCLK)) | HCLK_12M; //选外部12MHz晶振为系统时钟
//CLKSEL0 &= (~HCLK);
//CLKSEL0 |= HCLK_12M;;
Lock_Reg();
//重新锁被保护的寄存器位
P3_PMD |= (1<<12); //P3.6 out mode
P3_DOUT |= (1<<6);
P2_MFP &= ~(P20_AD8_PWM0 |
P21_AD9_PWM1 |
P22_AD10_PWM2|
P23_AD11_PWM3);
P2_MFP |= (PWM0 | PWM1 | PWM2 | PWM3); //设置P2.0~3为PWM0~3功能
P2_PMD &= ~(Px0_PMD | Px1_PMD | Px2_PMD | Px3_PMD);
P2_PMD |= (Px0_OUT | Px1_OUT | Px2_OUT | Px3_OUT); //设置P2.0~3为推挽输出模式
APBCLK |= (PWM01_CLKEN | PWM23_CLKEN); //使能PWM0,1和PWM2,3时钟
CLKSEL1 = CLKSEL1 & (~(PWM01_CLK | PWM23_CLK));
CLKSEL1 |= (PWM01_12M | PWM23_12M); //选择外部12MHz晶振输入作为PWM0,1和PWM2,3时钟源
PPRA = PWM_PRESCALAE | DEAD_ZONE_INTERVAL; //设置PWM0,1和pWM2,3时钟预分频值和PWM2,3死区长度
CSRA = CSRA & (~(CSR0 | CSR1 | CSR2 | CSR3));
CSRA |= (CSR0_CLK_2|CSR1_CLK_4|CSR2_CLK_8|CSR3_CLK_16); //设置PWM0~3时钟分频值
PCRA |= (CH2INV_ON | DZEN23); //设定PWM2,3为互补输出模式,并且PWM2反向
PCRA |= (CH0_AU_RL | CH1_AU_RL | CH2_AU_RL | CH3_AU_RL); //设定PWM0,1,2,3为自动重载模式
//CNR0A = CNR1A = CNR2A = CNR3A = 0x1000; //设定PWM0,1,2,3周期
CNR0A=PWM0_Period;
CNR1A=PWM1_Period;
CNR2A=PWM2_Period;
CNR3A=PWM3_Period;
//CMR0A = CMR1A = 0x800; //设定PWM0,1高占空比50%
CMR0A=PWM0_duty;
CMR1A=PWM1_duty;
//CMR2A = CMR3A = 0x400; //设定PWM2,3高占空比25%
CMR2A=PWM2_duty;
CMR3A=PWM3_duty;
PIERA |= (PWMIE0 | PWMIE1 | PWMIE2 | PWMIE3); //使能PWM0~3中断
NVIC_ISER = PWMA_INT; //使能NVIC PWMA中断向量
POEA |= (PWM0_OE | PWM1_OE | PWM2_OE | PWM3_OE); //输出使能
PCRA |= (CH0EN | CH1EN | CH2EN | CH3EN); //使能PWM计数器开始计数
while(1);
return 1;
}
|