代码非常简单,根据官方例子移植到 Arduino 完成。使用 P2.5 引脚,Ch55xduino 编译:
#define SetPWMClk(CK_SE) (PWM_CK_SE = CK_SE) //分频,默认时钟Fsys
#define SetPWMCycle(Cycle) (PWM_CYCLE = Cycle) //设置循环周期
#define SetPWM1Dat(dat) (PWM_DATA = dat) //设置PWM输出占空比
#define SetPWM2Dat(dat) (PWM_DATA2 = dat)
/*******************************************************************************
* Function Name : InitPWM2(UINT8 polar)
* Description : PWM初始化函数
* Input : polar=0选择默认低电平,高电平输出有效;
polar=1选择默认高电平,低电平输出有效;
* Output : None
* Return : None
*******************************************************************************/
void InitPWM2(uint8_t polar)
{
PWM_CTRL &= ~bPWM_CLR_ALL; //清空FIFO和计数
PWM_CTRL &= ~bPWM_MOD_MFM;
PWM_CTRL |= bPWM_IE_END; //使能PWM计数周期完成中断
PWM_CTRL |= bPWM2_OUT_EN; //PWM2输出使能
PWM_CTRL |= bPWM_IF_END; //清除所有的中断标志
if(polar){
PWM_CTRL |= bPWM2_POLAR; //低电平有效
}
else{
PWM_CTRL &= ~bPWM2_POLAR; //高电平有效
}
}
void setup() {
// put your setup code here, to run once:
SetPWMClk(12); //设置PWM1&2的时钟分频系数为12
InitPWM2(0); //PWM2初始化,高电平有效
SetPWMCycle(1000); //设置循环周期100
SetPWM2Dat(50); //PWM1占空比设置50/100
}
void loop() {
// put your main code here, to run repeatedly:
}